ベースアダプタを使用してListListにArrayListを設定しようとしています。 ArrayListにはデータベースが設定されており、アプリケーションが初めて起動されたときなど、データベースにはエントリが存在しないため、空のArrayListが存在する可能性があります。 ArrayListが空のとき、私は非スクリプト "java.lang.RuntimeException:アクティビティComponentInfo ... java.lang.NullPointerExceptionを開始できません"を受け取ります。Android BaseAdapter空のArrayListを扱う
私の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(ヌル)は、私が設定している空のリストビューを表示するには、アプリを取得します。しかし、それを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(最高ではない、私が知っている)を使用しています。どんな助けでも大歓迎です。
本当にありがとうございました。私の空のListViewは、アプリケーションが初めて起動したときに表示されますが、データベースのすべてのエントリを削除し、ArrayListを更新してsa.notifyDataSetChanged()を呼び出すとNPEが戻ってきます。何かご意見は? –