Junaid
Junaid

Reputation: 7860

Trying to use a Loader with AsyncTask. (Android)

I am trying to use a Loader with an AsyncTask, however the call to execute the Loader in the DoinBackground method gives me an error: The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, LoaderClass.MagicCall)

Here is my code:

private class MagicCall extends AsyncTask<Void, Void, String> {

        ProgressDialog Asycdialog = new ProgressDialog(LoaderClass.this);
        @Override
        protected void onPreExecute() {

            Asycdialog.setMessage("Working");
            Asycdialog.show();
            super.onPreExecute();
        }

        protected String doInBackground(Void... args) {
            getLoaderManager().initLoader(0, null, this);

            String Z = Integer.toString(insertNameBD());
            return Z;
        }

        @Override
        protected void onPostExecute(String result) {
            //hide the dialog
            Asycdialog.dismiss();
            t3.setText(result); 
            super.onPostExecute(result);
        }
    }

Upvotes: 2

Views: 828

Answers (2)

Lettings Mall
Lettings Mall

Reputation: 300

You should not use a Loader in an AsyncTask! The answer above is correct as there is an AsynTaskLoader which extends loader and provides additional methods which override the default Loader properties.

You can extend AsynTaskLoader to provide your own implementation and control sevral other loader specific features.

Upvotes: 0

Karthi
Karthi

Reputation: 748

you should do like this

class FooLoader extends AsyncTaskLoader {
 public FooLoader(Context context, Bundle args) {
  super(context);
  // do some initializations here
}
public String loadInBackground() {
  String result = "";
  // ...
  // do long running tasks here
  // ...
  return result;
}
}

class FooLoaderClient implements LoaderManager.LoaderCallbacks {
  Activity context;
  // to be used for support library:
  // FragmentActivity context2;
  public Loader onCreateLoader(int id, Bundle args) {
     // init loader depending on id
    return new FooLoader(context, args);
 }
   public void onLoadFinished(Loader loader, String data) {
     // ...
     // update UI here
     //
  }
  public void onLoaderReset(Loader loader) {
     // ...
  }
  public void useLoader() {
     Bundle args = new Bundle();
    // ...
    // fill in args
  // ...
  Loader loader = 
     context.getLoaderManager().initLoader(0, args, this);
  // with support library: 
  // Loader loader = 
  //    context2.getSupportLoaderManager().initLoader(0, args, this);
  // call forceLoad() to start processing
  loader.forceLoad();
  }
 } 

Upvotes: 1

Related Questions