Android如何从Firebase数据库中删除价值? [英] Android how to remove value from firebase database?

查看:81
本文介绍了Android如何从Firebase数据库中删除价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在Firebase中的第一个项目.我正在尝试从Firebase删除值,但是每当我尝试从Firebase删除值时,我的应用程序就会崩溃.我没有解决该错误的方法

this is my first project in firebase. I am trying to remove value from firebase but when ever i am trying to remove value from firebase, my application crashes. I am not getting how do i solve this error

Service.class

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)

推荐答案

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

dataSnapshot.getRef().setValue(null); isn't the correct way of deleting your Firebase Object. You're not allowed to save a null value to your database. To remove it, you use:

dataSnapshot.getRef().removeValue();

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

You should also check if the value isn't null, since you will delete that object.

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

这篇关于Android如何从Firebase数据库中删除价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