【发布时间】:2019-04-13 00:43:02
【问题描述】:
我的 recyclerview 从 json api 获取数据并填充文章列表。我现在已经在 firebase 实时数据库的帮助下实现了一个评论系统。我想在 recyclerview 中的每篇文章图片下方显示 cmets 的数量。我尝试了几种方法来实现,但都不是很有效。
-
起初我为每个视图实现了基于文章唯一 ID 的数据库查询,但由于 recyclerview 有超过 100 篇文章,因此它对数据库进行了 100 多个实例调用,并导致了巨大的带宽问题。
李> 然后我进行了一次查询以从数据库中获取所有 cmets 计数并将它们本地保存在 SQLite 数据库中,在 recyclerview 中我查询 SQLite 数据库以获取 cmets 计数但在 SQLite 中插入 100 行具有文章 id 和 cmets 计数的速度很慢.
对于这样的任务,我会花费最少的带宽并获得评论计数,你们推荐什么最佳方法?
我的数据库结构是这样的。
获取cmets方法
public void getComments() {
keyrf = FirebaseDatabase.getInstance().getReference().child("Keys");
keyrf.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
HashMap map = new HashMap();
for( DataSnapshot child : dataSnapshot.getChildren() ) {
String childKey = child.getKey();
String c = child.child("c").getValue().toString();
map.put(childKey, c);
addComments(MainActivity.this, childKey, c);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
插入 cmets 方法
public static void addComments(Context context, String childKey, String c) {
try {
SQLiteDatabase myDB = context.openOrCreateDatabase("MyDb", Context.MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS comments (articleId INTEGER not null unique, comment INTEGER not null)");
String sql = "REPLACE INTO comments (articleId, comment) VALUES (?, ?)";
SQLiteStatement statement = myDB.compileStatement(sql);
statement.bindString(1, childKey);
statement.bindString(2, c);
statement.execute();
} catch (Exception e) {
}
}
【问题讨论】:
标签: android firebase firebase-realtime-database android-recyclerview android-sqlite