0

I have tried making a class supporting AsyncTask and I failed miserably. Later I made a superclass of this class and added to my Main Class this:

//subclass of the superclass CustomHttpClient
CustomHttpClient2 cl= new CustomHttpClient2();
cl.execute();
response = cl.executeHttpPost("http://ironis.dyndns.org/aeglea/android/log.php", postParameters);

The error message is android.os.NetworkOnMainThreadException

The class I want to convert is this(I used it in sdk 7, but I moved to 14 and now it fails)

public class CustomHttpClient2 (extends CustomHttpClient)<<I used it without this {

 public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
    private static HttpClient mHttpClient;


    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public JSONObject executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        HttpEntity he=null;
        JSONObject jo=null;

        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            //mine
            he=response.getEntity();
            jo=new JSONObject(EntityUtils.toString(he));
            //end mine

            return jo;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

The other class I use CustomHttpClient is below

public class CustomHttpClient extends AsyncTask<HttpClient,String,String> {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;



protected HttpClient doInBackground(String... params) {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params1 = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params1, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params1, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params1, HTTP_TIMEOUT);
    }
    return mHttpClient;
}



@Override
protected String doInBackground(HttpClient... params) {
    // TODO Auto-generated method stub
    return null;
}




}

Any love for me?

3 Answers 3

2

Probably Your async task would look like:

public class CustomHttpTask extends AsyncTask<CustomHttpClient2,String,String> {
   public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds


   @Override
   protected String doInBackground(HttpClient... params) {
       //subclass of the superclass CustomHttpClient
       CustomHttpClient2 cl= params[0];
       response = cl.executeHttpPost("http://ironis.dyndns.org/aeglea/android/log.php", postParameters);

        // say, you need response string back

        return response.toString();
}

    @Override
    protected void onPostExecute(String result) {
        showDialog("Downloaded " + result + " response");
    }
}

And call it the following way:

CustomHttpTask task = new CustomHttpTask();
task.execute(new CustomHttpClient2());

And, Android is doing the right way throwing NetworkOnMainThreadException then You try to execute network requests on UI Thread to help You avoid ANR with slow connections.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for nice answer, but should remove this line: cl.execute();
@sandrstar I took what you said and modified it a little. You are the man, man. :P
0

I would think it might have something to do with not overriding the correct doInBackground method. Instead, you're overloading with different param types. Switch the HttpClient and String in your class definition (e.g. ...extends AsyncTask<String,String,HTTPClient>) to be able to pass the correct params and return the proper result.

[EDIT] I'm not sure if I understood the essence of your question, but my point was the only stuff that will be executed in a separate thread (which you must put your IO in) is the stuff in the correct doInBackground method.

Comments

0

Whoever has a similar problem I will post my solution.

I modded the @sandrstar 's solution and I did that

public class CustomHttpTask extends AsyncTask<Object,String,JSONObject> {
   public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
   private JSONObject response = null;

   @Override
   protected JSONObject doInBackground(Object... params) {
       //subclass of the superclass CustomHttpClient
       //CustomHttpClient cl= (CustomHttpClient) params[0];
       String url = (String) params[0];
       ArrayList<NameValuePair> postParameters = (ArrayList<NameValuePair>) params[1];
    try {
        response = CustomHttpClient.executeHttpPost(url, postParameters);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        // say, you need response string back

        return response;
}

    @Override
    protected void onPostExecute(JSONObject result) {

    }
    public JSONObject getval(){
        return response;
    }

}

Now I can do multiple posts in different url's. The problem is that I want a json object. There are 2 ways. Either create a function as I did. or use AsyncTask's get() function

CustomHttpTask asdf = new CustomHttpTask();
response = asdf.execute("http://192.168.1.4/aeglea/android/log.php", postParameters).get();

That executes first and when it finishes it executes the get part. ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.