Search code examples
javaandroidandroid-asynctaskclipboardimgur

onPostExecute not allowing me to create Toast message


Please see this before for context: Anonymous Uploading File object to Imgur API (JSON) gives Authentication Error 401 (it has the code for doInBackground() method in case anyone is interested)

Using an AsyncTask class, I am uploading an image to Imgur. The uploading process is done within doInBackground() method. It returns String link to onPostExecute which should display the link in the form of a Toast message.

@Override
protected void onPostExecute(String result) 
{
    super.onPostExecute(result);
    Toast.makeText(getApplicationContext(), "Uploaded! Link: " + result, Toast.LENGTH_SHORT).show();
}

However, doing this gives the following error:

The method getApplicationContext() is undefined for the type UploadToImgurTask

Trying to copy the return string to the clipboard gives a similar issue.

@Override
protected void onPostExecute(String result) 
{
    super.onPostExecute(result);
    ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); 
    ClipData clip = ClipData.newPlainText("label", "Text to copy");
    clipboard.setPrimaryClip(clip);
}

The method getSystemService(String) is undefined for the type UploadToImgurTask


Solution

  • @Raghunandan is right. So, inside your UploadToImgurTask class you can have:

    private Context context;
    //in constructor:
    public UploadToImgurTask(Context context){
            this.context=context;
    }
    

    Then in onPostExecute you can simply use:

    Toast.makeText(context, "Uploaded! Link: " + result, Toast.LENGTH_SHORT).show();
    

    Hope this helps you.