我有一個多行listview,使用hashmaps實現。我從數據庫中獲取數據。使用hashmap時刷新listview
我有另一個活動,我正在添加我的項目,它正在被添加到數據庫。現在當按下保存按鈕時,新添加的項目應該立即顯示在片段中實現的列表視圖中。我無法弄清楚如何刷新此活動中的列表視圖。
這裏是我的片段執行列表視圖:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_layout, container, false);
l = db.getAllEntries();
list = (ListView) myView.findViewById(R.id.entrylist);
mylist = new ArrayList<HashMap<String,String>>();
HashMap<String,String> item;
while(!l.isEmpty()){
e = l.get(0);
l.remove(0);
item = new HashMap<String,String>();
item.put("line1", e._totime + " - " + e._totime);
item.put("line2", e._subject);
item.put("line3", e._place);
mylist.add(n++,item);
}
sa = new SimpleAdapter(getActivity(), mylist,
R.layout.multi_line,
new String[] { "line1","line2", "line3" },
new int[] {R.id.line_a, R.id.line_b, R.id.line_c});
list.setAdapter(sa);
return myView;
}
這裏這個活動我加入項目數據庫,應立即出現在我的列表視圖上面:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
sub = subject.getText().toString();
teach = teacher.getText().toString();
pla = place.getText().toString();
da = day.getSelectedItem().toString();
fro = fromtime.getText().toString();
to = totime.getText().toString();
i = new Entries(sub,teach,pla,da,fro,to);
db.addEntry(i);
FragmentView1 f = (FragmentView1) this.getSupportFragmentManager().findFragmentByTag(FragmentView1.class.getName());
l = db.getAllEntries();
HashMap<String,String> map;
while(!l.isEmpty()){
e = l.get(0);
l.remove(0);
map = new HashMap<String,String>();
map.put("line1", e._fromtime + " - " + e._totime);
map.put("line2", e._subject);
map.put("line3", e._place);
f.getArrayList().add(n++,map); //nullpointerexception here
}
f.getMyListAdapter().notifyDataSetChanged();
/*Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.save) + " menu option",
Toast.LENGTH_SHORT).show();*/
return true;
default:
return super.onOptionsItemSelected(item);
}
}
((YourActivityName)getActivity())。setfragmentView1Tag(tag)給我classcastexception,實際上我試圖在其他活動中調用片段,而不是主要活動(此片段的父活動) – user1304
您可以將更新從其他活動保存到數據庫。並且爲了更新列表中的結果(包含在另一個活動的片段中),您可以在Fragment類的onResume()回調方法中編寫更新代碼,而不是嘗試調用其任何方法。所以無論什麼時候片段進入焦點,它總是會獲取數據庫中的更新數據。欲瞭解更多信息:[片段生命週期](http://developer.android.com/guide/components/fragments.html) – andro