6

This is my database:

{
  "UID1" : {
    "KEY" : {
      "Name" : "name1",
      "Email" : "something1@something.com",
      "userid" : "UID1"
    }
  },
  "UID2" : {
    "KEY2" : {
      "Name" : "name1",
      "Email" : "something1@something.com",
      "userid" : "UID2"
    },
    "KEY3" : {
      "Name" : "name2",
      "Email" : "something2@something.com",
      "userid" : "UID2"
    },
    "KEY4" : {
      "Name" : "name3",
      "Email" : "something3@something.com",
      "userid" : "UID2"
  }
}

I would like to update and delete data which for example would be at the position of "KEY2".

How can I achieve this? I have not yet tried any code in Android.

Rodrigo Ehlers
  • 1,830
  • 11
  • 25
Danny boy
  • 63
  • 1
  • 1
  • 6

2 Answers2

14

To write single data you can use the setValue() method on your DatabaseReference with your child Id's:

private void writeNewData(String userId, String name, String email) {
    User user = new User(name, email);    
    mDatabase.child("users").child(userId).setValue(user);
}

In your case you can do something like: mDatabase.child("UID2").child("KEY2").setValue(yourNewValueOrObject);

If you want to update a specific value, you should be more concise: mDatabase.child("UID2").child("KEY2").child("email").setValue(newEmail);

Anyway I recomend you to use custom classes as POJO's(Plain Old Java Object) with the values of each of your items in database. For example:

public class User {

    public String username;
    public String email;

    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public User(String username, String email) {
        this.username = username;
        this.email = email;
    }

}

Finally to remove data you should use the removeValue() method in the same way.

  private void deleteUserData(String userId) {           
        mDatabase.child("users").child(userId).removeValue();
    }

This method will remove the whole reference from your Database, so be care with it. In the case that you wanted to remove a specific field, you should add another .child() call to the tree. For example, let's say that we want to remove the email value from "KEY2" node: mDatabase.child("users").child(userId).child("email").removeValue();

Finally, there's the case that maybe we want to update multiple fields in different database nodes. In that case we should use the updateChildren() method with a map of references and values.

private void writeNewPost(String userId, String username, String title, String body) {
   // Create new post at /user-posts/$userid/$postid and at
   // /posts/$postid simultaneously
   String key = mDatabase.child("posts").push().getKey();
   Post post = new Post(userId, username, title, body);
   Map<String, Object> postValues = post.toMap();

   Map<String, Object> childUpdates = new HashMap<>();
   childUpdates.put("/posts/" + key, postValues);
   childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

   mDatabase.updateChildren(childUpdates);
}

What updateChildren method do. Is a setValue () call over each row in the given Map<String, Object> being the key the full reference of the node and the Object the value.

You can read more update and delete data in the official Firebase documentation

Francisco Durdin Garcia
  • 12,540
  • 9
  • 53
  • 95
  • 1
    Regarding the removal. I want to say for example remove all data from KEY2 how can I do that? – Danny boy Jan 26 '17 at 10:14
  • 1
    Remove the whole Reference from "KEY2": `mDatabase.child("UID2").child("KEY2").removeValue();` – Francisco Durdin Garcia Jan 26 '17 at 10:16
  • 1
    `removeValue()` remove the whole reference. You don' need to add "KEY2" as a parammeter, anyway, you can't. In the case that you want to remove a single value INSIDE "KEY2" You should do: `mDatabase.child("UID2").child("KEY2").child(email).removeValue();` – Francisco Durdin Garcia Jan 26 '17 at 10:18
  • Great thanks. I will give both of the solution a try and keep you updated – Danny boy Jan 26 '17 at 10:24
  • I added more information to the post, like how to update data from multiple nodes at once. Anyway I recommend you to pause and read the documentation of firebase to learn how to work with it: https://firebase.google.com/docs/database/android/read-and-write Don't forget to flag the answers and comments to make easier the search for more people with the same questions than you ;) – Francisco Durdin Garcia Jan 26 '17 at 10:26
  • Will do. Just trying out the solutions. Thanks for the detailed answer btw. – Danny boy Jan 26 '17 at 10:37
  • This might sound silly because the code you provided to update data looks correct however, the data is not being updated in Firebase. I have checked using Log.d and the uID and pushId matches to that of data in database. – Danny boy Jan 26 '17 at 10:43
  • I am writing data as you have suggested, passing values as parameters in the constructor. – Danny boy Jan 26 '17 at 10:45
  • Update your code above, anyway, check first that your FirebaseRules doesn't requiere any condition like a logged user or something like that: https://firebase.google.com/docs/database/security/?hl=en – Francisco Durdin Garcia Jan 26 '17 at 10:45
  • Sorry silly me, I was passing the same value instead of the new ones and thats why it didn't update them. Works fine now. will try the remove from database. Thanks again – Danny boy Jan 26 '17 at 10:50
  • Great! both work. Accepted but I need 15 rep to vote up :( Can I ask currently when item get deleted from the database it does not automatically disappear from my application. I think the reclyerview does not get updated. Do you know how it can be fixed? – Danny boy Jan 26 '17 at 11:02
  • You should use a `onChildEvent` in your `RecyclerView`, that Listener will update each one of your childrens individually. Instead of make a full query again and reload the full `adapter`, which is pretty bad in performance and user experience. – Francisco Durdin Garcia Jan 26 '17 at 11:06
  • I am not sure where I should write that. My code looks like this: http://paste.ofcode.org/ZqTKxgghBXe6xWzx6gafdC – Danny boy Jan 26 '17 at 11:13
  • You should ask that in other question. Anyway debug your code in the `fetchData` method, there's your problem I think. – Francisco Durdin Garcia Jan 26 '17 at 11:26
  • I have asked the question here: http://stackoverflow.com/questions/41872655/data-from-firebase-does-not-automatically-get-updated-on-reclyerview-android please can you see if you can find a solution – Danny boy Jan 26 '17 at 11:39
  • @FranciscoDurdinGarcia have a look at this too please: http://stackoverflow.com/q/41842681/6144372 – Hammad Nasir Jan 26 '17 at 14:57
-3

This is the complete code to insert , delete, updatte and select from firebase database manually. addvalueListner() is justt used to get all values from database at begining in oncreate().

public class MainActivity extends AppCompatActivity {

    EditText e1,e2,e3;
    Button b1,b2;
    int i;
   static int p=0;
    String key,s1,s2,s3;
    DatabaseReference databaseReference;
    DataSnapshot dsp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        e1=findViewById(R.id.editText);
        e2=findViewById(R.id.editText2);
        e3=findViewById(R.id.editText3);
        b1=findViewById(R.id.button);
        b2=findViewById(R.id.button2);
        databaseReference= FirebaseDatabase.getInstance().getReference().child("mydata");


        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            dsp=dataSnapshot;

          }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
   }

    public void selectdata(View view) {
                   s3=e3.getText().toString();
                    String s=dsp.child(s3).getValue().toString();
                    Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();

              }

    public void removedata(View view) {

        s3=e3.getText().toString();
        databaseReference.child(s3).removeValue();
        Toast.makeText(MainActivity.this, "remove data", Toast.LENGTH_SHORT).show();

    }

    public void insertperticul(View view) {

        p=0;

      s1=e1.getText().toString();
      s2=e2.getText().toString();
      s3=e3.getText().toString();

       for(DataSnapshot childdata: dsp.getChildren())
       {
           key=childdata.getKey().toString();
            if(s3.equals(key))
            {
                p=1;
                Toast.makeText(this, "User exist", Toast.LENGTH_SHORT).show();
                break;
            }

       }
       if(p==0)
       {
           User user=new User(s1,s2);
           databaseReference.child(""+s3).setValue(user);
       }
    }

    public void updatedata(View view) {

        s1=e1.getText().toString();
        s2=e2.getText().toString();
        s3=e3.getText().toString();
        for(DataSnapshot childdata: dsp.getChildren())
        {
            key=childdata.getKey().toString();
            if(s3.equals(key))
            {

                User user=new User(s1,s2);
                databaseReference.child(""+s3).setValue(user);

                Toast.makeText(this, "data updated", Toast.LENGTH_SHORT).show();
                break;
            }

        }
    }
}



public class User {
    String name;
    String email;

    public User()
    {

    }
    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:layout_editor_absoluteY="81dp">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="39dp"
        android:ems="10"
        android:hint="enetr name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:hint="enter email"
        android:inputType="textPersonName"
        app:layout_constraintStart_toStartOf="@+id/editText"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="selectdata"
        android:text="Select"
        app:layout_constraintBaseline_toBaselineOf="@+id/button"
        app:layout_constraintEnd_toEndOf="@+id/editText3" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="19dp"
        android:onClick="removedata"
        android:text="Remove"
        app:layout_constraintBottom_toTopOf="@+id/button6"
        app:layout_constraintStart_toStartOf="@+id/button" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="19dp"
        android:onClick="insertperticul"
        android:text="Insert"
        app:layout_constraintBottom_toTopOf="@+id/button6"
        app:layout_constraintStart_toStartOf="@+id/button2" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="19dp"
        android:ems="10"
        android:hint="Enetr Id"
        android:inputType="textPersonName"
        app:layout_constraintStart_toStartOf="@+id/editText2"
        app:layout_constraintTop_toBottomOf="@+id/editText2" />

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="60dp"
        android:onClick="updatedata"
        android:text="Update"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>