简体   繁体   中英

How to delete data(particular node of json) from realtime database in Firebase in android app

I build a Todo list app in that i have onClick listener (named as delteTask).I want to remove my data in firebase when the delete button is clicked.I have got the database refrence as i checked in documentation that to delete a node you can make use of removeValue() method.But i don't understand how to use it.I have written the code as well,Please help me in this.

**MY MAINACTIVTY>JAVA**
package com.example.manuj.todolist;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    String tasks;

    FirebaseDatabase db=FirebaseDatabase.getInstance();
    DatabaseReference rootRef=db.getReference();
    DatabaseReference dataRef=rootRef.child("Todo");


    TextView textView;
    Button button;
    ListView listView;
    ArrayAdapter mAdapter;

    ArrayList<String> arrayList=new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button=findViewById(R.id.button);
        textView=findViewById(R.id.textView);
        listView=findViewById(R.id.listView);


        mAdapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.textView,arrayList);
        listView.setAdapter(mAdapter);


        dataRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                String value=dataSnapshot.getValue().toString();
                try {
                    JSONObject object=new JSONObject(value);
                    tasks=object.getString("Task");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                arrayList.add(tasks);
                mAdapter.notifyDataSetChanged();
            }

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

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

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

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.addTask:
                final EditText editText=new EditText(this);
                AlertDialog dialog=new AlertDialog.Builder(this)
                        .setTitle("Add new Task")
                        .setMessage("What's your Task?")
                        .setView(editText)
                        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String task= editText.getText().toString();
                                HashMap<String,String> todoMap=new HashMap<String, String>();
                                todoMap.put("Task",task);
                                dataRef.push().setValue(todoMap);

                            }
                        })
                        .setNegativeButton("CANCEL",null).create();
                dialog.show();
                return true;
        }
        return super.onOptionsItemSelected(item);

    }
    public void deleteTask(View view) {

        DatabaseReference removeRef=FirebaseDatabase.getInstance().getReference("Todo");
        removeRef.removeValue();//the problem i n using the above is it removes my all data,but how
        //do i  remove a particular.

    }
}

You need the key to the record you are trying to access. It would be helpful to see how the Json is structured.

DatabaseReference removeRef=FirebaseDatabase.getInstance().getReference("Todo").child("RECORD KEY").removeValue();

I'm answering my question itself hehe,But it took my time to identify the problem.So,iam not deleting the question and letting the people to know the answer of such type of problem so they don't face the same problem as i did.

Ok here is the answer

public void deleteTask(View view) {
        int index=listView.getPositionForView(view);
        String str= (String) mAdapter.getItem(index++);

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        Query taskQuery = ref.child("Todo").orderByChild("Task").equalTo(str);
        taskQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
                    appleSnapshot.getRef().removeValue();
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e("TAG", "onCancelled", databaseError.toException());
            }
        });
        mAdapter.notifyDataSetChanged();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM