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);