2013-02-26 54 views
1

我想將文本從網頁放置到Android 3.0的文本視圖中。我有這樣的代碼:將網頁文本放入文本視圖(Android)

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」而不是頁面中的文本。請幫我解決這個問題。謝謝。

+0

你得到一個異常來自getHTML?以及您正在測試的目標設備是什麼? – 2013-02-26 17:02:59

+0

我在Android 4.0.2平板電腦上測試 – 2013-02-26 17:04:17

回答

0

你的代碼更改爲:

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

,並嘗試這個辦法: outtext.setText(Html.fromHtml(HTML));

而不是在主線程中執行網絡的行動,我會建議你使用要做到這一點在單獨的線程AsyncTask

+0

當我這樣做時,應用程序崩潰。 – 2013-02-26 17:01:06

+1

我編輯過,看一看。 – Waqas 2013-02-26 17:02:27

+0

在哪裏可以做出改變? – 2013-02-26 17:04:46

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的線程:Tutorial

+0

的TextView仍然爲空... – 2013-02-26 17:17:57

+0

是啊,我這樣做, – 2013-02-26 17:22:38

+0

沒有再次.. – 2013-02-26 17:58:24