每当从服务更新数据库中的数据时,如何重新运行加载程序以更新适配器数据?
数据拉取服务:
public class DataPullService extends Service {
private Timer nstimer=new Timer();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NetworkConnection network=new NetworkConnection(this.getApplicationContext());
boolean online = network.isOnline();
if(online){
try {
nstimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
DBHelper dbHelper=new DBHelper(getApplicationContext());
SQLiteDatabase mydb = dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DBConstants.COMPANY, "Innodea");
mydb.insert(DBConstants.FAVORITE_TABLE, null, values);
}
}, 0, 60000);
} catch (Exception e) {
}
}
return startId;
}
@Override
public void onDestroy() {
super.onDestroy();
nstimer.cancel();
}
}
我的列表片段:
public class MyListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private SimpleCursorAdapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("List loading...");
setHasOptionsMenu(true);
mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_2, null, new String[]{DBConstants.SNO,DBConstants.COMPANY}, new int[]{android.R.id.text1,android.R.id.text2});
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
DBHelper dbHelper=new DBHelper(getActivity());
return new LiveMyLoader(getActivity(),dbHelper);
}
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
mAdapter.swapCursor(c);
setListAdapter(mAdapter);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
}
上面的代码在创建片段时加载数据。那么当DB中的数据发生变化时如何更新这个列表片段(由DataPullService更新)?