CursorLoader usage without ContentProvider

前端 未结 5 627

Android SDK documentation says that startManagingCursor() method is depracated:

This method is deprecated. Use the new CursorLoader class

5条回答
  •  一个人的身影
    2020-11-22 13:12

    The third option proposed by Timo Ohr, together with the comments by Yeung, provide the simplest answer (Occam's razor). Below is an example of a complete class that works for me. There are two rules for using this class.

    1. Extend this abstract class and implement methods getCursor() and getContentUri().
    2. Any time that the underlying database changes (e.g., after an insert or delete), make sure to call

      getContentResolver().notifyChange(myUri, null);
      

      where myUri is the same one returned from your implementation of method getContentUri().

    Here is the code for the class that I used:

    package com.example.project;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.content.CursorLoader;
    import android.content.Loader;
    
    public abstract class AbstractCustomCursorLoader extends CursorLoader
      {
        private final Loader.ForceLoadContentObserver mObserver = new Loader.ForceLoadContentObserver();
    
        public AbstractCustomCursorLoader(Context context)
          {
            super(context);
          }
    
        @Override
        public Cursor loadInBackground()
          {
            Cursor cursor = getCursor();
    
            if (cursor != null)
              {
                // Ensure the cursor window is filled
                cursor.getCount();
                cursor.registerContentObserver(mObserver);
              }
    
            cursor.setNotificationUri(getContext().getContentResolver(), getContentUri());
            return cursor;
          }
    
        protected abstract Cursor getCursor();
        protected abstract Uri getContentUri();
      }
    

提交回复
热议问题