Estou tentando fazer uma requisição por JSON, juntamente com AsyncTask. Com isso, fiz a chamada do JSON no método doInBackground, porém, o código executa o método onResponse do JsonArrayRequest após a chamada do onPostExecute, e não no momento da sua devida chamada.
public class MainActivity extends AppCompatActivity {
private TextView tvCarregandoLogin;
private GifTextView gifLogin;
private String resposta = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_login);
tvCarregandoLogin = (TextView)findViewById(R.id.tvCarregandoLogin);
gifLogin = (GifTextView)findViewById(R.id.gifLogin);
tvCarregandoLogin.setVisibility(View.INVISIBLE);
gifLogin.setVisibility(View.INVISIBLE);
new GetTask().execute();
}
class GetTask extends AsyncTask<Object, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
gifLogin.setVisibility(View.VISIBLE);
tvCarregandoLogin.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Object... params) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, Auxiliar.json_url_getEspecialidades, (String)null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
String descricao = "";
for(int i=0; i<response.length(); i++)
{
try {
JSONObject jsonObject = response.getJSONObject(i);
descricao = jsonObject.getString("Especialidade");
resposta += descricao + "~";
} catch (JSONException e) {
e.printStackTrace();
}
}
onEspecialidadeIsReady(resposta);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
MySingleton.getInstance(MainActivity.this).addToRequest(jsonArrayRequest);
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
gifLogin.setVisibility(View.INVISIBLE);
tvCarregandoLogin.setVisibility(View.INVISIBLE);
//fazer alguma coisa com a variavel resposta
}
}
public void onEspecialidadeIsReady(String r)
{
resposta = r;
}
}
Classe MySingleton
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
private MySingleton(Context context)
{
mCtx = context;
requestQueue = getRequest();
}
public RequestQueue getRequest()
{
if(requestQueue == null)
{
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
public static synchronized MySingleton getInstance(Context context)
{
if(mInstance == null)
{
mInstance = new MySingleton(context);
}
return mInstance;
}
public<T> void addToRequest(Request<T> request)
{
requestQueue.add(request);
}
}