RecycleViewAdapter加载项目时得到null异常(片段中的RecycleView)

时间:2019-06-26 16:04:22

标签: java android android-recyclerview

在我的应用程序中,我有一个活动(主要活动),其中有一个ViewPager,其中显示了片段。现在,我有一个其中包含RecyclerView的Fragment。这个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()));
    }

}

Goal.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类中)的所有者下的goalImage,goalName和goalCardParent全部为null,而所有者则为null。是什么原因,如何解决?

预先感谢(:

2 个答案:

答案 0 :(得分:0)

我知道这是一个自定义视图,但是如果它扩展了普通的ImageView,则应该改用它,因为您使用的是可绘制的ID

holder.goalImage.setImageDrawable(mContext.getDrawable(goals.get(position).getImageId()));

答案 1 :(得分:0)

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