AsyncTaskLoader basic example. (Android)

前端 未结 6 1668
[愿得一人]
[愿得一人] 2020-12-01 02:56

I am using a Loader in my application and based on the result I get from the query I perform on COntacts using this Loader I perform some calculations and store them back in

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 03:31

    Simplifying hard, maybe

      private void loadContent() {
        getLoaderManager().initLoader(1000, new Bundle(), 
          new LoaderManager.LoaderCallbacks>() {
    
          @Override
          public Loader> onCreateLoader(int id, Bundle args) {
            return new AsyncTaskLoader>(MainActivity.this.getApplicationContext()) {
    
              @Override
              public List loadInBackground() {
                Log.i("B", "Load background data ");
                ArrayList data = new ArrayList<>();
                for (int i = 0; i < 5000; i++) {
                  data.add("Data." + i + " " + System.currentTimeMillis());
                }
                try {
                  Thread.sleep(5000);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                return data;
              }
            };
          }
    
          @Override
          public void onLoadFinished(Loader> loader, List data) {
            Log.i("B", "Here are your data loaded" + data);
            if (!loader.isAbandoned()) {
              mAdapter.setData(data); // Read also about RecyclerView
            }
          }
    
          @Override
          public void onLoaderReset(Loader> loader) {
            Log.i("B", "Loader reset");
          }
        }).forceLoad();
      }
    
      @Override
      protected void onDestroy() {
        // Abandon the loader so that it should not attempt to modify already dead GUI component
        getLoaderManager().getLoader(1000).abandon();
        super.onDestroy();
      }
    

    Make this part of your Activity. The sample simulates delay, but makes new entries easy to recognize because they will have the different time stamp suffix. Of course you also need RecyclerView to display the data, the answer to this question seems very good.

    The loader in this example is the inner class that keeps the reference to the parent activity. It must be external static class without such reference in production.

提交回复
热议问题