我想知道android中用于显示来自数据库的用户数据的正确模式是什么,同时从服务器下载数据。因为用户讨厌在应用程序中等待内容,所以我必须优先考虑数据库提取器,但我认为数据同步可能存在问题(旧数据可能会替换新数据)。
我目前的代码:
public class MyDataFragment extends Fragment implements LoaderManager.LoaderCallbacks<Object> {
private final static int LOADER_DOWNLOAD = 0x02;
private final static int LOADER_DATABASE = 0x03;
private SampleAdapter adapter;
private MainActivity mActivity;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = (MainActivity) activity;
}
public Context getContext() {
if (mActivity != null) {
return mActivity.getApplicationContext();
}
return null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new SampleAdapter();
getLoaderManager().restartLoader(LOADER_DATABASE, null, this);
getLoaderManager().restartLoader(LOADER_DOWNLOAD, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.profile_fragment, container, false);
// create listview and connect to adapter
return v;
}
@Override
public Loader<Object> onCreateLoader(int id, Bundle args) {
switch (id) {
case LOADER_DATABASE:
return new DataLoaderFromDatabase(getContext());
case LOADER_DOWNLOAD:
return new DataLoaderFromRequest(getContext());
}
return null;
}
@Override
public void onLoadFinished(Loader<Object> loader, Object data) {
List<Object> myObjectList = (List) data;
switch (loader.getId()) {
case LOADER_DOWNLOAD:
if (myObjectList.isEmpty()) {
showError();
} else {
adapter.setData(myObjectList);
}
break;
case LOADER_DATABASE:
if (!myObjectList.isEmpty()) {
adapter.setData(myObjectList);
}
break;
}
}
private void showError() {
Toast.makeText(getContext(), "Connection problem", Toast.LENGTH_SHORT).show();
}
@Override
public void onLoaderReset(Loader<Object> loader) {
}
public static class DataLoaderFromRequest extends BetterLoader {
public DataLoaderFromRequest(Context ctx) {
super(ctx);
}
@Override
public Object load() {
RestClient restClient = new RestClient();
//Send request to database
Response response = restClient.sendRequestForData();
if (response.isSucceed()) {
return response.getData();
} else {
return Collections.emptyList();
}
}
}
public static class DataLoaderFromDatabase extends BetterLoader {
public DataLoaderFromDatabase(Context ctx) {
super(ctx);
}
@Override
public Object load() {
//get data from Database
return new Select().all().from(MyModelData.class).queryList();
}
}
}