在RecyclerView中点击收藏项出现问题。

huangapple 未分类评论47阅读模式
英文:

Problem with clicking on favorite item in RecyclerView

问题

我正尝试使用Volley库和JSON创建一个RSS新闻订阅应用程序,基于RecyclerView,其中每行包含标题、发布日期、描述和文章链接。

该应用程序应允许创建一个收藏夹文章列表(数据库)。

当我使用占位信息而不是真实的互联网内容运行应用程序时,一切正常。

但当我连接到互联网并点击“收藏”按钮(心形按钮)时,出现以下错误:
[从互联网加载的信息][1]
[错误消息][2]
以下是相关代码的部分,其中包含突出显示的行和调试日志:

public BbsNewsViewHolder(@NonNull View itemView){
    super(itemView);
    titleTextView = itemView.findViewById(R.id.txtTitle);
    pubDateTextView= itemView.findViewById(R.id.txtPubDate);
    descriptionTextView=itemView.findViewById(R.id.txtDescription);
    linkTextView = itemView.findViewById(R.id.link);
    favBtn = itemView.findViewById(R.id.favBtn);
    //添加到收藏夹
    favBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            int position = getAdapterPosition();
            ArticleItem articleItem = articleItems.get(position);
            if (articleItem.getFavStatus().equals("0")) {
                articleItem.setFavStatus("1");
                favDB.insertIntoTheDatabase(articleItem.getTitle(),
                    articleItem.getPubDate(),
                    articleItem.getDescription(),
                    articleItem.getWebUrl(),
                    articleItem.getKey_id(),
                    articleItem.getFavStatus());
                favBtn.setBackgroundResource(R.drawable.ic_favorite_color);
            } else {
                articleItem.setFavStatus("0");
                favDB.remove_fav(articleItem.getKey_id());
                favBtn.setBackgroundResource(R.drawable.ic_favorite_border);
            }
        }
    }); 
}

错误日志:

04/06 16:29:34: 在 Nexus 4 API 23 上启动'app'。
$ adb shell am start -n "com.example.favoritelist/com.example.favoritelist.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
等待应用程序上线:com.example.favoritelist.test | com.example.favoritelist
等待应用程序上线:com.example.favoritelist.test | com.example.favoritelist
等待应用程序上线:com.example.favoritelist.test | com.example.favoritelist
连接到 com.example.favoritelist
已连接到目标虚拟机,地址:'localhost:8628',传输:'socket'
捕获并显示应用程序的日志消息。可以在“调试器”设置页面的“Logcat输出”部分中禁用此行为。
I/art: 调试器已启动
I/System.out: 调试器已连接
等待调试器稳定...
I/System.out: 等待调试器稳定...
I/System.out: 等待调试器稳定...
I/System.out: 等待调试器稳定...
I/System.out: 等待调试器稳定...
I/System.out: 等待调试器稳定...
I/System.out: 等待调试器稳定...
I/System.out: 调试器已稳定(1495)
W/System: 类加载器引用了未知路径:/data/app/com.example.favoritelist-2/lib/x86
W/FirebaseApp:默认FirebaseApp初始化失败,因为未找到默认选项。这通常意味着 com.google.gms:google-services 没有应用于您的 gradle 项目。
I/FirebaseInitProvider:FirebaseApp 初始化失败
W/art:Android 4.1 之前,在 android.graphics.drawable 中的方法 android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) 将错误地覆盖 android.graphics.drawable.Drawable 中的 package-private 方法
I/art:拒绝对先前失败的类 java.lang.Class<androidx.core.view.ViewCompat$2> 进行重新初始化
I/art:拒绝对先前失败的类 java.lang.Class<androidx.core.view.ViewCompat$2> 进行重新初始化
D/OpenGLRenderer:使用 EGL_SWAP_BEHAVIOR_PRESERVED:true
D/:HostConnection::get() 已建立新的主机连接 0xb3fefd40,tid 6001
D/:HostConnection::get() 已建立新的主机连接 0xa1cff240,tid 6040
I/OpenGLRenderer:已初始化 EGL,版本 1.4
W/OpenGLRenderer:选择带有 EGL_SWAP_BEHAVIOR_PRESERVED 的配置失败,正在重试...
D/EGL_emulation:eglCreateContext:0xae6b45c0:maj 3 min 1 rcv 4
D/EGL_emulation:eglMakeCurrent:0xae6b45c0:ver 3 1(tinfo 0xb2a145c0)
E/eglCodecCommon:glUtilsParamSize:未知参数 0x000082da
glUtilsParamSize:未知参数 0x00008cdf
E/eglCodecCommon:glUtilsParamSize:未知参数 0x00008824
D/EGL_emulation:eglMakeCurrent:0xae6b45c0:ver 3 1(tinfo 0xb2a145c0)
D/AndroidRuntime:关闭 VM
E/AndroidRuntime:致命异常:主线程
处理程序:com.example.favoritelist,PID:6001
java.lang.NullPointerException:尝试调用虚拟方法 'boolean java.lang.String.equals(java.lang.Object)',但空对象引用
在 com.example.favoritelist.ArticleAdapter$BbsNewsViewHolder$1.onClick(ArticleAdapter.java:89) 处
在 android.view.View.performClick(View.java:5198) 处
在 android.view.View$PerformClick.run(View.java:21147) 处
在 android.os.Handler.handleCallback(Handler.java:739) 处
在 android.os.Handler.dispatchMessage(Handler.java:95) 处
在 android.os.Looper.loop(Looper.java:148) 处
在 android.app.ActivityThread.main(ActivityThread.java:5417) 处
在 java.lang.reflect.Method.invoke(Native Method) 处
在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 处
在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 处
I/Process:发送信号。PID:6001 SIG:9
已从目标虚拟机断开连接,地址:

