Search code examples
androidsqliteandroid-recyclerviewcursorandroid-lifecycle

Query DB once in Activity life-cycle using Loader


I'm completing a project which use Singleton as pattern an SQLite as Database.

The think is that i do not want to make the select query every time the onCreate method is trigger in the activity lifecycle, instead, what i want is that when the configuration change or when the activity y is recreated the adapter use the same data that was loaded before.

How i'm not using Content Provider I can not use Loader or CursorLoader so I do not know how to do that.

My MainActivity code is the follow:

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));
}

I always use SQLite with providers so this approach is newly for my.

Any suggestion?


Solution

  • I made it using AsyncTaskLoader. Here is the code:

     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);
            }
        }
    }