我正在使用Android Studio开发应用,并使用Firebase来存储/检索数据。这样可以正常工作,但是当我将检索到的数据保存到局部变量然后尝试在列表视图中显示数据时,它才会刷新视图。
这是我的OnCreate功能:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_chores);
//get database reference and user data
mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl("https://...");
user = (User) getIntent().getSerializableExtra("user");
configureBackButton();
updateFromFirebase();
display();
}
这是更新功能(变量图是全局变量):
private void updateFromFirebase() {
final ArrayList<String> list;
final String name = user.getName().toLowerCase();
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot child : snapshot.getChildren()) {
ArrayList<String> list;
String name;
name = child.getKey();
list = (ArrayList)child.getValue();
map.put(name.toLowerCase(), list);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
...
}
});
list = map.get(name);
if(list==null) return;
final ListView list_xml = (ListView) findViewById(R.id.list);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
list_xml.setAdapter(adapter);
}
这是显示功能:
private void display() {
final ArrayList<String> list;
final String name = user.getName().toLowerCase();
list = map.get(name);
if(list==null) return;
final ListView list_xml = (ListView) findViewById(R.id.list);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
list_xml.setAdapter(adapter);
list_xml.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = adapter.getItem(position);
list.remove(item);
map.put(name, list);
CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
Snackbar sb = Snackbar.make(coordinatorLayout, "Item Removed!", Snackbar.LENGTH_SHORT);
sb.show();
adapter.notifyDataSetChanged();
}
});
}
对于第一次不显示原因的任何见解都将不胜感激。
答案 0 :(得分:2)
由于valueEventListener是一个异步函数,它可能不会立即得到结果,所以我认为如果更新数据更新(onDataChange)将会更好
@Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot child : snapshot.getChildren()) {
ArrayList<String> list;
String name;
name = child.getKey();
list = (ArrayList)child.getValue();
map.put(name.toLowerCase(), list);
}
//this is displaying result whenever change occurs
display();
}