Java 如何修复ListView中的NullPointerException?
我在使用自定义适配器创建ListView时遇到一个NullPointerException,但我不知道导致错误的代码部分。以下是代码片段: ChatMessageAdapter.javaJava 如何修复ListView中的NullPointerException?,java,android,nullpointerexception,Java,Android,Nullpointerexception,我在使用自定义适配器创建ListView时遇到一个NullPointerException,但我不知道导致错误的代码部分。以下是代码片段: ChatMessageAdapter.java package com.myappcompany.rajan.thefictionalchat; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotati
package com.myappcompany.rajan.thefictionalchat;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ChatMessageAdapter extends ArrayAdapter<ChatText> {
ChatMessageAdapter(Context context, ArrayList<ChatText> list) {
super(context, 0, list);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View currentView = convertView;
if(currentView==null) {
LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}
ChatText chatText = getItem(position);
TextView textView;
textView = (TextView)currentView.findViewById(R.id.chat_text);
textView.setText(chatText.getMessage());
if(chatText.getMessageType().equals("PERSON_1")) {
textView.setGravity(Gravity.LEFT);
}
else if(chatText.getMessageType().equals("PERSON_2")) {
textView.setGravity(Gravity.RIGHT);
}
else {
textView.setGravity(Gravity.CENTER_HORIZONTAL);
}
return currentView;
}
}
对视图进行充气,但不将充气视图保存到
currentView
更改此代码:
View currentView = convertView;
if(currentView==null) {
LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}
为此:
View currentView = convertView;
if(currentView==null) {
currentView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}
您需要从父视图所在的位置查找视图
View rootView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
TextView textView ;
textView = rootView.findViewById(R.id.chat_text);
View currentView = convertView;
if(currentView==null) {
currentView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}
View rootView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
TextView textView ;
textView = rootView.findViewById(R.id.chat_text);