Greeting all, I am having the hard time to set int value for a variable in ValueEventListener and get that value outside ValueEventListener for the method to checking is value == 1
, the method will return 1
, else return 0
I have tried many way like save the value via SharedPreferences, set value to Textview and call from textview, but still, the method always return 0
as it cannot read the value that have been set in ValueEventListener. Any help are much appreciate. Thank you
Here my code
int status = 0;
protected void onCreate(Bundle savedInstanceState) {
...
btnSync_in.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getCustomerList() == 1) {
msg = msg + "Get customer success \n";
} else {
msg = msg + "Get customer unsuccessful \n";
}
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
}
The method that will return the int
private int getCustomerList() {
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
status = 1; //here my problem, value assign here is success
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
...
status = 0; // here if unsuccessful
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
...
}
});
if (status == 1) {
return 1;
} else {
return 0;
}
}