This question already has an answer here:
- What is a NullPointerException, and how do I fix it? 12 answers
- Using context in a fragment 26 answers
I am currently trying to change the colour of an imageview. I am trying to do this from a fragment, and it works fine until I switch activities. When I return to the fragment that I use to change the colour of the image I get this error,
Attempt to invoke virtual method 'int android.content.Context.getColor(int)' on a null object reference
I use the following code to change the colour of my image,
imgUpvote.setColorFilter(ContextCompat.getColor(getContext(), R.color.lGrey));
Anyone know a fix? This error only occurs when I switch activities, thanks for any answers.
EDIT:here is where code is located,
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<postsGetInfo, postsGetInfoViewHolder>(postsGetInfo.class, R.layout.posts_layout,postsGetInfoViewHolder.class,postRef) {
@Override
protected void populateViewHolder(final postsGetInfoViewHolder viewHolder, postsGetInfo model, int position) {
final String postKey = getRef(position).getKey();
UpdateTheDisplayVotes(postKey); //Displays the votes at the start of creation
postRef.removeEventListener(VoteListener);
defaultVote = VotesRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(postKey)) {
VotesRef.child(postKey).child(current_user_id).child("votes").setValue("none");
}
String voteStatus = dataSnapshot.child(postKey).child(current_user_id).child("votes").getValue().toString();
if (voteStatus.equals("upvoted")){
ImageView btnUpvote = viewHolder.myView.findViewById(R.id.imgUpvote);
ImageView btnDownvote = viewHolder.myView.findViewById(R.id.imgDownvote);
btnUpvote.setColorFilter(ContextCompat.getColor(getActivity(), R.color.lBlue));
btnDownvote.setColorFilter(ContextCompat.getColor(getActivity(), R.color.lGrey));
}if (voteStatus.equals("downvoted")){
ImageView btnUpvote = viewHolder.myView.findViewById(R.id.imgUpvote);
ImageView btnDownvote = viewHolder.myView.findViewById(R.id.imgDownvote);
btnUpvote.setColorFilter(ContextCompat.getColor(getActivity(), R.color.lGrey));
btnDownvote.setColorFilter(ContextCompat.getColor(getActivity(), R.color.Black));
}if (voteStatus.equals("none")){
ImageView btnUpvote = viewHolder.myView.findViewById(R.id.imgUpvote);
ImageView btnDownvote = viewHolder.myView.findViewById(R.id.imgDownvote);
btnUpvote.setColorFilter(ContextCompat.getColor(getActivity(), R.color.lGrey));
btnDownvote.setColorFilter(ContextCompat.getColor(getActivity(), R.color.lGrey));
}
}