Why this doesn't work for ICS [duplicate]

二次信任 提交于 2019-12-02 08:01:15

Like @Vipul Shah said you have to move getInputStreamFromUrl() into another thread use Async Task, this is work on ICS:

package com.home.anas;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.EditText;

public class WebPageContentActivity extends Activity {
    private EditText ed;


/** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ed = (EditText) findViewById(R.id.editText1);
        readWebpage();
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = "";
            for (String url : urls) {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                try {
                    HttpResponse execute = client.execute(httpGet);
                    InputStream content = execute.getEntity().getContent();

                    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                    String s = "";
                    while ((s = buffer.readLine()) != null) {
                        response += s;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            ed.setText(result);
        }
    }

    public void readWebpage() {
        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }
} 

But it always remains empty when I run the code on ICS. What may be the problem?

Issue is ICS don't allow you do asynchronous task on main thread so move your asynchronous into new thread.

You should move following code in seperate thread.

public static InputStream getInputStreamFromUrl(String url){
           InputStream contentStream = null;

           try{
             HttpClient httpclient = new DefaultHttpClient();
             HttpResponse response = httpclient.execute(new HttpGet(url));
             contentStream = response.getEntity().getContent();
           } catch(Exception e){
              e.printStackTrace();
           }
           System.out.println("Content stream is " + contentStream);
           return contentStream;
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!