我有一个代码:Android的ListView的更新项目,火力地堡数据库
@Override
protected void onCreate(Bundle savedInstanceState) {
.........
listViewMyAccountSettings = (ListView) findViewById(R.id.listViewMyAccountSettings);
arrayList = new ArrayList();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
listViewMyAccountSettings.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
listViewMyAccountSettings.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
showAlertUsername();
} else if (position == 1){
showAlertAge();
}
......................
}
});
.................
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("userdata").child(myEmail).child("username");
myRef.addValueEventListener(new ValueEventListener() {
@SuppressLint("SetTextI18n")
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
username = dataSnapshot.getValue(String.class);
arrayList.add("Your username: " + username);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG", "Failed to read value.", error.toException());
}
});
有showAlertUsername方法:
private void showAlertUsername() {
alertDialogBuilder = new AlertDialog.Builder(
MyAccountSettings.this);
input = new EditText(MyAccountSettings.this);
lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialogBuilder.setView(input);
alertDialogBuilder.setPositiveButton("Discard",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "No changes were made",
Toast.LENGTH_SHORT).show();
}
});
alertDialogBuilder
.setTitle("USERNAME")
.setMessage("Enter new username")
.setCancelable(false)
.setNegativeButton("Change",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (!input.getText().toString().isEmpty()) {
mDatabase.child("userdata").child(myEmail).child("username").setValue(input.getText().toString());
Toast.makeText(getApplicationContext(), "Your username was changed successfully",
Toast.LENGTH_LONG).show();
listViewMyAccountSettings.invalidateViews();
} else {
Toast.makeText(getApplicationContext(), "Username can't be empty. No changes were made",
Toast.LENGTH_LONG).show();
}
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
我要更新列表视图特定领域当我改变值(和将其设置为数据库)。问题是,当我更改数据库中的值时,它会添加一个新项目以新值显示列表视图?有没有办法在不重新启动活动的情况下更新旧的?谢谢。
是的,我想到了他的方式,但我有3种onDataChange方法,因为我已经在数据库3个字段更新(用户名,年龄和性别),因此这将删除2个项目,只有1将在阵列 – Samo
留也许listview不是你的用例的理想组件。或者,您可以听取基础'.child(myEmail)'表上的更改并获取您感兴趣的3个字段中的一个更改事件。 – Natan