Android 如何从 firebase 数据库中删除值?

新手上路,请多包涵

这是我在 Firebase 中的第一个项目。我正在尝试从 firebase 中删除值,但是每当我尝试从 firebase 中删除值时,我的应用程序就会崩溃。我不知道如何解决此错误

服务类

public class NotiListener extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //When the service is started
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Opening sharedpreferences
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.SHARED_PREF, MODE_PRIVATE);

        //Getting the firebase id from sharedpreferences
        String id = sharedPreferences.getString(Constant.UNIQUE_ID, null);

        //Creating a firebase object
        Firebase firebase = new Firebase(Constant.FIREBASE_APP + id);

        //Adding a valueevent listener to firebase
        //this will help us to  track the value changes on firebase
        firebase.addValueEventListener(new ValueEventListener() {

            //This method is called whenever we change the value in firebase
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                  if(snapshot.child("msg") != null){
                String msg = snapshot.child("msg").getValue().toString();

                if (msg.equals("none"))
                    return;

                showNotification(msg);
            } else{
                Log.e("Value-->","Null");
            }

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                Log.e("The read failed: ", firebaseError.getMessage());
            }
        });

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
    }

    private void showNotification(String msg){
        //Creating a notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("Firebase Push Notification");
        builder.setContentText(msg);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build());
    }
}

删除值的代码是:

 Firebase firebase=new Firebase(Constant.FIREBASE_APP+id);
                    firebase.orderByChild(id).equalTo(id).addListenerForSingleValueEvent(
                            new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                     dataSnapshot.getRef().removeValue();

                                }

                                @Override
                                public void onCancelled(FirebaseError firebaseError) {

                                }
                             });

日志:

 10-21 17:46:17.384 30986-30986/com.example.pitech09.bizfriend E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.pitech09.bizfriend, PID: 30986
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                                    at com.example.pitech09.bizfriend.NotiListener$1.onDataChange(NotiListener.java:52)
                                                                                    at com.firebase.client.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:56)
                                                                                    at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
                                                                                    at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
                                                                                    at android.os.Handler.handleCallback(Handler.java:739)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                    at android.os.Looper.loop(Looper.java:135)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

原文由 Satish Lodhi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 373
2 个回答

dataSnapshot.getRef().setValue(null); 不是删除 Firebase 对象的正确方法。不允许将空值保存到数据库中。要删除它,您可以使用:

 dataSnapshot.getRef().removeValue();

您还应该检查该值是否不为空,因为您将删除该对象。

 if(snapshot.child("msg").getValue() != null){
   String msg = snapshot.child("msg").getValue().toString();
   return;
}

原文由 Ali Bdeir 发布,翻译遵循 CC BY-SA 3.0 许可协议

你好@Satish Lodhi 只是你必须传递你从 firebase 中删除的项目的密钥并放置这一行。

 rootRef.child(clickedKey).removeValue();

原文由 Sachin Suthar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题