问题
How do I get the response out of onResponse so that I can return it? I have found this but I don't really understand how to implement it for me. How can I return value from function onResponse of Volley?
I hope there is an updated method or something easier that I might have missed This is my code
public Boolean checkIfPersonExists(Context context, final Person aPerson){
StringRequest postRequest = new StringRequest(Request.Method.POST, USEREXISTS, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("RESPONSE",response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("email",aPerson.getEmail());
params.put("phone",aPerson.getPhone());
return params;
}
};
Volley.newRequestQueue(context).add(postRequest);
return null;
}
回答1:
As it was mentioned, you need to implement interface and get a callback
Create a new interface like this
public interface GeneralCallbacks {
void VolleyResponse(String data);
}
Implement the interface on your activity class
public class YourActivity implements ScoreboardCallback
{
@Override
public void VolleyResponse(String data)
{
//do stuff with data
}
}
And finally changing your response function to something like this
@Override
public void onResponse(String response) {
((GeneralCallbacks)context).VolleyResponse(response); // This will make a callback to activity.
aPerson.SomeFunction(); // This will call person's function
Log.d("RESPONSE",response.toString());
}
来源:https://stackoverflow.com/questions/40948598/android-volley-return-value-from-response