我想将异步类的结果数据添加到字符串变量中,我正在从主类传递一个字符串变量,而我正在创建异步类的obj并调用它的重载构造函数,并且在async类的post方法中我m将结果值分配给该字符串,但是当我在主类中打印该字符串时,我没有得到结果值(post方法结果值),而当我执行相同的过程同时从主类传递textview而不是字符串时将结果值设置为该textview,然后从main获取值i得到结果值,但我想通过传递字符串而不是textview来执行相同的功能。
这就是我如何调用asyncclass:
getCountryId getCountryid=new getCountryId(this, roleField); // rolefield is textview
getCountryid.execute(itemcountry);
这是我的异步类:
public class getCountryId extends AsyncTask<String,Void,String> {
private Context context;
private TextView role;
public getCountryId(Context context, TextView role){
this.context=context;
this.role=role;
}
protected void onPreExecute(){
}
@Override
protected String doInBackground(String... arg0) {
try{
String z = (String)arg0[0];
String link="http://ipadress/regform/getstateid.php";
String data = URLEncoder.encode("z", "UTF-8") + "=" + URLEncoder.encode(z, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result){
role.setText(result);
}
}
答案 0 :(得分:0)
请改用StringBuilder:
StringBuilder myStrBuild = new StringBuilder ();
...
getCountryId getCountryid=new getCountryId(this, myStrBuild);
此外,您的代码没有解释您的MainActivity如何从AsyncTask读取结果。请记住,MainActivity需要在onPostExecute之后读取您的结果,而不是更早。例如,当AsyncTas完成作业时,您可以调用一些MainActivity函数(让我们称之为“presentResult”)。 如果你真的想使用String而不是StringBuilder,那么presentResult()也可能接受String参数。 提出了一个很好的解决方案here