YP_be
YP_be

Reputation: 731

Doing multiple counts on content provider (best practice?)

I'm making an Android application for managing projects. Each project in my project table has a project_status column with a value of 0 (planned), 1 (current) or 2 (finished project).

In one of the fragments in my app I'm giving the user an overview how many projects he has of each type.

So for example

24 finished 3 current 10 planned

I'm using a content provider to interact with my DB. At the moment I can get a single count for one of the 3 statuses with this code (normal loader):

@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
  return new android.support.v4.content.CursorLoader(this.getActivity(), ProjectDbProvider.CONTENT_URI, new String[] {"count(*) AS count"}, ProjectsTable.COLUMN_STATUS_PROJECT + "=?", new String[] {"2"}, null);
}

And when that's loaded I have this code to get the count:

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    TextView textViewFinished = (TextView) getActivity().findViewById(R.id.btn_proj_finished);
    cursor.moveToFirst();
    String count = String.valueOf(cursor.getInt(0));
    textViewFinished.setText(count);
}


This works perfectly.
Now I'm just wondering what the best way / best practice is to get the count for all 3 statuses at the same time? Should I just load a normal cursor (no count) of all my projects and iterate over it in my onloadfinished? Or should I make 3 loaders (or does this asks too much from the device?). Or should I handle this in my contentprovider?

Thanks in advance.

Upvotes: 0

Views: 129

Answers (1)

Dries De Smet
Dries De Smet

Reputation: 876

You answered it yourself. You just create 3 different loaders. The weight on the device is really minor. Of course it would be for the best that you could minimize the queries to the database, but Android has minimized the effort to handle SQLite database queries.

Sidenote: to be transparent, I would opt - in my opinion - to just create three loaders that query for all instances of the where clause, and not the count. If you do this, you get a Cursor in return and you can do cursor.getCount() to get the count. Also with this, your device will not be heavily afflicted and you will have a more transparent way of how you handle your content.

Upvotes: 1

Related Questions