Search code examples
androidlistviewandroid-cursorloader

Stop refreshing listView on change in Database


I am creating a ListView using cursorLoader. If any changes happen in Database, i don't want to refresh my list data or restart loader. Is there any solution?

Here is how i am loading my data from my database.

@Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

        String SELECTION = MyContactsQuery.SELECTION ;
            return new CursorLoader(SelectContactsForGroup.this, MyContactsProvider.CONTENT_URI, MyContactsQuery.PROJECTION,SELECTION, null, MyContactsQuery.SORT_ORDER);

    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
        if(arg1.getCount() <= 0){
            invitelist.setFastScrollAlwaysVisible(false);
        }else{
            invitelist.post(fitsOnScreen);
        }

        if(!isfromRestartLoader){
            arg1.moveToFirst();
            while(arg1.moveToNext()){
                checkedStates.put(arg1.getString(arg1.getColumnIndex(MyContactsConstants.CONTACT_JID)), false);
            }
            arg1.moveToFirst();
        }
        madapter.swapCursor(arg1);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        if (arg0.getId() == MyContactsQuery.QUERY_ID){
            madapter.swapCursor(null);
        }
    }

And in my onCreate method :

getLoaderManager().initLoader(MyContactsQuery.QUERY_ID, null, (LoaderCallbacks<Cursor>) this);

Solution

  • Since CursorLoarder registers a ContentObserver on the uri you can use another implementation of Loader

    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
    
        String SELECTION = MyContactsQuery.SELECTION ;
        return new AsyncTaskLoader<Cursor>(SelectContactsForGroup.this) {
    
            @Override
            public Cursor loadInBackground() {
                return getContentResolver().query(MyContactsProvider.CONTENT_URI, 
                                                  MyContactsQuery.PROJECTION, 
                                                  SELECTION, 
                                                  null, 
                                                  MyContactsQuery.SORT_ORDER);
            }
        };
    }
    

    this will return a cursor that doesn't have a notification uri and so it'll will not be notified when the db changes