1

我想将网页中的文本放到 Android 3.0 上的文本视图中。我有这个代码:

public class Biografie extends Activity {
    private TextView outtext;
    private String HTML;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_biografie);

        outtext= (TextView) findViewById(R.id.textview1); 

        try { 
        getHTML();
    } catch (Exception e) {
        e.printStackTrace();
    }       
    outtext.setText("" + HTML);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.biografie, menu);
        return true;
    }

    private void getHTML() throws ClientProtocolException, IOException 

    {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://artistone.appone.nl/api/biografie.php?dataid=998"); //URL!
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = null;
        while ((line = reader.readLine()) != null) {
            result += line + "\n";
            HTML = result;
        }

    }

}

我的 TextView 返回“null”而不是页面中的文本。请帮我解决这个问题。对此表示感谢。

4

2 回答 2

0

将您的代码更改为:

while ((line = reader.readLine()) != null) {
    result += line + "\n";
}
HTML = result;

试试这个: outtext.setText(Html.fromHtml(HTML));

而不是在主线程中执行网络操作,我建议您在单独的线程中使用AsyncTask

于 2013-02-26T16:59:33.223 回答
0

问题是你得到NetworkOnMainThreadException 那是因为你在主线程(活动线程)上下载网络内容。

相反,您需要使用后台线程来下载该内容,或使用AsynchTask

应该解决此问题的简单代码:

    final Handler handler = new Handler();
    Thread thread = new Thread() {
        public void run() {
            try {
                getHTML();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        outtext.setText("" + HTML);

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                    handler.post(new Runnable() {
                    @Override
                    public void run() {
                        outtext.setText(e.toString());

                    }
            }
        }
    };
thread.start(); // I forgot to start the thread. sorry !

代替 :

    try { 
           getHTML();
    } catch (Exception e) {
        e.printStackTrace();
     }       
    outtext.setText("" + HTML);

还可以看看这个关于 android 线程的教程:教程

于 2013-02-26T17:13:41.390 回答