Toast in AsyncTask in Non Activity class

I have a non Activity class that contains an AsyncTask that calls a URL. If the connection timed out for some reason, I want to inform the user about this by posting Toast. But I just can't get the context.

How can this be achieved?

RPIcall.class

import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.IOException;

class RPicall extends AsyncTask<String, String, Void> {

    @Override
    protected Void doInBackground(String... uri) {

        int timeoutSocket       = 3000;
        int timeoutConnection   = 3000;

        try{

            Log.v("call URL: ", uri[0]);

            HttpGet httpGet = new HttpGet(uri[0]);
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            // The default value is zero, that means the timeout is not used. 

            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) 
            // in milliseconds which is the timeout for waiting for data.

            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpResponse response = httpClient.execute(httpGet);

        } catch (ClientProtocolException e) {
            //Here Connection TimeOut excepion
            //Toast.makeText(, "Your connection timedout", Toast.LENGTH_SHORT).show();
            Log.v("Server not Reachable: ", uri[0]);
            publishProgress("TimeOut");

        } catch (HttpHostConnectException e) {

            Log.e("Server not Reachable: ", uri[0]);

        }

        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        String test = "test";
        Log.v("finished: ", test);

    }
}
+4
source share
2 answers

Step # 1: add a constructor to RPicallthat accepts Contextby storing it in the data item.

Step # 2: use Contextin onPostExecute()to display Toast.

Step # 3: When creating the instance, RPicallgo to the appropriate one Context.

+4

, Context . :

class RPicall extends AsyncTask<String, String, Void> {

       private final Context mContext;
       public RPicall(Context c) {
          mContext = c;
       }

 }
+1

All Articles