简体   繁体   中英

How to solve Textview setText() is on a null object reference

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM