0

I want to add result data of async class to a string variable, i am passing a string variable from main class while i'm creating obj of async class and calling it's overload contructor, and in post method of async class i'm assigning the result value to that string, but when i print that string in main class, i didn't get the resultant value (post method result value), while when i perform same procedure while passing textview instead of string from main class and set result value to that textview and then on getting the value from main i have resultant value, but i want to do same functionality by passing string not textview.

Thats how i am calling asyncclass:

    getCountryId getCountryid=new getCountryId(this, roleField);  // rolefield is textview  
    getCountryid.execute(itemcountry);

That's my async class:

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);
}

}

1 Answers1

0

Use StringBuilder instead:

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

Also, your code doesn't explain how your MainActivity reads result from your AsyncTask. Remember, that MainActivity needs to read your result after onPostExecute, not earlier. You can call, for example, some MainActivity function (let's call it "presentResult") when your AsyncTas finishes the job. If you really want to use String, and not StringBuilder, presentResult() might also accept String argument. Nice solution is presented here

Community
  • 1
  • 1
aliczab
  • 116
  • 3