我尝试从Firebase数据库填充我的Android应用中的ListView
。我正在使用(以及后续存储我的图像)。我将记录放入数据库没有问题,但是检索信息并填充我的ListView被证明是棘手的。这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adminfeed);
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl("https://bookstore-30213.firebaseio.com/All_Books");
final ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String>(this, R.layout.listview_layout);
list = (ListView) findViewById(R.id.listView);
adapter = new CustomListAdapter(AdminFeed.this, bookModelList);
list.setAdapter(adapter);
}
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("All_Books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject book = jsonArray.getJSONObject(i); //something goes wrong here, i think its possibly with the size of the reading
Book newBook = new Book();
newBook.setTitle(book.getJSONObject("title").getString("title"));
newBook.setImageURL(book.getString("imageURL"));
newBook.setAuthor(book.getJSONObject("author").getString("author"));
// adding event to events array
bookModelList.add(newBook);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
它返回了我的书籍模型列表&#39;是空的,但我不知道为什么我要明确地添加一本书。关于我出错的地方的任何指示?
答案 0 :(得分:2)
要解决此问题,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference allBooksRef = rootRef.child("All_Books");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Book> bookModelList = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Book book = ds.getValue(Book.class);
bookModelList.add(book);
}
ListView list = (ListView) findViewById(R.id.listView);
CustomListAdapter adapter = new CustomListAdapter(AdminFeed.this, bookModelList);
list.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
allBooksRef.addListenerForSingleValueEvent(valueEventListener);
请注意,无需使用JSONObject
即可从Firebase数据库获取数据。