我正在使用基本适配器并使用不同数组列表的相应元素填充每个列表项的各种组件。我使用以下代码:
public class OfflineAdapter extends BaseAdapter {
static Context context;
static int layoutResourceId;
ArrayList<String> qid = new ArrayList<String>();
ArrayList<String> author = new ArrayList<String>();
ArrayList<String> title = new ArrayList<String>();
ArrayList<String> vote = new ArrayList<String>();
public OfflineAdapter(Context c,int layoutResourceId,ArrayList<String> qid,ArrayList<String> author,ArrayList<String> title,ArrayList<String> vote)
{
//super(c,layoutResourceId,qid,author,title,vote);
this.context = c;
this.layoutResourceId = layoutResourceId;
this.qid = qid;
this.author = author;
this.title = title;
this.vote = vote;
}
@Override
public int getCount() {
return 20;
}
@Override
public Object getItem(int position) {
return qid.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
QuestionHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new QuestionHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.questionTitle);
holder.txtTitle2 = (TextView)row.findViewById(R.id.questionAuthor);
holder.txtTitle3 = (TextView)row.findViewById(R.id.questionVotes);
holder.txtTitle4 = (TextView)row.findViewById(R.id.questionID);
row.setTag(holder);
}
else
{
holder = (QuestionHolder)row.getTag();
}
//Question hold = data[position];
//if(hold!=null) {
holder.txtTitle.setText(Html.fromHtml(title.get(position)));
holder.txtTitle2.setText(author.get(position));
holder.txtTitle3.setText(vote.get(position));
holder.txtTitle4.setText(qid.get(position));
//}
return row;
}
static class QuestionHolder
{
TextView txtTitle;
TextView txtTitle2;
TextView txtTitle3;
TextView txtTitle4;
}
但是我收到以下错误:
尝试在空对象引用上调用虚方法'java.lang.Object java.util.ArrayList.get(int)'
在这一行:
holder.txtTitle.setText(Html.fromHtml(title.get(position)));
可能是什么原因? 我已经初始化了所有数组列表,但没有一个是null。
谢谢!
答案 0 :(得分:3)
首先,对于干净的代码和更好的编程习惯,而不是像你一样创建 4个字符串列表:
ArrayList<String> qid = new ArrayList<String>();
ArrayList<String> author = new ArrayList<String>();
ArrayList<String> title = new ArrayList<String>();
ArrayList<String> vote = new ArrayList<String>();
使用 4个参数(qid,作者,标题,投票)创建Object
public class YourObject implements Serializable{
public String qid;
public String author;
public String title;
public String vote;
}
并将该对象的单个列表传递给adapter
;
ArrayList<YourObject> objList = new ArrayList<YourObject>();
然后在getCount()
方法返回objList.size()
答案 1 :(得分:0)
你已经初始化了所有的ArrayLists但是你没有使用它们,你使用在构造函数中传递的任何东西。标题列表很可能为null,因为您在构造函数中传递了null。检查如何调用适配器的构造函数以及传递哪些引用。