【问题标题】:Why this doesn't work for ICS [duplicate]为什么这不适用于 ICS [重复]
【发布时间】:2012-06-23 09:20:33
【问题描述】:

可能重复:
Strange NetworkOnMainThreadException in Android app?
Trying To Upload To Dropbox: NetworkOnMainThreadException?

我使用下面的代码从 url 读取 HTML 内容。这适用于 2.3.3,但是当我尝试运行相同的代码时,它不适用于 ICS。

我正在尝试将这些 html 内容附加到 edittext。但是当我在 ICS 上运行代码时,它总是为空。可能是什么问题?

public class Quiz1Activity extends Activity {
    private static BufferedReader reader = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

EditText ed = (EditText) findViewById(R.id.editText1);

        try {
            ed.append(getStringFromUrl("http://www.google.com"));
            //getInputStreamFromUrl("").close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    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;
        }

    public static String getStringFromUrl(String url) throws IOException{
        reader = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));

        StringBuilder sb = new StringBuilder();
        try{
        String line = null;
        while((line = reader.readLine()) != null)
        {
            sb.append(line);
        }    
        }catch (IOException e){
         e.printStackTrace();
        }
       getInputStreamFromUrl(url).close();
        return sb.toString();
    }
}

【问题讨论】:

  • 在这里阅读我的答案stackoverflow.com/a/10892925/1321873
  • +1 拉杰什。在 ICS 中,如果您没有实现 AsyncTask 或 AsyncTaskLoader,则会出现 NetworkOnMainThreadException 异常。
  • 您最好尝试查看 Logcat 输出。

标签: java android html android-4.0-ice-cream-sandwich


【解决方案1】:

但当我在 ICS 上运行代码时,它总是为空。可能是什么问题?

问题是 ICS 不允许您在主线程上执行异步任务,因此请将您的异步移动到新线程中。

您应该在单独的线程中移动以下代码。

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;
        }

【讨论】:

    【解决方案2】:

    就像@Vipul Shah 所说,你必须将 getInputStreamFromUrl() 移动到另一个线程中使用异步任务,这是在 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" });
    
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 2013-07-12
      • 1970-01-01
      • 2022-08-19
      • 2012-03-20
      相关资源
      最近更新 更多