Android ListView更新项,Firebase数据库

时间:2017-07-17 17:49:58

标签: android listview firebase firebase-realtime-database

我有一个代码:

@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();
}

当我更改值(并将其设置为数据库)时,我想更新列表视图中的特定字段。问题是,当我在数据库中更改值时,它会向列表视图中添加一个具有新值的新项目?有没有办法在不重新启动活动的情况下更新旧的?感谢。

4 个答案:

答案 0 :(得分:0)

每次更改firebase数据时,都会在列表中添加一个新项目:

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    List<Patch> patches = parseJson(); // Parse the JSON file and get the patches
    for (Patch patch : patches) {
        int databaseVersion = patch.getVersion();
        if (databaseVersion > oldVersion && databaseVersion <= newVersion) {
            for (String command : patch.getCommands()) {
                database.execSQL(command);
            }
        }
    }
}

如果您想要一个条目,请在此之前清除列表。

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);
}

答案 1 :(得分:0)

如果您当前的ArrayList包含,您将更改数据,否则只需添加新数据:

public void onDataChange(DataSnapshot dataSnapshot) {
    username = dataSnapshot.getValue(String.class);
    String item = "Your username: " + username;

    if(arrayList.contains(item)) {
        //if current arrayList contains the item just change it
        arrayList.set(arrayList.indexOf(item), item);
    } else {
        //otherwise add the new one
        arrayList.add(item);
    } 
    //assuming your data is mutable
    arrayAdapter.notifyDataSetChanged();
}

答案 2 :(得分:0)

使用ChildEventListener而不是ValueEventListener.ChildEventListener提供以下方法,

    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
     // here in dataSnapshot you will the detail for which the value is changed,using this you can update the list. 
     }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {}

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {}

    @Override
    public void onCancelled(DatabaseError databaseError) {}

答案 3 :(得分:0)

@Priya感谢您使用过的一段答案,代码现在看起来就是这样,它正在做它应该做的事情。

FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("userdata").child(myEmail);
    myRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
            if (dataSnapshot.getKey().equals("username")) {
                username = (String) dataSnapshot.getValue();
                arrayList.add("Username: " + username);
            } else if (dataSnapshot.getKey().equals("age")) {
                age = (String) dataSnapshot.getValue();
                arrayList.add("Age: " + age);
            } else if (dataSnapshot.getKey().equals("gender")) {
                gender = (String) dataSnapshot.getValue();
                arrayList.add("Gender: " + gender);
            }
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
            if (dataSnapshot.getKey().equals("username")) {
                username = (String) dataSnapshot.getValue();
                arrayList.set(2, "Username: " + username);
            } else if (dataSnapshot.getKey().equals("age")) {
                age = (String) dataSnapshot.getValue();
                arrayList.set(0, "Age: " + age);
            } else if (dataSnapshot.getKey().equals("gender")) {
                gender = (String) dataSnapshot.getValue();
                arrayList.set(1, "Gender: " + gender);
            }
            arrayAdapter.notifyDataSetChanged();
        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {}
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });