如何在從服務數據庫更新數據時重新運行加載程序以更新適配器數據?如何在服務器更改數據庫時重新運行加載程序
DataPullService:
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();
}
}
MyListFragment:
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);
}
}
上述代碼負載數據時片段created.Then如何更新此列表片段每當在DB改變的數據(由更新DataPullService)?
是的,如何從Service.getLoaderManager中調用getLoaderManager僅在Activity和fragment中可用 – Ramprasad
是的,如何從服務重啓Loader – Ramprasad