我正在尝试使用基本适配器使用 ArrayList> 填充 ListView。ArrayList 由数据库填充,并且数据库可能没有条目,因此是一个空的 ArrayList,例如在第一次启动应用程序时。当 ArrayList 为空时,我收到一个非脚本“java.lang.RuntimeException:无法启动活动 ComponentInfo ... java.lang.NullPointerException”。
我的 onCreate 方法如下所示:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.samples_list_layout);
mContext = getApplicationContext();
lv = getListView();
list = myDatabase.getInstance(mContext).getAllSamples();
sa = new SamplesAdapter(this, list);
lv.setAdapter(sa);
registerForContextMenu(lv);
}
设置 lv.setAdapter(null) 将使应用程序显示我设置的空列表视图。但是,当我把它留给 BaseAdapter 时,我得到了错误。我遵循了 2 个 Android List8.java 和 List14.java 示例,无论哪种方式都给出了相同的结果。我的 BaseAdapter 类如下所示:
public class SamplesAdapter extends BaseAdapter {
private static final String SAMPLE_NAME_COL = "name";
private static final String SAMPLE_HOST_COL = "host";
private static final String SAMPLE_ICON_COL = "icon";
private static final String SAMPLE_MODIFIED_STAMP_COL = "moddate";
private Context mContext;
private ArrayList<HashMap<String, String>> samples = new ArrayList<HashMap<String, String>>();
public SamplesAdapter(Context c, ArrayList<HashMap<String, String>> list){
mContext = c;
samples = list;
}
public int getCount() {
return samples.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.samples_row_layout, parent, false);
TextView name = (TextView) v.findViewById(R.id.samples_name);
name.setText(samples.get(position).get(SAMPLE_NAME_COL));
TextView host = (TextView) v.findViewById(R.id.samples_host);
host.setText(samples.get(position).get(SAMPLE_HOST_COL));
TextView moddate = (TextView) v.findViewById(R.id.samples_mod_stamp);
moddate.setText(samples.get(position).get(SAMPLE_MODIFIED_STAMP_COL));
return v;
}
}
我还应该注意,当有要显示的内容时,ListView 会正确显示项目。只有当 ArrayList 为空时才会失败。另外,我使用的是 Android 2.2(不是最好的,我知道)。任何帮助将不胜感激。