如何在Android应用程序的Firebase中从实时数据库中删除数据(json的特定节点)

时间:2018-08-17 16:21:30

标签: android firebase

我构建了一个Todo列表应用程序,因为我具有onClick侦听器(名为delteTask)。当我单击删除按钮时,我想在Firebase中删除我的数据。我在检查要删除的文档时得到了数据库引用一个节点,您可以使用removeValue()方法。但是我不知道如何使用它。我也已经编写了代码,请为此提供帮助。

**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.

    }
}

2 个答案:

答案 0 :(得分:0)

您需要尝试访问的记录的密钥。看看Json的结构将很有帮助。

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

答案 1 :(得分:0)

我自己回答问题,但是花了我一些时间才能确定问题。因此,不要删除问题,让人们知道此类问题的答案,这样他们就不会面对相同的问题像我一样。

好的,这就是答案

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