2014-11-05 63 views
0

我想從服務器使用HTTPGet檢索字符串,然後我想將該字符串設置爲我的MainActivity類中的TextView。這是我正在試圖用來完成這個的課程。 (我不包括進口這裏,但他們在實際的類。我也攔阻我使用這裏的URL,但實際的URL是在我的課)製作異步HTTPGet類

public class GetFromServer { 

public String getInternetData() throws Exception { 
    BufferedReader in = null; 
    String data = null; 
    try{ 
     HttpClient client = new DefaultHttpClient(); 
     URI website = new URI("URL withheld"); 
     HttpGet request = new HttpGet(); 
     request.setURI(website); 
     HttpResponse response = client.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     StringBuffer sb = new StringBuffer(""); 
     String l = ""; 
     String nl = System.getProperty("line.separator"); 
     while ((l = in.readLine()) !=null){ 
      sb.append(l + nl); 
     } 
     in.close(); 
     data = sb.toString(); 
     return data; 
    }finally { 
     if (in != null){ 
      try{ 
       in.close(); 
       return data; 
      }catch (Exception e){ 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
} 

然後在使用它我

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    textView = (TextView) findViewById(R.id.textView); 

    GetFromServer test = new GetFromServer(); 
    String returned = null; 
    try { 
     returned = test.getInternetData(); 
     textView.setText(returned); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

這不工作,因爲我得到了android.os.NetworkOnMainThreadException,這意味着我必須使用的AsyncTask:MainActivity類別。我問的是如何將這個類變成一個AsyncTask,以便它能工作?一旦它是一個AsyncTask,我如何在我的MainActivity類中使用它?

回答

1

AsyncTask在developer documentation上有一個非常全面的解釋。

基本上,您子類AsyncTask,定義您將使用的參數的類型。您的HTTPGet代碼將進入doInBackground()方法。要運行它,您需要創建一個AsyncTask類的新實例並調用​​。

+0

我設法在AsyncTask類中創建類。我可以在調試應用程序時看到我想要返回的字符串。現在我需要將返回的字符串放入MainActivity類中,以便將TextView設置爲返回的字符串。我將如何做到這一點? – 2014-11-05 20:23:11

+0

在AsyncTask的構造函數中,傳遞對您的活動的引用並將其存儲在字段中。然後你可以從'onPostExecute()'中調用該Activity的公共方法,將該字符串作爲參數傳遞。 – 2014-11-05 20:28:32