Error: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!RecyclerView: Inconsistency detected. Invalid item positionhow to get the object from firebase in android?FirebaseRecyclerAdapter : pass Activity Context to ViewHolderHow to get MultipleView Type by using CursorRecyclerViewAdapter?Added View has RecyclerView as parent but view is not a real childError inflating Class ImageView on RecyclerViewWhen invoked “notifyDataSetChanged() ”of the RecyclerView Adapter,RecyclerView throw “java.lang.Throwable: addInArray ”Picasso recycle view retrofit 2 in grid viewAnimation for recyclerview getting ErrorRecyclerView - java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0

Why do we bend a book to keep it straight?

Do I really need to have a message in a novel to appeal to readers?

Why are there no cargo aircraft with "flying wing" design?

Wu formula for manifolds with boundary

8 Prisoners wearing hats

How to react to hostile behavior from a senior developer?

How do I find out the mythology and history of my Fortress?

Where are Serre’s lectures at Collège de France to be found?

Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?

Can a party unilaterally change candidates in preparation for a General election?

What does できなさすぎる means?

When the Haste spell ends on a creature, do attackers have advantage against that creature?

What would be the ideal power source for a cybernetic eye?

How to compare two different files line by line in unix?

また usage in a dictionary

What is the meaning of the simile “quick as silk”?

What does this Jacques Hadamard quote mean?

Do square wave exist?

Can an alien society believe that their star system is the universe?

Compare a given version number in the form major.minor.build.patch and see if one is less than the other

Is it fair for a professor to grade us on the possession of past papers?

What causes the direction of lightning flashes?

Did MS DOS itself ever use blinking text?

What font is "z" in "z-score"?



Error: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!RecyclerView: Inconsistency detected. Invalid item positionhow to get the object from firebase in android?FirebaseRecyclerAdapter : pass Activity Context to ViewHolderHow to get MultipleView Type by using CursorRecyclerViewAdapter?Added View has RecyclerView as parent but view is not a real childError inflating Class ImageView on RecyclerViewWhen invoked “notifyDataSetChanged() ”of the RecyclerView Adapter,RecyclerView throw “java.lang.Throwable: addInArray ”Picasso recycle view retrofit 2 in grid viewAnimation for recyclerview getting ErrorRecyclerView - java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Im new in Android Studio and Im working in my college capstone project, and I`m trying to generate some cards trough recyclerview.
The problem is that depending on the CardID, I need to change the card Icon and the header card background color, and for both command the program crash and shows that error " Attempt to invoke virtual method....on a null object reference".
I tried different ways to change the images and the background color but with no success, and following the research that I did here, I believe that both command are correct:



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


This is my XML layout file that I`m using to generate the cards:



 <?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>


And this is my LongTErm page that calls the RecyclerView to generate the cards:



 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));





This is my Recycler view file, and I commented before exactly the part that Im trying t change the background color and the Icon that gives the error, and I tried to execute one isolated or another and didnt work:



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);





To finalize, this is the full error that shows when I try to execute my program:



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.


If someone has some idea about what can be the solution to solve it, I really appreciate.



Thank you










share|improve this question






























    0















    Im new in Android Studio and Im working in my college capstone project, and I`m trying to generate some cards trough recyclerview.
    The problem is that depending on the CardID, I need to change the card Icon and the header card background color, and for both command the program crash and shows that error " Attempt to invoke virtual method....on a null object reference".
    I tried different ways to change the images and the background color but with no success, and following the research that I did here, I believe that both command are correct:



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


    This is my XML layout file that I`m using to generate the cards:



     <?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>


    And this is my LongTErm page that calls the RecyclerView to generate the cards:



     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));





    This is my Recycler view file, and I commented before exactly the part that Im trying t change the background color and the Icon that gives the error, and I tried to execute one isolated or another and didnt work:



    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);





    To finalize, this is the full error that shows when I try to execute my program:



    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.


    If someone has some idea about what can be the solution to solve it, I really appreciate.



    Thank you










    share|improve this question


























      0












      0








      0








      Im new in Android Studio and Im working in my college capstone project, and I`m trying to generate some cards trough recyclerview.
      The problem is that depending on the CardID, I need to change the card Icon and the header card background color, and for both command the program crash and shows that error " Attempt to invoke virtual method....on a null object reference".
      I tried different ways to change the images and the background color but with no success, and following the research that I did here, I believe that both command are correct:



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


      This is my XML layout file that I`m using to generate the cards:



       <?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>


      And this is my LongTErm page that calls the RecyclerView to generate the cards:



       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));





      This is my Recycler view file, and I commented before exactly the part that Im trying t change the background color and the Icon that gives the error, and I tried to execute one isolated or another and didnt work:



      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);





      To finalize, this is the full error that shows when I try to execute my program:



      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.


      If someone has some idea about what can be the solution to solve it, I really appreciate.



      Thank you










      share|improve this question
















      Im new in Android Studio and Im working in my college capstone project, and I`m trying to generate some cards trough recyclerview.
      The problem is that depending on the CardID, I need to change the card Icon and the header card background color, and for both command the program crash and shows that error " Attempt to invoke virtual method....on a null object reference".
      I tried different ways to change the images and the background color but with no success, and following the research that I did here, I believe that both command are correct:



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


      This is my XML layout file that I`m using to generate the cards:



       <?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>


      And this is my LongTErm page that calls the RecyclerView to generate the cards:



       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));





      This is my Recycler view file, and I commented before exactly the part that Im trying t change the background color and the Icon that gives the error, and I tried to execute one isolated or another and didnt work:



      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);





      To finalize, this is the full error that shows when I try to execute my program:



      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.


      If someone has some idea about what can be the solution to solve it, I really appreciate.



      Thank you







      java android






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 19:05









      Zoe

      13.8k85586




      13.8k85586










      asked Mar 8 at 19:01









      alexbuzacheroalexbuzachero

      11




      11






















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55069419%2ferror-attempt-to-invoke-virtual-method-void-android-widget-imageview-setimager%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55069419%2ferror-attempt-to-invoke-virtual-method-void-android-widget-imageview-setimager%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          1928 у кіно

          Захаров Федір Захарович

          Ель Греко