Java – Cannot assign a value to a variable from doInBackground to the main class

Cannot assign a value to a variable from doInBackground to the main class… here is a solution to the problem.

Cannot assign a value to a variable from doInBackground to the main class

I

have an android class where I initialize my variables:

public class myClass extends Activity {
String itemIdString;
...
}

Then I call AssyncTask in my onCreate method

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next_item_caller);

Log.d("Before " +itemName);
            new getItemNumber().execute();
            Log.d("After" +itemName);
            ...
     return "success";
    }

In AssyncTask, I parse JSON objects and assign values to variables:

 class getItemNumber extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d("getItemNumber", "On pre-execute");
    }

protected String doInBackground(String... args) {
parse here
itemIdString = c.getString(TAG_ITEM_ID);
Log.d(TAG, itemIdString);
}
 protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d("getItemNumber", "on Post-Execute");
    }

My login in AssyncTask prints values as expected, but the before and after values are empty in onCreate? How should I assign these strings so that I can access them from other methods as well? Thanks

Solution

AsyncTask's doInBackground runs on another thread.

onCreate runs on the UI thread.

Therefore, when you call AsyncTask.execute(), you don’t need to wait for it to finish and proceed to the next line

Log.d("After" +itemName);

To detect when doInBackground completes, you have a handy callback method onPostExecute:

private class MyTask extends AsyncTask<Void, Void, Void> {

@Override
    protected Void doInBackground(Void... params) {
        return null;
    }

@Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
         doInBackground finished, use your variable now
    }

}

Related Problems and Solutions