I've setup a MySql server with a RESTful api to handle my login/signup system for my android app.
I'm creating an ASyncTask to handle the signup POST request, the server should return a JSON object telling us whether it was successful or not. When I input valid details and register on my Android app, the first response in onPostExecute is null. I press the button again and it is correct. What could I be doing wrong?
private class PostAndReadResponseTask extends AsyncTask<Account, Void, String> {
#Override
protected String doInBackground(Account... accounts) {
final Account thisAccount = accounts[0];
RequestQueue requestQueue = Volley.newRequestQueue(RegisterActivity.this);
final String signupURL = "http://localhost:8080/fitnessTrack/api.php?apicall=signup";
StringRequest stringRequest = new StringRequest(Request.Method.POST, signupURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
responseJSON = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Error:", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", thisAccount.getUsername());
params.put("password", thisAccount.getPassword());
params.put("email", thisAccount.getEmail());
params.put("firstname", thisAccount.getFirstName());
return params;
}
};
requestQueue.add(stringRequest);
return responseJSON;
}
#Override
protected void onPostExecute(String result) {
System.out.println(result);
}
}
FYI: I edited the URL to say localhost, even though I'm using my own external IP. Even when the response is null, the database does update with the signup data.
The responseJSON is only updated here
#Override
public void onResponse(String response) {
responseJSON = response; // update UI using responseJSON in here
}
so it won't be ready until that method is called with the response. Try printing in there and it should work
Related
I want to update the "Pass" field using WebAPI, I have created an HTTP PUT Request using Asp.Net WEB API and Android Java with Volley.
through Postman it's updating field value but when I test through my App it's updating the blank value in DB.
Thanks in advance.
private void callPUTDataMethod(String name, String job) {
loadingPB.setVisibility(View.VISIBLE);
String url = URL;
RequestQueue queue = Volley.newRequestQueue(PassUpdt.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingPB.setVisibility(View.GONE);
jobEdt.setText("");
userNameEdt.setText("");
// on below line we are displaying a toast message as data updated.
Toast.makeText(PassUpdt.this, "Data Updated..", Toast.LENGTH_SHORT).show();
try {
JSONObject jsonObject = new JSONObject("Pass");
String output = "Password Updated";
responseTV.setText(output);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PassUpdt.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("EmpCd", "P010");
params.put("Pass", "12345");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
queue.add(jsonObjectRequest);
}
}
I am trying to retrieve data from server using volley, but when I call this method the first time, I get the response from server, but null is returned by the method. If I call it the second time I get the last response.
public String retrieveDataFromServer(String url, String param, final String token){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
data = new JSONObject(response).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try{
data = new JSONObject(error.toString()).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("token", token);
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
// Adding request to request queue
addToRequestQueue(stringRequest);
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
return data;
}
How do I get the response on first call of method?
You can use call back to return Volley response:
public void retrieveDataFromServer(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}
}}
Create interface:
public interface VolleyCallback{
void onSuccess(String response);
}
And get result from activity:
String yourString = "";
#override
public void onResume() {
super.onResume();
retrieveDataFromServer(new VolleyCallback(){
#Override
public void onSuccess(String response){
//Get result from here
yourString = response;
}
});
}
I'm trying to receive raw string response using volley, but I'm not able to get any type of response. Below is my code that I have tried while hiring the user.
I'm able to get key value pair response, but if we are using raw string, it's not throwing any response in log cat.
username = editTextUsername.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
Toast.makeText(this, "Button Hit", Toast.LENGTH_SHORT).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
if (response.trim().equals("Message:Valid User")) {
Toast.makeText(PostLogin.this, "Resposne"+response.toString(), Toast.LENGTH_SHORT).show();
Log.d("Response:",""+response.toString());
} else {
Toast.makeText(PostLogin.this, response, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PostLogin.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
map.put("Content-Type","application/json");
return map;
}
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
String str = "{\"login\":\""+username+"\",\"password\":\""+password+"\"}";
return str.getBytes();
};
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
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
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()
I defines a function in an activity class like this:
private void passParam(String pname){
StringRequest compareRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//handle response code
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {}
}) {
#Override
protected Map<String, String> getParams() {
//set post params
Map<String, String> params = new HashMap<String, String>();
params.put("foo", "foo");
params.put("name", pname);//Grammar error, want to use parameter pname
return params;
}
};
requestQ.add(compareRequest);
}
I want to set post parameter "name" value to the parameter pname of function passParam.How to do this conveniently?Thanks!