【问题标题】:Android how to remove value from firebase database?Android如何从firebase数据库中删除值?
【发布时间】:2017-06-22 14:46:39
【问题描述】:

这是我在 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)

【问题讨论】:

  • NotiListener 类第 52 行的内容
  • 第 52 行:String msg = snapshot.child("msg").getValue().toString();值已从数据库中删除,但同时应用程序也崩溃了
  • 检查我的编辑..
  • 我编辑了我的答案。
  • @T.S & AbAppletic 感谢您的解决方案 :)

标签: android firebase firebase-realtime-database


【解决方案1】:

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

dataSnapshot.getRef().removeValue();

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

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

【讨论】:

  • 我使用了 dataSnapshot.getRef().removeValue();但我得到了相同的结果
  • 如果您仍然收到错误,请通过编辑问题发布您的第二个 logcat。
  • 不,你还没有
  • 谢谢 :),它的工作
  • 很高兴它得到了修复。
【解决方案2】:

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

rootRef.child(clickedKey).removeValue();

【讨论】:

  • 他不必传递密钥,他有DatabaseReference。
  • 你好@AdAppletic我在这里传递“clickedkey”是这样的:keysArray.add(dataSnapshot.getKey().toString());
  • 但是rootRef是他要删除的DatabaseReference。
【解决方案3】:

当您删除值时,当您尝试在ValueEventListener 中再次获取值时,就会出现NullPointerException

这一行:

String msg = snapshot.child("msg").getValue().toString();

在获得值之前,您应该检查是否(snapshot != null && snapshot.child("msg").getValue() != null

【讨论】:

  • 不错的收获!我在你之前也抓住了它,但是当你回答它时我正在编辑我的答案。 +1
【解决方案4】:

实际上,如果看到 firebase 的 removeValue() 的实现,它的作用与将值设置为 null 相同。

public Task<Void> removeValue() {
        return this.setValue((Object)null);
    }

所以将值设置为null或者使用removeValue()函数都是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2017-02-01
    • 2019-02-07
    相关资源
    最近更新 更多