我正在尝试从我的firebase数据库实时更新listview。数据上传到数据库没有任何问题,并且显示新添加的数据的toast也可以工作。但我无法让listview工作。这是我的代码:
public class MainActivity extends AppCompatActivity {
private ListView list;
private Button btnadd;
private EditText ettext;
private DatabaseReference mDatabase;
private ArrayList<String> arrayList= new ArrayList<>();
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=findViewById(R.id.liston);
list.setAdapter(adapter);
btnadd=findViewById(R.id.button);
ettext=findViewById(R.id.ed);
btnadd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDatabase.push().setValue(ettext.getText().toString());
}
});
mDatabase= FirebaseDatabase.getInstance().getReference();
adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String string =dataSnapshot.getValue(String.class);
arrayList.add(string);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
"Name: " + dataSnapshot.getValue(), Toast.LENGTH_LONG)
.show();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String string =dataSnapshot.getValue(String.class);
arrayList.remove(string);
adapter.notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
数据库的更新也是在应用程序中使用“edittext”和按钮进行的。