Android Volley return value from response

对着背影说爱祢 提交于 2020-01-15 10:36:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!