0

I am getting the exception android.os.NetworkOnMainThreadException when I tried to use the following codes:

public class CheckServer  extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Runnable runn = null;
        HttpTask.execute(runn);



    }
    private class HttpTask extends AsyncTask<String, String, String>
    {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            HttpURLConnection urlConnection = null;

            URL theURL = null;
            try {
                theURL = new URL("http://192.168.2.8/parkme/Client/clientquery.php?ticket=66t");
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                urlConnection = (HttpURLConnection) theURL.openConnection();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String response = null;
            try {
                response = readInputStream(urlConnection.getInputStream());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return response;

        }

        private String readInputStream(InputStream is) {
            // TODO Auto-generated method stub
            String line = "";
            StringBuilder total = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            try {
                while ((line = rd.readLine()) != null) {
                    total.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return total.toString();

        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        }
}}

If possible can someone tell me how to use it inside an Async Task and get the output? I tried but can't seem to get anywhere.

3 Answers3

2

Ok, lets do it step by step ...

1) create private class extending AsyncTask

private class HttpUrlConnectionTask extends AsyncTask {

2) Override the doInBackground() method, this will do the heavy load

@Override
protected Object doInBackground(Object... params) {
// your HttpUrlConnection code goes here

return response;

3) Once the job is done and returns, the onPostExecute() method will be called. The result parameter contains the return value of doInBackground() - so response.

@Override
protected void onPostExecute(Object result) {

Within this method you can update your UI.

4) Finally lets have a look onto the HttpUrlConnection code

HttpURLConnection urlConnection = null;

URL theURL = new URL(url);
urlConnection = (HttpURLConnection) theURL.openConnection();
String response = readInputStream(urlConnection.getInputStream());
return response;

Hope this helps. Happy coding!

David
  • 3,388
  • 2
  • 21
  • 25
  • please tell me about the three parameters of Async. and to which all mthods its passed to – vivek kartha Apr 04 '13 at 22:07
  • this is best explained here http://stackoverflow.com/questions/6053602/what-arguments-are-passed-into-asynctaskarg1-arg2-arg3 – David Apr 04 '13 at 22:10
-1

@Raghunandan comes with a really good explanation of how AsyncTask works

Here you go:

public static class InitializeTask extends MyAsyncTask<String, String, String> {

private Activity activity;
private ProgressDialog dialog;

public InitializeTask(Activity activity) {
    this.activity = activity;
}

@Override
protected void onPostExecute(String result) {
        Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}

@Override
protected String doInBackground(String... params) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://192.168.2.8/localhost/parkme/Client/clientquery.php?ticket=");
    try {
        HttpResponse response = httpclient.execute(httpget);
        if(response != null) {
            String line = "";
            InputStream inputstream = response.getEntity().getContent();
            return convertStreamToString(inputstream);
        } else {
            return "Unable to complete your request";
        }
    } catch (ClientProtocolException e) {
        return "Caught ClientProtocolException";
    } catch (IOException e) {
        return "Caught IOException";
    }
}

private String convertStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
        return "Stream Exception";
    }
    return total.toString();
}
}

A little side note, it is generally considered bad code to catch just Exception, since this will catch anything, and you are not accounting for what it is.

To use the AsyncTask in the Activity do this:

InitializeTask task = new InitializeTask(this)
task.execute()
-1

Exactly as it says, network activity isn't allowed on the thread the activity ran in. Moving your code to an Asynctask is the way to do it properly. Though if you're just trying to get your concept working still you can do this...

//lazy workaround with newer than gingerbread
//normally UI thread can't get Internet.
if(Build.VERSION.SDK_INT >= 9){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

And then the UI thread actually can. I wouldn't release anything like this however, I haven't even tried infact. It's just my lazy debugging move I use a lot.

cgv
  • 118
  • 1
  • 10
  • 1
    I agree. I have the impression this was a method of his Activity and he wanted to get his ideas functioning before conforming to how it really should be implemented. It can help with not splitting hairs. – cgv Apr 04 '13 at 21:18
  • Indeed, just move beyond needing it by the time you get to public release. – cgv Apr 04 '13 at 23:05