我想从类别键内的键中获取所有值。
我正在使用AndroidX,Gradle 5.1.1,并且正在使用以下结构:
db-name
category1
unique_random_id: value
unique_random_id2: value_value
category2
unique_random_id: value
unique_random_id2: value_value
ListView lv;
FirebaseDatabase fb;
DatabaseReference dr;
ArrayList<Article> list;
ArrayAdapter<Article> adapter;
Article article;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articlelist);
Intent intent = getIntent();
Bundle gotExtras = intent.getExtras();
final TextView articleCatShow = (TextView)findViewById(R.id.articleCatShow);
articleTopCat.setText(gotExtras.getString("cat"));
article = new Article();
lv = (ListView)findViewById(R.id.listView);
fb = FirebaseDatabase.getInstance();
dr = fb.getReference(gotExtras.getString("cat"));
list = new ArrayList<>();
adapter = new ArrayAdapter<Article>(this, R.layout.article_each, R.id.articleTxt, list);
dr.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()) {
adapter.add(ds.getValue(Article.class));
lv.setAdapter(adapter);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Gradle依赖关系:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.firebase:firebase-analytics:17.2.0'
implementation 'com.google.firebase:firebase-core:17.2.0'
implementation 'com.google.firebase:firebase-database:19.1.0'
}
我希望listview有数据。
当我运行应用程序并按将与Extras
Can't convert an object of type java.lang.String to type <my-hidden-package-name>
一起使用的按钮时,我也收到此错误 最佳答案
更改此:
dr.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()) {
adapter.add(ds.getValue(Article.class));
lv.setAdapter(adapter);
}
}
到这个:
dr.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
adapter.add(dataSnapshot.getValue(Article.class));
lv.setAdapter(adapter);
}
}
删除
for
循环,因为在进行迭代时,您检索的是String
类型的值,而不是包的类型。关于java - 如何从Firebase Realtime DB的 key 中获取所有值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58005065/