由于here中所述,自Android P(API 28)起已不再使用加载程序:加载程序,因此我决定在我的应用中使用ViewModel
和LiveData
,但不幸的是几乎没有教程和资源,幸运的是,我发现这篇blog帖子在谈论它。
在MainActivity中使用OrmLite
ItemsDBHelper itemsDBHelper;
private static RuntimeExceptionDao<Item, Integer> runtimeExceptionDaoItems;
我使用AsyncTask这样存储/兑现数据
static class SaveInDatabase extends AsyncTask<Item, Void, Void> {
@Override
protected Void doInBackground(Item... items) {
List<Item> itemsList = Arrays.asList(items);
runtimeExceptionDaoItems.create(itemsList);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// itemsDBHelper.close();
}
}
并检索:
runtimeExceptionDaoItems.queryForAll()
当前,如果存在连接,我使用翻新回调从服务器获取数据并将其存储到db中,以便在没有连接的情况下从数据库中检索数据
final Call<PostList> postList = BloggerAPI.getService().getPostList(url);
postList.enqueue(new Callback<PostList>() {
@Override
public void onResponse(@NonNull Call<PostList> call, @NonNull Response<PostList> response) {
if (response.isSuccessful()) {
progressBar.setVisibility(View.GONE);
PostList list = response.body();
if (list != null) {
token = list.getNextPageToken();
items.addAll(list.getItems());
adapter.notifyDataSetChanged();
SaveInDatabase task = new SaveInDatabase();
Item[] listArr = items.toArray(new Item[0]);
task.execute(listArr);
}
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
}
@Override
public void onFailure(@NonNull Call<PostList> call, @NonNull Throwable t) {
Toast.makeText(MainActivity.this, "Error occured", Toast.LENGTH_LONG).show();
Log.e(TAG, "onFailure: " + t.toString());
Log.e(TAG, "onFailure: " + t.getCause());
}
});
当前,我创建ItemViewModel类,并为这样的应用程序自定义:
public class ItemViewModel extends AndroidViewModel {
private final String TAG = this.getClass().getName();
private LiveData<List<Item>> listItems;
public ItemViewModel(@NonNull Application application) {
super(application);
}
public class ItemLiveData extends LiveData<List<Item>> {
private final Context context;
public ItemLiveData(Context context) {
this.context = context;
loadData();
}
// Here data must be called either from the server (Retrofit) or from the database
private void loadData() {
new AsyncTask<Void,Void,List<Item>>() {
@Override
protected List<Item> doInBackground(Void... voids) {
List<Item> items = new ArrayList<>();
return items;
}
@Override
protected void onPostExecute(List<Item> items) {
super.onPostExecute(items);
}
}.execute();
}
}
}
它像这样
ItemViewModel model =
ViewModelProviders.of(this).get(Item.class);
model.getData().observe(this, data -> {
// update UI
});
在上一课中,我应该使用什么方法将数据存储到其中?