Question

I tested this code and it works fine on 2.2 and 2.3.3, but it crashes on 4.0.

The problem seems to be with the http request. Any ideas why?

public class Rezultat extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    //http post
    InputStream is=null;
    try{

            String url="http://google.com";
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }
    //convert response to string
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();

            result=sb.toString();

    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
Was it helpful?

Solution

e.printstacktrace() will tell you:

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

private class DownloadFromUrlTask extends AsyncTask<String, Void, Bitmap> {

    protected void onPreExecute() {
        mDialog = ProgressDialog.show(ChartActivity.this,"Please wait...", "Retrieving data ...", true);
    }

    protected String doInBackground(String... urls) {
        //All your network stuff here.
        return result
    }
}

OTHER TIPS

You're performing a (potentially slow) network operation on the main thread. If your target SDK is 11 or higher this will throw a NetworkOnMainThreadException , because this behaviour can block the UI and lead to an unresponsive app.

You could use an AsyncTask to get around this, loading the data in its doInBackground(..).

You should normally post your stack trace when asking about a crash but in this case you're doing network operations on the main UI thread. This is not recommended and now throws an exception. Instead do it in another thread, perhaps via an AsyncTask.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top