ActionBarActivity を拡張する MainActivity には ListView があり、これを使用してリロードしたいのですが、これnotifyDataSetChanged()
を行う方法がわかりません。
これまでの私のコード:
public class MainActivity extends ActionBarActivity {
private JournalEntryDataSource datasource;
private ListView listView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new JournalEntryDataSource(this);
datasource.open();
listView = (ListView) findViewById(R.id.list);
List<JournalEntry> values = datasource.getAllJournalEntries();
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Log.i("app", "Deleting item number " + position);
datasource.deleteJournalEntry((JournalEntry) listView.getAdapter().getItem(position));
//I would like to do this here:
//ArrayAdapter<JournalEntry> adapter = (ArrayAdapter<JournalEntry>) getListAdapter();
//adapter.notifyDataSetChanged();
}
});
}
しかし、呼び出すとエラーが発生しadapter.notifyDatasetChanged()
ます...
任意のヒント?私は同様の質問を見てきましたが、これまでのところ運がありません... --------編集されたコード---------
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new JournalEntryDataSource(this);
datasource.open();
listView = (ListView) findViewById(R.id.list);
values = datasource.getAllJournalEntries();
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
ArrayAdapter<JournalEntry> adapter = (ArrayAdapter<JournalEntry>) getListAdapter();
// use the SimpleCursorAdapter to show the
// elements in a ListView
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
listView.setLongClickable(true);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
Log.i("hola","borrando la posición "+position);
JournalEntry removeMe = (JournalEntry)listView.getAdapter().getItem(position);
values.remove(removeMe);
datasource.deleteJournalEntry(removeMe);
//adapter.notifyDataSetChanged();
reloadMe();
return true;
}
});
}
public void reloadMe(){
//need to do this better... but meh.
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
protected ListView getListView() {
if (listView == null) {
listView = (ListView) findViewById(android.R.id.list);
}
return listView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}