javaandroidandroid-studioandroid-fragmentsmain-activity

MainActivity is not an enclosing class in Fragment Class


I have two Android Studio projects opened. One is the actual app, other is a testing project. In the testing project I have used this code in MainActivity.java and it worked perfectly. Now when I try to transfer it to my actual app project, it doesn't work. Probably because the code is inside a fragment class and not MainActivity.

This is the code I'm talking about:

private class SendMailTask extends AsyncTask<Message, Void, Void> {
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Sending mail", true, false);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
    }

    @Override
    protected Void doInBackground(Message... messages) {
        try {
            Transport.send(messages[0]);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

What it does is simply display the message "Sending email" while it does so on the screen. I'm not sure if I should copy the whole class if needed, so tell me if it is so.

The error is shown at this line:

progressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Sending mail", true, false);

It says: 'com.example.private.privateprivate.MainActivity' is not an enclosing class'.

I'm unsure what to do since if I put MainFragment.this, it gives an error and says: 'Wrong 1st argument type. Found: 'com.example.private.privateprivate.MainFragment', required: 'android.content.Context'


Solution

  • Use getActivity() as the first argument.

    You need a Context object in order to call show(). When your AsyncTask was living inside of an activity, the way to get one was to reference the encosing activity directly using MainActivity.this. Now that your task is living inside of a Fragment, you can't do that. But fragments have a getActivity() method that will return their activity, so you can use that instead.