我有一個代碼: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