问题
I create a custom dialog with DialogFragment, and in the dialog, I can add some data to the SQLite database. Also, there is a listview in the main activity, which show the data of the SQLite.
I want to refresh the listview when I add the data to the database from the dialog. However, I have some problems.
I call the notifyDataSetChanged() in the onResume(), but the listview doesn't refresh when I dismiss the dialog. And if I press the home button and open the activity from the recent list, the listview will refresh.
@Override
protected void onResume() {
super.onResume();
listItem.clear();
ServerListDB db = new ServerListDB(context);
Cursor cursor = db.select();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("serverName", String.valueOf(cursor.getString(1)));
map.put("serverIp", cursor.getString(2));
map.put("serverPort", cursor.getString(3));
listItem.add(map);
}
notifyDataSetChanged();
}
I add the log.v in the onPause(), and when the dialog show, the onPause() isn't called. Is this right for DialogFragment?
@Override
protected void onPause() {
super.onPause();
Log.v("Pause", "onPause() called!");
}
回答1:
Your dialog fragment will be tied to activity. One simple approach is to notify your parent activity directly from dialog, as described here:
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
Based on this, I would create an Interface
that Activity
must implement in order to get a callback when database is updated and to reload a list (or whatever):
public interface OnDBUpdatedListener {
public void OnDBUpdated();
}
In your activity(s) you implement this interface:
public void OnDBUpdated() {
// Reload list here
}
In your dialog fragment, when you save data or when you are dismissing the dialog, put the following code:
(OnDBUpdatedListener)getActivity()).OnDBUpdated()
来源:https://stackoverflow.com/questions/16321155/how-to-refresh-the-listview-after-change-the-data-with-the-dialogfragment