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

时间:2016-10-21 11:55:58

标签: android firebase firebase-realtime-database

这是我在firebase中的第一个项目。我试图从firebase中删除值,但是当我试图从firebase中删除值时,我的应用程序崩溃了。我没有得到如何解决这个错误

Service.class

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)

4 个答案:

答案 0 :(得分:6)

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

dataSnapshot.getRef().removeValue();

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

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

答案 1 :(得分:0)

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

这一行:

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

你应该检查(snapshot != null && snapshot.child("msg").getValue() != null是否可以获得价值。

答案 2 :(得分:0)

你好@Satish Lodhi你只需要传递你从firebase中删除的项目并放上这一行。

rootRef.child(clickedKey).removeValue();

答案 3 :(得分:0)

实际上如果看到firebase的removeValue()的实现,它就像将值设置为null一样。

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

因此将值设置为null或使用removeValue()函数是相同的。