Android BaseAdapter处理空ArrayList

时间:2012-04-24 15:44:37

标签: java android listview baseadapter

我正在尝试使用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(不是最好的,我知道)。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:6)

getCount返回0,以避免NPE:

public int getCount() {
    return (samples == null) ? 0 : samples.size();
}