<details>
<summary>英文:</summary>

I’m trying to create rss news feeding app using Volley library/JSON with on the base of RecyclerView, where each row contains title, pubdate, description and link to the Article. 

This app should allow to create a list of favorite articles(DB). 

When I run the app with placeholder info instead of real internet content, everything works OK.

But when I run it with internet connection  and click on the “favorite ” button(heart), the following error appears: 
[loaded info from internet][1]
[error message][2]
Below is the part of the related code with highlighted line and debug log:

    public BbsNewsViewHolder(@NonNull View itemView){
        super(itemView);
        titleTextView = itemView.findViewById(R.id.txtTitle);
        pubDateTextView= itemView.findViewById(R.id.txtPubDate);
        descriptionTextView=itemView.findViewById(R.id.txtDescription);
        linkTextView = itemView.findViewById(R.id.link);
        favBtn = itemView.findViewById(R.id.favBtn);
        //add to favorites
        favBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                int position = getAdapterPosition();
                ArticleItem articleItem = articleItems.get(position);
                if (articleItem.getFavStatus().equals(&quot;0&quot;)) {
                    articleItem.setFavStatus(&quot;1&quot;);
                    favDB.insertIntoTheDatabase(articleItem.getTitle(),
                        articleItem.getPubDate(),
                        articleItem.getDescription(),
                        articleItem.getWebUrl(),
                        articleItem.getKey_id(),
                        articleItem.getFavStatus());
                    favBtn.setBackgroundResource(R.drawable.ic_favorite_color);
                } else {
                    articleItem.setFavStatus(&quot;0&quot;);
                    favDB.remove_fav(articleItem.getKey_id());
                    favBtn.setBackgroundResource(R.drawable.ic_favorite_border);
                }
            }
        }); 
    }


