0

How to check inside UI whether data exist in a table? By using Loader or just query()?

Which way is better?

1) Using Loader.

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getActivity().getSupportLoaderManager().restartLoader(POPULATE_CATEGORY_LIST_VIEW_LOADER, null, this);

    } 


        @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

        switch (loader.getId()) {
            case POPULATE_CATEGORY_LIST_VIEW_LOADER:

                if (!data.moveToFirst()) {

                    // load data from server and store data to db

                }

                break;
            default:
                break;
        }
    }

2) Using getContentResolver().query() from UI

        Cursor locationCursor = getContext().getContentResolver().query(
                MenuContract.CategoryEntry.CONTENT_URI,
                new String[]{MenuContract.CategoryEntry._ID},
                null,
                null,
                null);

        if(!locationCursor.moveToFirst()) {
            // load data from server and store data to db
        }

I just need to check whether data exist id db. Then if there are no data in a table, load data from server and put to an Adapter, otherwise just put data to the Adapter. How to do it correctly using Loaders?

I understood that in both ways we need to wait until data base gives an answer. So maybe just querying a Cursor is enough for this task or it is bad practice to query data base from UI thread directly?

DeniSHow
  • 1,394
  • 1
  • 18
  • 30

1 Answers1

1

It's highly recommended to do database queries in a separate thread but if the data you're querying is very small then you can do it in the UI thread without induce lag.

Bubu
  • 1,533
  • 14
  • 14