2016-10-01 49 views
0

我想异步类的结果数据添加到字符串变量,我传递一个字符串变量从主类,而我创建异步类的OBJ并调用它的过载构造器,并在POST方法的异步类我分配结果值的字符串,但是当我在主类中打印该字符串,我没有得到结果值(后方法结果值),而当我执行同样的过程,而传递文本而不是字符串从主类和设置结果值到该textview,然后从主得到的价值我有结果值,但我想通过传递字符串不textview相同的功能。的Android异步类岗位功能

这就是我对你的呼唤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

使用StringBuilder代替:

StringBuilder myStrBuild = new StringBuilder(); 
... 
getCountryId getCountryid=new getCountryId(this, myStrBuild); 

而且,你的代码没有解释您的MainActivity如何从您的AsyncTask中读取结果。请记住,MainActivity需要在onPostExecute之后读取结果,而不是更早。例如,当AsyncTas完成作业时,您可以调用一些MainActivity函数(我们称之为“presentResult”)。 如果你真的想使用String而不是StringBuilder,presentResult()也可能接受String参数。 不错的解决方案here

+0

我在我的post方法和我的主类中设置了异步的结果值到Textview(角色),我通过调用该TextView的getText()函数来获取文本。 –

+0

感谢您的帮助。 –