-1

I have written the code it works on Android 2.2 API but it does not work on Android 4.0

 String url = textUrl.getText().toString();
     HttpClient client = new DefaultHttpClient();
     HttpGet  request = new HttpGet(url);
     try
     {
        HttpResponse response = client.execute(request);
        textResult.setText(HttpHelper.request(response));
     }
     catch (Exception e) {
        // TODO: handle exception
         textResult.setText("Failed");
    }
Sumant Singh
  • 904
  • 1
  • 14
  • 16

3 Answers3

1

Internet communication must run in a separate thread.

Use AsyncTask to simplify this.

You can read more about threads in Android here

EDIT: If you really want to access the internet on the main thread, you can allow it in the onCreate() method with the following code:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);

However, I really wouldn't recommend this approach.

Søren Lorentzen
  • 868
  • 1
  • 11
  • 26
1

If you call the URL from the main thread in android 2.x then it will be perfectly run.

But HonyCumb and its upper version you need to send call the URL from worker thread.

You can use AsyncTask for that.

Stephan
  • 41,764
  • 65
  • 238
  • 329
0

I got the same problem. The solution is very simple: You have to use AsyncTaks. To Implement them you can simply make a new class. p.e:

public class AsynkTaskRequest extends AsyncTask<String, Void, String> {


    @Override
    protected String doInBackground(String... params) {
        String answer = null;

        for (String request : params) {
            //your code comes here
        }
    }
}

For more details just search a bit and you will find it ("i've searched for you this time")

EDIT: Don't use:

catch (Exception e) {
    // TODO: handle exception
     textResult.setText("Failed");
}

do it like

catch (Exception e) {
    //if you use logcat in eclipse    
    Log.e("Request Error", e.getMessage());
    //else
    System.out.println(e.getMessage());     
}
Community
  • 1
  • 1
Mr.S
  • 94
  • 9