0

我閱讀了很多文章和指南,但在使用LoaderManagerSQLite數據庫獲取數據時,我仍然遇到很多問題。如何刷新LoaderManager

我一直在爲它掙扎超過一個星期,並且我多次編輯我的代碼,遵循許多不同的例子,但問題仍然存在。

首先,我不得不說我的AsyncTaskLoader返回由我創建的對象列表,所以我不能依靠CursorLoader方法來「刷新」查詢。

這是我AsyncTaskLoader從中我得到的MyContact

public class MyLoader extends AsyncTaskLoader<List<MyContact>>{ 
    private List<MyContact> myContacts; 
    private Bundle bundle; 

    public MyLoader(Context context, Bundle bundle) { 
     super(context); 
     this.bundle = bundle; 
    } 

    public List<MyContact> loadInBackground(){ 
     myContacts = //here I build my List of MyContact with data taken from a DB 
     return myContacts; 
    }  
} 

列表這是我的活動,我實現LoaderManager方法:

public class ContactsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<MyContact>>{ 

    private LoaderManager loaderManager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     loaderManager = getLoaderManager();  
     loaderManager.initLoader(1, null, this);  
    } 

    .... 
    @Override 
    public Loader<List<MyContact>> onCreateLoader(int i, Bundle bundle) { 
     return new MyLoader(this, bundle); 
    } 

    @Override 
    public void onLoadFinished(Loader<List<MyContact>> loader, List<MyContact> myContacts) { 
      Here I fill a RecyclerView with myContacts 
    } 

    @Override 
    public void onLoaderReset(Loader<List<MyContact>> loader) { 
    } 
} 

我的問題是,更新數據庫後,我應該通過「刷新」loaderManager來獲得MyContacts的更新列表。我不會告訴你我試圖達到目標的所有不同方式。

我嘗試了很多方法,遵循SO和其他網站上的示例,我甚至實施了BroadcastReceiver,但是我無法使其工作,並且我無法理解我的錯誤,因爲我沒有得到任何「 java「錯誤。

回答

0

請嘗試以下刷新。它爲各自的加載器ID重新設置並重啓加載器。雖然我已經將它用於光標,但它也適用於自定義對象。

loaderManager.restartLoader(loaderId, null, context); 
0

嘗試增加這個下面的代碼行做一個更新到SQLite數據庫之後:

getContentResolver().notifyChange(uri, null);