java - RecycleViewAdapter 在加载其项目时出现 null 异常( fragment 中的 RecycleView)

标签 java android android-recyclerview

在我的应用程序中,我有一个 Activity (主 Activity ),其中有一个 ViewPager,显示 fragment 。现在我有一个 fragment ,其中有一个 RecyclerView。此 RecyclerView 应该显示“目标”对象的列表。每次我运行该应用程序时,它都会崩溃,说它有一个空问题,我认为这可能是因为编写内容的顺序所致。

我尝试更改顺序,在互联网上搜索其他可能的问题,但没有成功。

错误日志:

2019-06-26 18:51:10.544 15296-15296/com.example.performancemeasurement E/RecyclerView: No adapter attached; skipping layout
2019-06-26 18:52:23.369 15296-15349/com.example.performancemeasurement E/zygote64: Dex checksum does not match for dex: /data/data/com.example.performancemeasurement/files/instant-run/dex-temp/reload0x0000.dex.Expected: 3346174271, actual: 1626468260
2019-06-26 18:52:24.380 15296-15296/com.example.performancemeasurement E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.performancemeasurement, PID: 15296
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.github.abdularis.civ.CircleImageView.setImageResource(int)' on a null object reference
        at com.example.performancemeasurement.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:36)
        at com.example.performancemeasurement.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:17)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at androidx.viewpager.widget.ViewPager.onLayout(ViewPager.java:1775)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1081)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:782)
        at android.view.View.layout(View.java:19654)
        at android.view.ViewGroup.layout(ViewGroup.java:6127)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2584)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2293)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1451)
2019-06-26 18:52:24.380 15296-15296/com.example.performancemeasurement E/AndroidRuntime:     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7204)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:979)
        at android.view.Choreographer.doCallbacks(Choreographer.java:791)
        at android.view.Choreographer.doFrame(Choreographer.java:726)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:965)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6710)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)

fragment_active_goals.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ActiveGoals">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/activeGoalsRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

goals_list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/goalCardParent"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="0dp"
    android:clickable="true"
    android:focusable="true"
    android:background="@color/cardview_light_background">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.github.abdularis.civ.CircleImageView
            android:id="@+id/goalImage"
            android:layout_width="150dp"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="1:1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintVertical_bias="0.5"
            android:src="@drawable/active_brain_drawing"/>

        <TextView
            android:id="@+id/goalName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toEndOf="@id/goalImage"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:autoSizeTextType="uniform"
            android:padding="15dp"
            android:text="@string/active_goal_name_sample"/>

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

ActiveGoals.java:

public class ActiveGoals extends Fragment {

    private ArrayList<Goal> goals = new ArrayList<>();
    private RecyclerView recyclerView;

    public ActiveGoals() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_active_goals, container, false);
        recyclerView = v.findViewById(R.id.activeGoalsRecyclerView);
        initGoals();
        return v;
    }

    private void initGoals(){
        goals.add(new Goal("A", "active", "", null));
        goals.add(new Goal("B", "bronze", "", null));
        goals.add(new Goal("C", "silver", "", null));
        goals.add(new Goal("D", "gold", "", null));
        goals.add(new Goal("E", "active", "", null));
        goals.add(new Goal("F", "bronze", "", null));
        goals.add(new Goal("G", "silver", "", null));
        goals.add(new Goal("H", "gold", "", null));
        initRecyclerView();
    }

    private void initRecyclerView(){
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(goals, this.getContext());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

}

目标.java:

public class Goal {
    private String name, status, description;
    private Integer imageId;
    private ArrayList<Goal> subGoals;

    public Goal(String name, String status, String description, ArrayList<Goal> subGoals) {
        this.name = name;
        this.status = status;
        this.description = description;
        this.subGoals = subGoals;

        switch (status){
            case "active":
                imageId = R.drawable.active_brain_drawing;
                break;
            case "bronze":
                imageId = R.drawable.bronze_medal;
                break;
            case "silver":
                imageId = R.drawable.silver_medal;
                break;
            case "gold":
                imageId = R.drawable.golden_medal;
                break;
            default:
                imageId = R.drawable.active_brain_drawing;
                break;
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
        switch (status){
            case "active":
                imageId = R.drawable.active_brain_drawing;
                break;
            case "bronze":
                imageId = R.drawable.bronze_medal;
                break;
            case "silver":
                imageId = R.drawable.silver_medal;
                break;
            case "gold":
                imageId = R.drawable.golden_medal;
                break;
            default:
                imageId = R.drawable.active_brain_drawing;
                break;
        }
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public ArrayList<Goal> getSubGoals() {
        return subGoals;
    }

    public void setImageId(Integer imageId) {
        this.imageId = imageId;
    }

    public Integer getImageId() {
        return imageId;
    }
}

RecyclerViewAdapter.java:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

    private ArrayList<Goal> goals;
    private Context mContext;

    RecyclerViewAdapter(ArrayList<Goal> goals, Context mContext) {
        this.goals = goals;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.goals_list_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.goalImage.setImageResource(goals.get(position).getImageId());

        holder.goalName.setText(goals.get(position).getName());

        holder.goalCardParent.setOnClickListener(view -> {

        });
    }

    @Override
    public int getItemCount() {
        return goals.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        private CardView goalCardParent;
        private CircleImageView goalImage;
        private TextView goalName;

        MyViewHolder(@NonNull View itemView) {
            super(itemView);
            goalCardParent = itemView.findViewById(R.id.goalCardParent);
            goalImage = itemView.findViewById(R.id.goalImage);
            goalName = itemView.findViewById(R.id.goalName);

        }
    }
}

问题出在哪里以及如何解决?

编辑

发现问题出在哪里——onBindViewHolder方法(RecyclerViewAdapter类中)的holder下的goalImage、goalName、goalCardParent都是null,而holder却不是。原因是什么以及如何解决?

提前致谢(:

最佳答案

刚刚想通了!问题出在 goal_list_item.xml (v26) 中...对象的 id 有所不同,并且代码无法通过其 id 找到正确的对象。抱歉打扰了,我的坏XD感谢大家帮助我!

关于java - RecycleViewAdapter 在加载其项目时出现 null 异常( fragment 中的 RecycleView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776973/

相关文章:

java - Android RecyclerView 添加按钮给我错误

java - 如何编写受 JDK bug 影响的 Java 单元测试

java - Shiro 中的纯密码和加密密码不匹配

java - Android 应用程序在设备上加载白屏

android - ConstraintLayout RecyclerView 显示在 BottomNavigationView 下

java - 从中心项开始我的 RecyclerView 水平旋转木马

java - 如何使用 onClick for android 从按钮生成随机类结果?

java - 使用适用于 Eclipse 的 weblogic 适配器部署 Web 应用程序

java - 在每个 ListView 项目中添加 Heavy UI

android - 通过 RetroFit 2 调用 Rest API 并使用 RecyclerView 时出现 NullPointerException