Reputation: 375
I need a little help :)
I'm using volley on my Android app and I wrote this codes.
public String validateCredentials(final String email, final String password) {
StringRequest strReq = new StringRequest(com.android.volley.Request.Method.POST,
LOGIN_URL, new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject serverResponse = new JSONObject(response);
Log.d("Result: ", serverResponse.getString("result"));
responseServ = serverResponse.getString("result");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(email, password);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq);
return responseServ;
}
When I click the button Log.d("Result: ", serverResponse.getString("result"));
this code is work but return responseServ;
is not send any data on first click.
My button onClick code is
Toast.makeText(activity, authModel.validateCredentials(email, password), Toast.LENGTH_SHORT).show();
How do I solve this problem?
Thanks in advance
Upvotes: 1
Views: 484
Reputation: 1428
Volley is asynchronous aka you make the call, then later the callback is executed (Log.d() part). But you are also synchronously returning value which is empty the first time, and only the second time return values. Have in mind that the second time it returns the first result.
What you have to do is do all your work in onResponse()
PS: As you want to keep MVP pattern you can- Define callback Interface
and pass it to validateCredentials(final String email, final String password, final OnLoginComplete callback)
and then in onResponse()
callback.loginComplete()
Upvotes: 2