0

So I get this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

I ran the debugging tool and these lines are null:

TextView leftMessageView = (TextView) row.findViewById(R.id.leftmsgr);
leftMessageView.setText(Servermessage);

This is the function where its coming from:

public View getView(int position, View convertView, @NonNull ViewGroup parent) {

    View row;
    LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ChMessage chMessageObj = getItem(position);
    if (chMessageObj.left) {
        row = inflater.inflate(R.layout.leftmessage, parent, false);
    }else{
        row = inflater.inflate(R.layout.rightmessage, parent, false);
    }

        TextView rightMessageView = (TextView) row.findViewById(R.id.rightmsgr);
        TextView leftMessageView = (TextView) row.findViewById(R.id.leftmsgr);
        rightMessageView.setText(chMessageObj.message);
        leftMessageView.setText(Servermessage);

    return row;
}

Not sure why its not null?

Any Help would be great!

Thanks

  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Mosius Oct 12 '18 at 18:21
  • It looks like at least one of the views you're trying to reference in your layout cannot be found. Double check to make sure that you have a TextView in your layout that corresponds to the view ids your referencing. – Michael Krause Oct 12 '18 at 19:25

1 Answers1

0

Try to fix the NullPointerException with this code:

public View getView(int position, View convertView, @NonNull ViewGroup parent) 
{   
    View row;
    LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ChMessage chMessageObj = getItem(position);
    if (chMessageObj.left) {
        row = inflater.inflate(R.layout.leftmessage, parent, false);
    }else{
        row = inflater.inflate(R.layout.rightmessage, parent, false);
    }

        TextView rightMessageView = (TextView) row.findViewById(R.id.rightmsgr);
        TextView leftMessageView = (TextView) row.findViewById(R.id.leftmsgr);
        if (rightMessageView!=null) {
          rightMessageView.setText(chMessageObj.message);
        }
        if (leftMessageView!=null) {
          leftMessageView.setText(Servermessage);
        }

    return row;
}

Then, I don't if it is correct that the TextView is null. Check your XML layout. Hope it helps.

xcesco
  • 4,690
  • 4
  • 34
  • 65