T B
T B

Reputation: 221

Update or Refresh UI with the update of database android

I have an image gallery. I have to show images with uploaded or not uploaded icon. A service is running in the background to upload the images and update the database.Suppose i am in gallery screen and some not uploaded images has been uploaded and update database. So i want to update my view without press any button.

whenever database is getting updated, is there any way i can get callback ?? what is the best approach to update my view without reload all??

Upvotes: 2

Views: 2153

Answers (3)

Yvan RAJAONARIVONY
Yvan RAJAONARIVONY

Reputation: 571

You can use loader for this. Loaders have these characteristics:

  • They are available to every Activity and Fragment.
  • They provide asynchronous loading of data.
  • They monitor the source of their data and deliver new results when the content changes.
  • They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.

Find here a get started help.

So :

  • First you should init you loader like this:

getLoaderManager().initLoader([YOUR_LOADER_ID], null, this);

  • Define loading instruction in onCreateLoader() :

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    // You can return other type than cursor or create your own custom cursorloader but I guess that cursor is right fro you since you want load database content.
    
    Uri baseUri = [you media uri , suppose that you sue content provider];
    
    return new CursorLoader(getActivity(), baseUri,
            [projection], [select], [arg],
            [orderby]);
    

    }

  • You get onLoadFinished() callback when data finishes to be loaded :

    public void onLoadFinished(Loader loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); }

In your case, loader monitors every change in gallery database. So everytime there is a change, swap cursor is called automatically, then your view is updated according what you defined in your adapter.

Upvotes: 0

AmaJayJB
AmaJayJB

Reputation: 1453

Two possible ways to update the UI would be:

  • NotifyDatasetChanged() method which can be used if you are using an adapter to display the images (I would assume you are using an adapter for your gallery). You can call this method each time an upload completes which would then tell the view to update itself.

  • Otherwise maybe run an AsyncTask which checks the status of the upload every so often and in the onProgressUpdate() method have a callback to your UI thread to update that the image has been uploaded.

I hope this helps.

Upvotes: 0

ksarmalkar
ksarmalkar

Reputation: 1894

You will need to use CursorLoaders/CursorAdapters. You can find an example here

https://github.com/ksarmalkar/ContentProviderJoin

Upvotes: 1

Related Questions