You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发音乐播放器App时遭遇java.lang.NullPointerException异常求助

音乐播放器App空指针异常解决方案

异常日志

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.appnghenhac, PID: 11560
    java.lang.NullPointerException: 尝试在空对象引用上调用接口方法'int java.util.List.size()'
        at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:389)
        at android.widget.ListView.setAdapter(ListView.java:581)
        at com.example.appnghenhac.Fragment.Fragment_Playlist$2.onResponse(Fragment_Playlist.java:69)
        at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7842)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

问题原因

从栈轨迹可直接定位:Fragment_Playlist.java第69行调用ListView.setAdapter()时,传入的ArrayAdapter依赖的数据源List对象为null,导致ArrayAdapter内部调用List.size()触发空指针异常。

解决步骤

  • 校验接口返回数据:在Retrofit的onResponse回调中,先判断接口返回的列表是否非null,再初始化适配器:
    @Override
    public void onResponse(Call<List<Playlist>> call, Response<List<Playlist>> response) {
        if (response.isSuccessful()) {
            List<Playlist> playlistList = response.body();
            if (playlistList != null) {
                ArrayAdapter<Playlist> adapter = new ArrayAdapter<>(getContext(), 
                    android.R.layout.simple_list_item_1, playlistList);
                yourListView.setAdapter(adapter);
            } else {
                Toast.makeText(getContext(), "暂无播放列表数据", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
  • 确保ListView初始化正确:检查Fragment_Playlist中ListView是否通过findViewById或ViewBinding完成初始化,避免ListView本身为null。
  • 处理请求失败场景:实现onFailure回调,处理网络错误、请求超时等情况,防止因请求失败导致数据未初始化就设置适配器:
    @Override
    public void onFailure(Call<List<Playlist>> call, Throwable t) {
        Toast.makeText(getContext(), "加载失败:" + t.getMessage(), Toast.LENGTH_SHORT).show();
    }
    

内容的提问来源于stack exchange,提问作者user21482755

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:22:18