Usando a biblioteca de vôlei, dentro do método onResponse, o ArrayList possui alguns dados, mas fora do método OnResponse, o arraylist está vazio
Estou executando a operação de rede em um modelo e, em seguida, retorno o resultado, mas o tamanho do arraylist é zero quando eu o retorno, mas dentro doonResponse
método, o tamanho do arraylist não é zero. Como resolver isso?
public class doInBackground {
//i have initialized the arraylist here
ArrayList<Contact> arrayList=new ArrayList<>();
String url="http://192.168.10.3/volley/allUser.php";
private Context context;
public doInBackground(Context context){
this.context=context;
}
public ArrayList<Contact> getArrayList(){
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for(int i=0;i<response.length();i++){
try {
JSONObject jsonObject=response.getJSONObject(i);
Contact contact=new Contact();
contact.setName(jsonObject.getString("name"));
contact.setUserName(jsonObject.getString("username"));
arrayList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
}
}
//outside the for loop the arraylist have data( i.e fetch from Mysql database)
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.toString(),Toast.LENGTH_LONG).show();
}
});
Toast.makeText(context,arrayList.size()+"",Toast.LENGTH_LONG).show();
//using singleton design pattern to add the request to the queue MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
// here the arraylist is empty
return arrayList;
}
}