如何从 Android 中的 Firebase 实时数据库中删除数据?
在本文中,我们将看到如何删除 Firebase 实时数据库中添加的数据。因此,我们将转向在 Android Firebase 中实现此删除数据。
我们将在本文中构建什么?
当用户长按 RecyclerView 项目时,我们将显示一个简单的 AlertBox。它将有两个选择。 (删除和取消)。当用户单击删除时,它只会删除该值。您可以参考如何在 Android 中将数据保存到 Firebase 实时数据库以了解如何在 Firebase 中保存数据。
Note: You can use Hashmap to save data in firebase.
此外,您还可以直接在 firebase 中添加数据,如下所示
分步实施
第 1 步:创建一个新项目
要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Java作为编程语言。
步骤 2:使用 activity_main.xml 文件
导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。
XML
Java
package com.anni.uploaddataexcelsheet;
public class DModel {
public DModel() {
}
public String getTime() {
return time;
}
public DModel(String time, String name) {
this.time = time;
this.name = name;
}
public void setTime(String time) {
this.time = time;
}
String time;
public DModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
String name;
}
Java
package com.anni.uploaddataexcelsheet;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class DAdapter extends RecyclerView.Adapter {
List notifications;
public DAdapter(List notifications, Context context) {
this.notifications = notifications;
this.context = context;
}
Context context;
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_delete,parent,false);
return new MyHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
// get the item value by positions
String text=notifications.get(position).getName();
final String time=notifications.get(position).getTime();
((MyHolder)holder).notification.setText(text);
// click on item to be deleted
((MyHolder)holder).notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence options[]=new CharSequence[]{
// select any from the value
"Delete",
"Cancel",
};
AlertDialog.Builder builder=new AlertDialog.Builder(holder.itemView.getContext());
builder.setTitle("Delete Content");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// if delete option is choosed
// then call delete function
if(which==0) {
delete(position,time);
}
}
});
builder.show();
}
});
}
private void delete(int position, String time) {
// creating a variable for our Database
// Reference for Firebase.
DatabaseReference dbref= FirebaseDatabase.getInstance().getReference().child("DataValue");
// we are use add listerner
// for event listener method
// which is called with query.
Query query=dbref.child(time);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// remove the value at reference
dataSnapshot.getRef().removeValue();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public int getItemCount() {
return notifications.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView notification;
public MyHolder(@NonNull View itemView) {
super(itemView);
notification=itemView.findViewById(R.id.name);
}
}
}
Java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
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 java.util.ArrayList;
import java.util.List;
public class DeleteData extends AppCompatActivity {
List notifications;
DAdapter adapterNotification;
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
// Initialise layout
recyclerView=findViewById(R.id.recyclerview);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(DeleteData.this);
// reverse tha layout
linearLayoutManager.setReverseLayout(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
notifications=new ArrayList<>();
// creating a variable for our Database
// Reference for Firebase.
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("DataValue");
// we are using add value event listener method
// which is called with database reference.
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// clear the data
notifications.clear();
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) {
DModel modelNotification = dataSnapshot1.getValue(DModel.class);
notifications.add(modelNotification);
adapterNotification = new DAdapter(notifications,DeleteData.this);
// set the adapter
recyclerView.setAdapter(adapterNotification);
adapterNotification.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
第 3 步:使用 DModel。 Java文件
转到DModel。 Java文件,参考如下代码。下面是DModel的代码。 Java文件。
Java
package com.anni.uploaddataexcelsheet;
public class DModel {
public DModel() {
}
public String getTime() {
return time;
}
public DModel(String time, String name) {
this.time = time;
this.name = name;
}
public void setTime(String time) {
this.time = time;
}
String time;
public DModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
String name;
}
第 4 步:使用 DAdapter。 Java文件
转到DAdapter。 Java文件,参考如下代码。下面是DAdapter的代码。 Java文件
Java
package com.anni.uploaddataexcelsheet;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class DAdapter extends RecyclerView.Adapter {
List notifications;
public DAdapter(List notifications, Context context) {
this.notifications = notifications;
this.context = context;
}
Context context;
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_delete,parent,false);
return new MyHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
// get the item value by positions
String text=notifications.get(position).getName();
final String time=notifications.get(position).getTime();
((MyHolder)holder).notification.setText(text);
// click on item to be deleted
((MyHolder)holder).notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence options[]=new CharSequence[]{
// select any from the value
"Delete",
"Cancel",
};
AlertDialog.Builder builder=new AlertDialog.Builder(holder.itemView.getContext());
builder.setTitle("Delete Content");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// if delete option is choosed
// then call delete function
if(which==0) {
delete(position,time);
}
}
});
builder.show();
}
});
}
private void delete(int position, String time) {
// creating a variable for our Database
// Reference for Firebase.
DatabaseReference dbref= FirebaseDatabase.getInstance().getReference().child("DataValue");
// we are use add listerner
// for event listener method
// which is called with query.
Query query=dbref.child(time);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// remove the value at reference
dataSnapshot.getRef().removeValue();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public int getItemCount() {
return notifications.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView notification;
public MyHolder(@NonNull View itemView) {
super(itemView);
notification=itemView.findViewById(R.id.name);
}
}
}
第 6 步:使用 MainActivity。 Java文件
转到主活动。 Java文件,参考如下代码。下面是MainActivity的代码。 Java文件
Java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
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 java.util.ArrayList;
import java.util.List;
public class DeleteData extends AppCompatActivity {
List notifications;
DAdapter adapterNotification;
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
// Initialise layout
recyclerView=findViewById(R.id.recyclerview);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(DeleteData.this);
// reverse tha layout
linearLayoutManager.setReverseLayout(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
notifications=new ArrayList<>();
// creating a variable for our Database
// Reference for Firebase.
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("DataValue");
// we are using add value event listener method
// which is called with database reference.
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// clear the data
notifications.clear();
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()) {
DModel modelNotification = dataSnapshot1.getValue(DModel.class);
notifications.add(modelNotification);
adapterNotification = new DAdapter(notifications,DeleteData.this);
// set the adapter
recyclerView.setAdapter(adapterNotification);
adapterNotification.notifyDataSetChanged();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
数据库结构
输出: