Rishabh Jindal Rishabh Jindal - 9 months ago 30
Android Question

how to return from doInBackground only after the the thread inside it is finished

I started a Volley JsonObject Request from asynctak and i want to return from doinBackground after the volley request is completed. I know it return from the doInBackground after it successfully started the thread. But how do i return after the Volley Thread is finished!

In this code I am getting a null value of Weather object. All the functions are working correctly.

Code:

@Override
protected JSONObject doInBackground(Void... voids) {
String url=getURL();
final JSONObject[] mJsonWeather = {null};
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mJsonWeather[0]=response;

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Error","can't process json result");
}
});
MySingleton.getInstance(mContext.getApplicationContext()).addToRequestQue(jsonObjectRequest);

return mJsonWeather[0];

}



@Override
protected void onPostExecute(JSONObject jsonObjectWeather) {
super.onPostExecute(jsonObjectWeather);

Weather weather = getJsonWeatherData(jsonObjectWeather);
setWeatherobj(weather);

}

Answer Source

I think you've misunderstood something about the async part of AsyncTask. It means it runs asynchronously

Sure your code will run, but while Volley is running in a separate thread, you've gone ahead to return mJsonWeather[0];, which is null.

No AsyncTask needed. Call this section of code directly in the Activity

EDIT "Clean code"

// Can define this wherever
Response.Listener<JSONObject> dataListener = new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Weather weather = getJsonWeatherData(response);
        setWeatherobj(weather);
  }
};

// This error listener is almost always the same, anyway, right?
Response.ErrorListener errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.i("Error","can't process json result");
    }
}

JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, 
    null, // Data
    dataListener, // onSuccess
    errorListener // onError
);

MySingleton.getInstance(getApplicationContext())
    .addToRequestQue(jsonObjectRequest); // Some RequestQueue