从firebase删除一个项目,而不会崩溃的应用程序 [英] Delete an item from firebase without crashing the app

查看:145
本文介绍了从firebase删除一个项目,而不会崩溃的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android新手,我一直在玩这个来自Firebase的示例应用程序。我想在 PostDetailActivity ,它通过将DatabaseReference mPostReference设置为null来删除从数据库中查看的当前帖子。然而,这会导致一个空值指针例外的ValueEventListener添加到mPostReference,导致应用程序崩溃。

  intent 
mPostKey = getIntent()。getStringExtra(EXTRA_POST_KEY);
if(mPostKey == null){
throw new IllegalArgumentException(必须通过EXTRA_POST_KEY);

$ b $ //初始化数据库
mPostReference = FirebaseDatabase.getInstance().getReference()
.child(posts)。child(mPostKey);

ValueEventListener postListener = new ValueEventListener(){
@Override $ b $ public void onDataChange(DataSnapshot dataSnapshot){
//获取Post对象并使用值更新UI
Post post = dataSnapshot.getValue(Post.class);
//活动中的文本视图
mAuthorView.setText(post.author);
mTitleView.setText(post.title);
mBodyView.setText(post.body);

$ b @Override
public void onCancelled(DatabaseError databaseError){
//获取发布失败,记录消息
Log.w(TAG, loadPost:onCancelled,databaseError.toException());
// [START_EXCLUDE]
Toast.makeText(PostDetailActivity.this,Failed to load post,
Toast.LENGTH_SHORT).show();
// [END_EXCLUDE]
}
};
mPostReference.addValueEventListener(postListener);

// delete button clicked
deleteButton.setOnClickListener(new View.OnClickListener(){
mPostReference.setValue(null);
}

如果mPostReference被删除或设置为null,有没有办法让应用程序崩溃?有没有更好的方法来实现删除按钮?
任何想法/建议将不胜感激。谢谢

以下是日志

 致命例外:main 
进程:com.google.firebase.quickstart.database,PID:2861
java.lang.NullPointerException:尝试从字段'java .lang.String com.google.firebase.quickstart.database.models.Post.author'在null对象引用
上com.google.firebase.quickstart.database.PostDetailActivity $ 1.onDataChange(PostDetailActivity.java:93 )
在com.google.android.gms.internal.zzbmz.zza(未知来源)
在com.google.android.gms.internal.zzbnz.zzYj(未知来源)
at com.google.android.gms.internal.zzboc $ 1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage (Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)$ b $在java.lang.reflect.Method.invoke(Method.java:372)
在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller .run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)


解决方案

如果语句只需要添加来检查 dataSnapshot 有一个值或 null

  public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
//获取Post对象并使用值更新UI
Post post = d ataSnapshot.getValue(Post.class);
//活动中的文本视图
mAuthorView.setText(post.author);
mTitleView.setText(post.title);
mBodyView.setText(post.body);
}
}


I'm new to android and I've been playing around with this sample app from firebase. I want to add a delete button on PostDetailActivity which deletes the current post being viewed from the database by setting the DatabaseReference mPostReference to null. However this causes a null pointer exception to a ValueEventListener added to mPostReference, causing the app to crash.

    // Get post key from intent
    mPostKey = getIntent().getStringExtra(EXTRA_POST_KEY);
    if (mPostKey == null) {
        throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
    }

    // Initialize Database
    mPostReference = FirebaseDatabase.getInstance().getReference()
            .child("posts").child(mPostKey);

    ValueEventListener postListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get Post object and use the values to update the UI
            Post post = dataSnapshot.getValue(Post.class);
            // Text Views in activity
            mAuthorView.setText(post.author);
            mTitleView.setText(post.title);
            mBodyView.setText(post.body);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            // [START_EXCLUDE]
            Toast.makeText(PostDetailActivity.this, "Failed to load post.",
                    Toast.LENGTH_SHORT).show();
            // [END_EXCLUDE]
        }
    };
    mPostReference.addValueEventListener(postListener);

   //delete button clicked
   deleteButton.setOnClickListener(new View.OnClickListener() {
        mPostReference.setValue(null);
   }

Is there a way to keep the app from crashing if mPostReference has been deleted or set to null? Are there better ways in implementing a delete button? Any ideas/suggestions would be greatly appreciated. Thank you

Here's the log

FATAL EXCEPTION: main
   Process: com.google.firebase.quickstart.database, PID: 2861
   java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.google.firebase.quickstart.database.models.Post.author' on a null object reference
   at com.google.firebase.quickstart.database.PostDetailActivity$1.onDataChange(PostDetailActivity.java:93)
   at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
   at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
   at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6145)
   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:1399)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

解决方案

You just need to add an if statement to check if the dataSnapshot has a value or null

public void onDataChange(DataSnapshot dataSnapshot) {
    if (dataSnapshot.exists()) {
        // Get Post object and use the values to update the UI
        Post post = dataSnapshot.getValue(Post.class);
        // Text Views in activity
        mAuthorView.setText(post.author);
        mTitleView.setText(post.title);
        mBodyView.setText(post.body);
    }
}

这篇关于从firebase删除一个项目,而不会崩溃的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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