Search code examples
androidandroid-asynctaskandroid-dialogfragment

Async task in dialogfragment


In an activity all i have to do to execute my AsyncTask is new MyAsyncTas().execute But it's not working in my DialogFragment i was wondering how to achieve this in a DialogFragment.Thanks in advance.


Solution

  • Just create a new task and execute it:

    new AsyncTask<Void, Void, Void>() {
      @Override
      protected Void doInBackground(Void... none) {
          ...
          return null;
      }
    
      @Override
      protected void onPostExecute(Void none) {
          ...
      }
    }.execute();
    

    Code above is embedded in createDialog():

    @Override
    protected Dialog onCreateDialog(int id) {
      switch (id) {
        case 1:
          Dialog dialog = new AlertDialog.Builder(MyActivity.this)
            .setTitle("Title")
            .setMessage("Message")
            .setPositiveButton("Execute", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int whichButton) {
                new AsyncTask<Void, Void, Void>() {
                    // code above ....
                }
              }
              ...