我正在尝试使用自定义列表适配器隐藏列表中的列表项。我可以让列表项隐藏,但是当我尝试滚动列表时,我可以出现以下错误:
java.lang.NullPointerException:
Attempt to read from field 'android.widget.TextView com.example.QuestionListAdapter$ViewHolder.tvqid'
on a null object reference
at com.example.QuestionListAdapter.getView(QuestionListAdapter.java:196)
这是我的getView
代码:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Questions questionListItems = contactList.get(position);
hidden = questionListItems.getHidden();
if (rowView == null) {
if (hidden.equals("true")){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.null_item, null);
return rowView;
} else {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.activity_question_view_row, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvqname = (TextView) rowView.findViewById(R.id.name);
viewHolder.tvqid = (TextView) rowView.findViewById(R.id.qid);
rowView.setTag(viewHolder);
}
}
final ViewHolder holder = (ViewHolder) rowView.getTag();
holder.tvqid.setText(qid); //ERROR IS HERE
holder.tvqname.setText(qname);
return rowview;
}
错误在.setText上,因为它正在尝试设置空项的文本。但我已经尝试将hidden.equals("true")
检查放在.setText
上,但它仍会导致应用崩溃。
我还尝试使用以下代码而不是上面的代码,下面的代码删除了列表项并使列表可滚动。但它留下了一个白色空间,其中列出了这些列表项目。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Questions questionListItems = contactList.get(position);
hidden = questionListItems.getHidden();
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.activity_question_view_row, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvqname = (TextView) rowView.findViewById(R.id.name);
viewHolder.tvqid = (TextView) rowView.findViewById(R.id.qid);
rowView.setTag(viewHolder);
}
final ViewHolder holder = (ViewHolder) rowView.getTag();
holder.tvqid.setText(qid); //ERROR IS HERE
holder.tvqname.setText(qname);
if (hidden.equals("true")){
rowView.setVisibility(View.GONE);
} else {
rowView.setVisibility(View.VISIBLE);
}
return rowview;
}
另外,在上面的第二个代码片段中。我尝试使用rowView = new Space(this)
而不是将可见性设置为GONE,但滚动时崩溃了应用程序。
答案 0 :(得分:1)
我认为您应该使用您提供给适配器的阵列而不是适配器的视图。 基本上要隐藏一个元素,你需要将它从Adapter的数组中删除。没有什么能阻止你在其他地方(或在适配器本身)保留完整数组的副本。
例如,当您想要更新ListView时,您可以在适配器之外的片段/活动中执行以下操作,在其中为您提供ArrayList of Questions:
ArrayList<Questions> questionListItemsInAdapter = new ArrayList<>();
for(Questions questions:questionListItems)
if(!questions.getHidden())
questionListItemsInAdapter.add(questions);
adapter.bind(questionListItemsInAdapter);
adapter.notifyDataSetChanged();