Error Log:

    04/06 16:29:34: Launching &#39;app&#39; on Nexus 4 API 23.
    $ adb shell am start -n &quot;com.example.favoritelist/com.example.favoritelist.MainActivity&quot; -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
    Waiting for application to come online: com.example.favoritelist.test | com.example.favoritelist
    Waiting for application to come online: com.example.favoritelist.test | com.example.favoritelist
    Waiting for application to come online: com.example.favoritelist.test | com.example.favoritelist
    Connecting to com.example.favoritelist
    Connected to the target VM, address: &#39;localhost:8628&#39;, transport: &#39;socket&#39;
    Capturing and displaying logcat messages from application. This behavior can be disabled in the &quot;Logcat output&quot; section of the &quot;Debugger&quot; settings page.
    I/art: Debugger is active
    I/System.out: Debugger has connected
        waiting for debugger to settle...
    I/System.out: waiting for debugger to settle...
    I/System.out: waiting for debugger to settle...
    I/System.out: waiting for debugger to settle...
    I/System.out: waiting for debugger to settle...
    I/System.out: waiting for debugger to settle...
    I/System.out: waiting for debugger to settle...
    I/System.out: debugger has settled (1495)
    W/System: ClassLoader referenced unknown path: /data/app/com.example.favoritelist-2/lib/x86
    W/FirebaseApp: Default FirebaseApp failed to initialize because no default options were found. This usually means that com.google.gms:google-services was not applied to your gradle project.
    I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
    W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
    I/art: Rejecting re-init on previously-failed class java.lang.Class&lt;androidx.core.view.ViewCompat$2&gt;
    I/art: Rejecting re-init on previously-failed class java.lang.Class&lt;androidx.core.view.ViewCompat$2&gt;
    D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
    D/: HostConnection::get() New Host Connection established 0xb3fefd40, tid 6001
    D/: HostConnection::get() New Host Connection established 0xa1cff240, tid 6040
    I/OpenGLRenderer: Initialized EGL, version 1.4
    W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
    D/EGL_emulation: eglCreateContext: 0xae6b45c0: maj 3 min 1 rcv 4
    D/EGL_emulation: eglMakeCurrent: 0xae6b45c0: ver 3 1 (tinfo 0xb2a145c0)
    E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
        glUtilsParamSize: unknow param 0x00008cdf
    E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
    D/EGL_emulation: eglMakeCurrent: 0xae6b45c0: ver 3 1 (tinfo 0xb2a145c0)
    D/AndroidRuntime: Shutting down VM
    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.favoritelist, PID: 6001
        java.lang.NullPointerException: Attempt to invoke virtual method &#39;boolean java.lang.String.equals(java.lang.Object)&#39; on a null object reference
            at com.example.favoritelist.ArticleAdapter$BbsNewsViewHolder$1.onClick(ArticleAdapter.java:89)
            at android.view.View.performClick(View.java:5198)
            at android.view.View$PerformClick.run(View.java:21147)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    I/Process: Sending signal. PID: 6001 SIG: 9
    Disconnected from the target VM, address: &#39;localhost:8628&#39;, transport: &#39;socket&#39;


[1]: https://i.stack.imgur.com/JDvDe.jpg
[2]: https://i.stack.imgur.com/tq37X.png

</details>


# 答案1
**得分**: 0

如果您注意到,您在以下日志中遇到了`NullPointException`:

&gt;  `java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法'boolean java.lang.String.equals(java.lang.Object)'`

因此,此异常的原因是您在`String`对象上调用了`.equals()`方法。回顾您的代码;您仅在`articleItem.getFavStatus().equals(&quot;0&quot;)`中使用了`.equals()`。

所以,显然您的`articleItem.getFavStatus()`是一个空值,并且您试图将其与&quot;0&quot;进行比较。因此,您需要检查为什么它返回为空,还可以将此代码部分包装在`try`块中,或者在此语句处设置断点以进行检查。

希望对您有所帮助。

<details>
<summary>英文:</summary>

If you notice, you got `NullPointException` with the following log:

&gt;  `java.lang.NullPointerException: Attempt to invoke virtual method &#39;boolean java.lang.String.equals(java.lang.Object)&#39; on a null object reference`

So, the cause of this exception that you call `.equals()` method on a `String` object. Looking back into your code; you used `.equals()` only once in `articleItem.getFavStatus().equals(&quot;0&quot;)`.

So, obviously your `articleItem.getFavStatus()` is a null value and you are trying to compare it to &quot;0&quot;. So, you need to check why it returns null, also you can wrap this part of code into a `try` block, or put a break point at this statement to examine it.

hope that help you out.

</details>



huangapple
  • 本文由 发表于 2020年4月7日 05:05:44
  • 转载请务必保留本文链接:https://java.coder-hub.com/61068972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定