Java 创建异步HTTPGet类
我试图使用HTTPGet从服务器检索字符串,然后我想将该字符串设置为MainActivity类中的TextView。这是我试图用来完成这一任务的课程。(我没有在这里包括导入,但它们在实际的类中。我也保留了我在这里使用的URL,但实际的URL在我的类中) 然后在我的MainActivity类中使用它:Java 创建异步HTTPGet类,java,android,android-asynctask,androidhttpclient,Java,Android,Android Asynctask,Androidhttpclient,我试图使用HTTPGet从服务器检索字符串,然后我想将该字符串设置为MainActivity类中的TextView。这是我试图用来完成这一任务的课程。(我没有在这里包括导入,但它们在实际的类中。我也保留了我在这里使用的URL,但实际的URL在我的类中) 然后在我的MainActivity类中使用它: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); se
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子类化,定义将使用的参数类型。您的HTTPGet代码将进入
doInBackground()
方法。要运行它,您需要创建AsyncTask类的一个新实例,并调用execute()
我设法将该类放入AsyncTask类中。我可以在调试应用程序时看到返回了我想要的字符串。现在我需要将返回的字符串放入MainActivity类中,以便将TextView设置为返回的字符串。我该怎么做?在AsyncTask的构造函数中,传递对活动的引用并将其存储在字段中。然后可以从onPostExecute()
调用该活动的公共方法,并将字符串作为参数传递。
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();
}
}