2014-11-05 64 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