Search code examples
javaandroidhttphttpcontext

How get information from Web page (Android)?


I make Android application which must receive data from the page http://example.com/get.php?id=1. For this I use the following method:

private String getData()
    {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext(); // !!! application stops here
        HttpGet httpGet = new HttpGet("http://example.com/get.php?id=1");
        HttpResponse response = null;
            try {
                response = httpClient.execute(httpGet, localContext);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        String result = "";

        BufferedReader reader = null;
            try {
                reader = new BufferedReader(
                    new InputStreamReader(
                      response.getEntity().getContent()
                    )
                  );
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        String line = null;
        try {
                while ((line = reader.readLine()) != null){
                  result += line + "\n";
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        // Now you have the whole HTML loaded on the result variable
        return result;
    }

I also added a permission to AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.repetitor_ent_free"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />

The problem is that when I run the application on the device I get the error: An unexpected stop the application MyApp (process com.android.myapp). Please try again.


Solution

  • You got android.os.NetworkOnMainThreadException, if you would like the better solution try to use AsyncTask. For more about threads look at 'processes and threads' (please, read this guide carefully to avoid this issue in future).

    For example you could try one of these solutions:

    1) Use the Roman's answer and add something like this:

    final StringBuilder sb = ... ;
    final TextView tv = ... ;
    
    tv.post(new Runnable() {
            public void run() {
                tv.setText(sb.toString());
            }
        });
    

    or use activity method:

    runOnUiThread(new Runnable() {
        public void run() {
            final StringBuilder sb = ... ;
            final TextView tv = ... ;
    
            tv.setText(sb.toString());
        }
    });
    

    2) Use AsyncTask:

    new AsyncTask<Void, Void, Void> () {
        protected Void doInBackground(Void... none) {
            //
            // your code
            //
    
            return null;
        }
        protected void onProgressUpdate(Void... none) {}
        protected void onPostExecute(Void none) {
            // use this to set the text
    
            final StringBuilder sb = ... ;
            final TextView tv = ... ;
    
            tv.setText(sb.toString());              
        }
    }.execute();