我遇到了一个简单的自定义列表问题。我尝试了几个例子,最终得到了同样的错误。我一直得到的错误是
java.lang.NullPointerException:尝试从空数组中读取
适配器类:
public class CustomList extends ArrayAdapter<String> {
Context context;
int [] images;
String [] titleArray;
String [] descriptionArray;
CustomList(Context context,String[] titles, int [] images, String [] description) {
super(context,R.layout.single_row,R.id.textView,titles);
this.context = context;
this.images = images;
this.descriptionArray = description;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,parent, false);
ImageView img = (ImageView) row.findViewById(R.id.imageView);
TextView myTxtTitle = (TextView) row.findViewById(R.id.textView);
TextView myTxtDescription = (TextView) row.findViewById(R.id.textView2);
img.setImageResource(images[position]);
myTxtTitle.setText(titleArray[position]); // where error is happening?
myTxtDescription.setText(descriptionArray[position]);
return row;
}}
活动类:
public class MainActivity extends AppCompatActivity {
ListView list;
String [] name;
String [] sound;
int [] images = {
R.drawable.bird,
R.drawable.cat,
R.drawable.cow,
R.drawable.dog,
R.drawable.frog
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
name = res.getStringArray(R.array.title);
sound = res.getStringArray(R.array.description);
list = (ListView) findViewById(R.id.list);
CustomList customAdapter = new CustomList(this, name, images, sound);
list.setAdapter(customAdapter);
}
}
答案 0 :(得分:5)
你只是忘了分配标题数组......因此数组是空引用....
String [] titleArray;
String [] descriptionArray;
CustomList(Context context,String[] titles, int [] images, String [] description)
{
super(context,R.layout.single_row,R.id.textView,titles);
this.context = context;
this.images = images;
this.descriptionArray = description;
//addd this to init the array
this.titleArray = titles;
}
答案 1 :(得分:0)
你需要空检查。
ex)if(titleArray!= null)和if(descriptionArray!= null)
当您尝试使用null数据时会发生这种情况。