【问题标题】:Query DB once in Activity life-cycle using Loader使用 Loader 在 Activity 生命周期中查询一次 DB
【发布时间】:2017-04-30 19:17:17
【问题描述】:

我正在完成一个使用 Singleton 作为模式并将 SQLite 作为数据库的项目。

我的想法是,我不想每次在活动生命周期中触发 onCreate 方法时都进行选择查询,相反,我想要的是当配置更改或重新创建活动 y 时,适配器使用之前加载的相同数据。

我怎么不使用 Content Provider 我不能使用 Loader 或 CursorLoader 所以我不知道该怎么做。

我的 MainActivity 代码如下:

RecyclerView recyclerView;
public Cursor cursor;
InsectRecyclerAdapter insectAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(this);

    cursor = DatabaseManager.getInstance(this).queryAllInsects("friendlyName");  //EVERY TIME THIS METHOD IS TRIGGER EXECUTE THE QUERY..AND I DON'T WANT THAT.
    insectAdapter = new InsectRecyclerAdapter(this, cursor);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setAdapter(insectAdapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
}

我总是将 SQLite 与提供程序一起使用,所以这种方法对我来说是新的。

有什么建议吗?

【问题讨论】:

  • 你不需要使用 ContentProvider 来使用 Loader。
  • 嗯...@GabeSechan 我正在尝试使用 AsyntTaskLoader,因为我无法使用 ContentLoader 做我想做的事情。但仍然有效。
  • 您仍然可以实现Loader,即使不使用ContentProvider。加载程序将在配置更改期间保留其数据。不过,从长远来看,仅仅使用内容提供者通常会更容易
  • 成功了!还是谢谢你!

标签: android sqlite android-recyclerview cursor android-lifecycle


【解决方案1】:

我使用 AsyncTaskLoader 完成了它。代码如下:

 public abstract class SimpleCursorLoader extends AsyncTaskLoader<Cursor> {
    private Cursor mCursor;
    public SimpleCursorLoader(Context context) {
        super(context);
    }

    @Override
    protected void onStartLoading() {
        //If the cursor is null call loadInBackground else deliverResult
        if (mCursor != null) {
            deliverResult(mCursor);
        }
        if (takeContentChanged() || mCursor == null) {
            forceLoad();
        }
    }

    @Override
    public  Cursor loadInBackground(){
        mCursor  = DatabaseManager.getInstance(MainActivity.this).queryAllInsects(MainActivity.FILTER);
        return mCursor;
    }

    /* Runs on the UI thread */
    @Override
    public void deliverResult(Cursor cursor) {
        if (isReset()) {
            // An async query came in while the loader is stopped
            if (cursor != null) {
                insectAdapter.swapCursor(cursor);
            }

            return;
        }
        mCursor = cursor;
        if (isStarted()) {
            super.deliverResult(cursor);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2013-04-06
    • 1970-01-01
    • 2018-07-18
    • 2012-09-21
    • 2019-01-05
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多