错误:尝试在空对象引用上调用虚拟方法'void android.widget.ImageView.setImageResource(int)'

时间:2019-03-08 19:01:25

标签: java android

m new in Android Studio and I在大学的顶峰项目中工作,我正在尝试通过recyclerview生成一些卡片。 问题是,根据CardID,我需要更改卡图标和标头卡背景色,并且对于这两个命令,程序都会崩溃,并显示错误“尝试在虚拟对象引用上调用虚拟方法...。” 。 我尝试了不同的方法来更改图像和背景颜色,但没有成功,并且在这里所做的研究之后,我相信这两个命令都是正确的:

       viewHolder.backgroundHeader.setBackgroundColor(Color.parseColor("#567845"));
       viewHolder.iconCard.setImageResource(R.drawable.health_icon);

这是我用来生成卡片的XML布局文件:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/longTermCardHealth"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="0dp"
    android:layout_marginBottom="10dp"
    android:background="@color/monocolorPallete04"
    android:orientation="vertical"
    tools:context=".LongTermCardHealth">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="3dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


    <GridLayout
        android:id="@+id/backgroundHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/mainPallete02">

        <ImageView
            android:id="@+id/iconCard"
            android:layout_width="43dp"
            android:layout_height="42dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="8dp"
            android:layout_weight="1"
            app:srcCompat="@drawable/fun_icon" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="60dp"
            android:orientation="vertical"
            android:paddingTop="5dp">

            <TextView
                android:id="@+id/categoryLabel"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:text="HEALTH"
                android:textColor="@color/monocolorPallete04"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/cardTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Get in shape for skiing"
                android:textColor="@color/monocolorPallete04"
                android:textSize="20sp"
                app:fontFamily="@font/alegreya_sans_medium_italic" />

        </LinearLayout>
    </GridLayout>


    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="30dp"
        android:layout_marginRight="20dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="10dp"
            android:layout_height="20dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_list_icon" />

        <TextView
            android:id="@+id/goalsCompleted"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:width="50dp"
            android:text="3/4" />

        <TextView
            android:id="@+id/goalsCompletedText"
            android:layout_width="131dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:width="250dp"
            android:text="COMPLETED" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="10dp"
            android:layout_height="20dp"
            android:layout_gravity="top"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_calelndar_icon" />

        <TextView
            android:id="@+id/dateComplete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="FEBRUARY 28" />


    </GridLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="20dp"
        android:orientation="horizontal">

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:progress="75" />
    </LinearLayout>
</LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

这是我的LongTErm页面,该页面调用RecyclerView生成卡片:

    package com.example.hackachieve;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.content.Intent;
import android.widget.ImageView;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import java.util.ArrayList;


public class LongTermPage extends AppCompatActivity{

//        Creating longTermCardVariable(one variable for each card)
    private ImageView ongoingButton;
    private ImageView addButton;
    private ImageView completedButton;

    //vars
    private ArrayList<String> mCardTitle = new ArrayList<>();
    private ArrayList<String> mGoalsCompleted = new ArrayList<>();
    private ArrayList<String> mDataCompleted = new ArrayList<>();
    private ArrayList<Integer> mBoard_id = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_long_term_page);

        initVars();


//        Defining Bottom Buttons
        ongoingButton = (ImageView) findViewById(R.id.ongoingIcon);
        addButton = (ImageView) findViewById(R.id.addIcon);
        completedButton = (ImageView) findViewById(R.id.completedIcon);


        completedButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openLongTermGoalsCompleted();
            }
        });

    }

        public void openLongTermGoalsCompleted(){
            Intent intent = new Intent(this, LongTermPageCompleted.class);
            startActivity(intent);
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }

    private void initVars(){

        mCardTitle.add("Save Money to Buy a Car");
        mGoalsCompleted.add("6");
        mDataCompleted.add("2019-03-14T16:36:25.019Z");
        mBoard_id.add(1);

        mCardTitle.add("Get in shape until winter");
        mGoalsCompleted.add("5");
        mDataCompleted.add("2019-02-14T16:36:25.019Z");
        mBoard_id.add(2);

        mCardTitle.add("Invest money in Bitcoins");
        mGoalsCompleted.add("4");
        mDataCompleted.add("2019-01-14T16:36:25.019Z");
        mBoard_id.add(1);

        mCardTitle.add("Learn Yoga");
        mGoalsCompleted.add("3");
        mDataCompleted.add("2019-04-14T16:36:25.019Z");
        mBoard_id.add(2);

        initRecyclerView();
    }

    private void initRecyclerView(){
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, mCardTitle, mGoalsCompleted,mDataCompleted, mBoard_id);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

}

