我正在完成一个项目,该项目使用Singleton作为模式,SQLite作为数据库。
我认为每次在活动生命周期中触发onCreate方法时我都不想生成select查询,相反,我想要的是当配置更改或重新创建活动y时,适配器使用之前加载的相同数据。
我如何不使用Content Provider我不能使用Loader或CursorLoader,所以我不知道该怎么做。
我的MainActivity代码如下:
RecyclerView recyclerView;
public Cursor cursor;
InsectRecyclerAdapter insectAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(this);
cursor = DatabaseManager.getInstance(this).queryAllInsects("friendlyName"); //EVERY TIME THIS METHOD IS TRIGGER EXECUTE THE QUERY..AND I DON'T WANT THAT.
insectAdapter = new InsectRecyclerAdapter(this, cursor);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setAdapter(insectAdapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
我总是将SQLite与提供者一起使用,所以这种方法对我来说是新的。
有什么建议吗?
答案 0 :(得分:1)
我是使用AsyncTaskLoader制作的。这是代码:
public abstract class SimpleCursorLoader extends AsyncTaskLoader<Cursor> {
private Cursor mCursor;
public SimpleCursorLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
//If the cursor is null call loadInBackground else deliverResult
if (mCursor != null) {
deliverResult(mCursor);
}
if (takeContentChanged() || mCursor == null) {
forceLoad();
}
}
@Override
public Cursor loadInBackground(){
mCursor = DatabaseManager.getInstance(MainActivity.this).queryAllInsects(MainActivity.FILTER);
return mCursor;
}
/* Runs on the UI thread */
@Override
public void deliverResult(Cursor cursor) {
if (isReset()) {
// An async query came in while the loader is stopped
if (cursor != null) {
insectAdapter.swapCursor(cursor);
}
return;
}
mCursor = cursor;
if (isStarted()) {
super.deliverResult(cursor);
}
}
}