Kourosh
Kourosh

Reputation: 618

how to execute an AsyncTask subclass in Java?

I'm trying to learn how to call an AsyncTask which is nested inside another class.

Class A (a class that the AsyncTask is a subclass). Class B (is the mainActivity).

In Class A:

I created an Interface that contains the method for when the AsyncTask is finished (for the sake of CallBack).

In Class B:

How would I go about calling my AsyncTask. seems like the normal way of making an instance and then .execute() doesn't work! i get the following error:

No enclosing instance of type NetConnectivity is accessible. Must qualify the allocation with an enclosing instance of type

NetConnectivity (e.g. x.new A() where x is an instance of NetConnectivity).

NetConnectivity is Class A in this context.

Thank you for your time.

Edit----

This is the NetConnectivity Class :

public class NetConnectivity {


    public boolean CheckNetworkAvailability(Context context){

        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        String tag = "NetworkCheck";
        if(networkInfo != null && networkInfo.isConnected()){
            Log.i(tag, "Network is available");
            return true;
        } else {
            Log.i(tag, "Network is not available");
            return false;
        }
    }

    public interface WebServiceAsyncListener {
        void WebServiceDone();
    }

    public static class WebServiceAsync extends AsyncTask <String, Integer, Double>{

        private WebServiceAsyncListener wListener;

        public WebServiceAsync(Activity act){
            wListener = (WebServiceAsyncListener) act;
        }

        @Override
        protected Double doInBackground(String... params) {
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(String result) {
          wListener.WebServiceDone();
        }

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://somewebsite.com/receiver.php");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);

            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }
        }
    }

}

Upvotes: 1

Views: 1032

Answers (1)

Ayman Mahgoub
Ayman Mahgoub

Reputation: 4220

Make the AsyncTask a "static" class.

Upvotes: 3

Related Questions