-1

I have

public static class FireMissilesDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Would you like to share your contacts?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        readContacts task = new readContacts(); // The IDE doesn't like "new readContacts()"
                        task.execute();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled the dialog
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}

But the IDE says 'com.example.MainActivity.this' cannot be referenced from a static context. But when I remove the static from FireMissilesDialogFragment declaration it says that FireMissilesDialogFragment should be static. So, isn't there any method to execute an AsyncTask within DialogFragment?

Edit: Here is my readContacts:

public class readContacts extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... voids){
    ...
}

public class readContacts extends AsyncTask<Void, Void, Void> { is an inner class of public class MainActivity extends AppCompatActivity {.

ilhan
  • 8,700
  • 35
  • 117
  • 201

1 Answers1

1

You need to make the AsyncTask a static class, then you can use

MainActivity.readContacts task = new MainActivity.readContacts();
task.execute();

However, I would suggest trying to make the AsyncTask a separate class so that you can reuse it elsewhere

And see How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245