这是我的Recycler视图文件,我在我m trying t change the background color and the Icon that gives the error, and I tried to execute one isolated or another and didn无法使用的部分之前做了评论:

package com.example.hackachieve;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

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

    private static final String TAG = "RecyclerViewAdapter";
    private ArrayList<String> mCardTitle = new ArrayList<>();
    private ArrayList<String> mGoalsCompleted = new ArrayList<>();
    private ArrayList<String> mDataCompleted = new ArrayList<>();
    private ArrayList<Integer> mBoard_id = new ArrayList<Integer>();
//    private String iconCard;

    public RecyclerViewAdapter(LongTermPage longTermPage, ArrayList<String> mCardTitle, ArrayList<String> mGoalsCompleted, ArrayList<String> mDataCompleted, ArrayList<Integer> mBoard_id) {
        this.mCardTitle = mCardTitle;
        this.mGoalsCompleted = mGoalsCompleted;
        this.mDataCompleted = mDataCompleted;
        this.mBoard_id = mBoard_id;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        View cardType = null;
        if (mBoard_id.get(position) == 1){
            cardType= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_long_term_card_finance, viewGroup,false);
        }
        if (mBoard_id.get(position) == 2){
            cardType = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_long_term_card_health, viewGroup,false);
        }
        View view = cardType;
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.cardTitle.setText(mCardTitle.get(position));
        viewHolder.goalsCompleted.setText(mGoalsCompleted.get(position));
        viewHolder.dateComplete.setText(mDataCompleted.get(position));

        if(mBoard_id.get(position) == 2) {
            viewHolder.categoryLabel.setText("HEALTH");

//         Both command bellow are presenting the same "attempt to invoke virtual method '....' on a null object reference" error
           viewHolder.backgroundHeader.setBackgroundColor(Color.parseColor("#567845"));
           viewHolder.iconCard.setImageResource(R.drawable.health_icon);

        }
        if(mBoard_id.get(position) == 1) {
            viewHolder.categoryLabel.setText("FINANCE");
        }

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{

        TextView cardTitle;
        TextView goalsCompleted;
        TextView dateComplete;
        ImageView iconCard;
        GridLayout backgroundHeader;
        TextView categoryLabel;

        public ViewHolder(View itemView) {
            super(itemView);
            cardTitle = itemView.findViewById(R.id.cardTitle);
            goalsCompleted = itemView.findViewById(R.id.goalsCompleted);
            dateComplete = itemView.findViewById(R.id.dateComplete);
            iconCard = itemView.findViewById(R.id.iconCard);
            backgroundHeader = itemView.findViewById(R.id.backgroundHeader);
            categoryLabel = itemView.findViewById(R.id.categoryLabel);
        }
    }
}

最后,这是我尝试执行程序时显示的完整错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.hackachieve, PID: 12375
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
        at com.example.hackachieve.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:59)
        at com.example.hackachieve.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:18)
        at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:22399)
        at android.view.ViewGroup.layout(ViewGroup.java:6572)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:22399)
        at android.view.ViewGroup.layout(ViewGroup.java:6572)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:22399)
        at android.view.ViewGroup.layout(ViewGroup.java:6572)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:22399)
        at android.view.ViewGroup.layout(ViewGroup.java:6572)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:22399)
        at android.view.ViewGroup.layout(ViewGroup.java:6572)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:22399)
        at android.view.ViewGroup.layout(ViewGroup.java:6572)
        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:1042)
        at android.view.View.layout(View.java:22399)
        at android.view.ViewGroup.layout(ViewGroup.java:6572)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3340)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2804)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1850)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8455)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6981)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
I/Process: Sending signal. PID: 12375 SIG: 9
Application terminated.

如果有人对可以解决的解决方案有所了解,我真的很感激。

谢谢

0 个答案:

没有答案