[英]How to solve Textview setText() is on a null object reference
所以我得到这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
我运行了调试工具,这些行为空:
TextView leftMessageView = (TextView) row.findViewById(R.id.leftmsgr);
leftMessageView.setText(Servermessage);
这是它来自的功能:
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;
}
不知道为什么它不为空?
任何帮助将是巨大的!
谢谢
尝试使用以下代码修复NullPointerException
:
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;
}
然后,如果TextView为null是否正确,我就不知道。 检查您的XML布局。 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.