Good afternoon,
I am getting a Cast Error from my Nodejs backend while I am requesting from my Android App. To be clear, first request from my app works well, but the second request causes a Cast Error. Apart from that, I dont get any error when I use Postman, no matter how many requests I fire.
Backend Code Nodejs and Mongoose
app.post('/adsclicked/:id', function (req, res) {
Ad.findOne({_id : req.params.id}, function (err, data) {
if (err) console.log(err);
var new_clicked_count = data.clicked + 1; //Updating count
data.set({ clicked: new_clicked_count }); //Saving new count
data.save(function (err, updatedData) {
if (err) console.log(err);
res.send(updatedData); //Indicate new object
});
});
});
Android App
public void AdVisitCount(Context context, String id){
Log.d("advisit id", id);
RequestQueue queue = Volley.newRequestQueue(context);
URL_FOR_ADVISITCOUNT = URL_FOR_ADVISITCOUNT + id;
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_ADVISITCOUNT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "advisitcount Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
queue.add(strReq);
}
check the data type of updatedData in nodejs
console.log(typeof(updatedData));
See if it is a object or a string
Problem is adding “id” to Url with every request. On second it was url +id+id and so on....
Delete the URL = URL + id;
line and add the query parameter id inside the request:
[...].POST, URL+id, new Response.Listener[...]
Related
Below is my implementation of ReCaptcha V2 in my Android app.
When I run it, it returns: Error message: unknown status code: 12008
This means the following:
public static final int RECAPTCHA_INVALID_KEYTYPE Cannot start the
reCAPTCHA service because type of site key is not valid.
Please register new site key with the key type set to "reCAPTCHA
Android" via //g.co/recaptcha/androidsignup.
Constant Value: 12008
My site key is available on my ReCaptcha admin portal, so what do I need to do for it to be 'valid'?
The code example that I've implemented does include the following comments regarding the server url:
//it is google recaptcha siteverify server
//you can place your server url
Is this a requirement or a suggestion?
public void onCaptchaClick(View view) {
SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY)
.addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
#Override
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
if (!response.getTokenResult().isEmpty()) {
handleSiteVerify(response.getTokenResult());
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
Log.d(TAG, "Error message: " +
CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
} else {
Log.d(TAG, "Unknown type of error: " + e.getMessage());
}
}
});
}
protected void handleSiteVerify(final String responseToken){
//it is google recaptcha siteverify server
//you can place your server url
String url = "https://www.google.com/recaptcha/api/siteverify";
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.getBoolean("success")){
Toast.makeText(getApplicationContext(),String.valueOf(jsonObject.getBoolean("success")),Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),String.valueOf(jsonObject.getString("error-codes")),Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Log.d(TAG, "JSON exception: " + ex.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error message: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("secret", SECRET_KEY);
params.put("response", responseToken);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
This error means that you are not using the right key.
Have you created an Android app key or a website key? I got this error when I tried to use the web key for the app, you need an Android app key.
I am building a login in my android app. I am trying to make to make my app communicate with a Node.JS server using volley to make network request. The node.js server is already setup and is running. I made sure that my PC and my android phone are on the same network (I really don't know if this is necessary). Also Mongo DB is setup and running. But I get an error response when I try to login. This is my code:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getLoginEmail = loginEmail.getText().toString();
String getLoginPassword = loginPassword.getText().toString();
if (!TextUtils.isEmpty(getLoginEmail) && !TextUtils.isEmpty(getLoginPassword)) {
loginUser(getLoginEmail, getLoginPassword);
} else if...
}
});...
private void loginUser(final String gottenLoginEmail, final String gottenLoginPassword) {
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage(getString(R.string.logging_in));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("onResponse", response);
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Log.i("Response", response); //logged response
//check if response at first position (index 0) equals success
if (jsonObject.names().get(0).equals("success")) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
...
}
} catch (JSONException e) {
Log.i("Exception", e.getMessage()); //logged exception
Snackbar.make(findViewById(R.id.login_activity), e.getMessage(), Snackbar.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Error", "ERRROR: " + error.getMessage()); //logged error. Refer to debugger image below
progressDialog.dismiss();
Snackbar.make(findViewById(R.id.login_activity), error.getMessage(), Snackbar.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", gottenLoginEmail);
params.put("password", gottenLoginPassword);
return params;
}
};
RequestHandler.getInstance(LoginActivity.this).addToRequestQueue(stringRequest);
}
In my Constants Java Class I have the following:
public class Constants {
public static final String ROOT_URL = "http://192.168.43.1:5000/api/user/auth/";
public static final String URL_LOGIN = ROOT_URL + "signin";
public static final String URL_REGISTER = ROOT_URL + "signup";
//192.168.43.1 is the DHCP server of the network my pc and android phone is connected to
//5000 is the node.js application port i.e. localhost:5000
}
Please I need help. I have been battling with this for 3 days now...
When I run the app I get this in the debugger console
N.B. "localhost:5000/api/user/auth/signin" is the API endpoint login route.
I think your trouble is Firewall try to disable it
if your OC is windows follow this guide https://www.youtube.com/watch?v=dlBgoVMXIWo
I am a new guy in android and trying to make a rest api call using volley.
I am getting "com.android.volley.ClientError" in my code. Can anyone help me to solve this please.
private void LoginByNet(String uID, String pSD){
String URL = "http://myipaddress:65017/api/values";
RequestQueue rq = Volley.newRequestQueue(this);
JsonObjectRequest jq = new JsonObjectRequest(
Request.Method.GET,
URL,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Success:"+response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error:"+ error.toString(), Toast.LENGTH_SHORT).show();
userName.setText(error.toString());
}
}
);
rq.add(jq);
}
This means that the server returned a 4xx error code.
[https://github.com/google/volley/blob/d1a3d5388c79ff1a6fdb904daeff9b39d0bb7d26/src/main/java/com/android/volley/toolbox/BasicNetwork.java#L199][1]
You can get the exact error code using : #error.networkResponse.statusCode
I am working with volley library in my android app development.
I have a base url and I need to append some value at the end of the url,click here,
So, this value "ZGxb87HuJK" keeps changing dynamically in my program and need to append this value at the end of url. How to add this in params?
Use this way.
StringRequest strreq = new StringRequest(Request.Method.GET,
"https://sample.com/testing/" + Hear Your dynamic value,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
// get response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
}
});
Volley.getInstance(this).addToRequestQueue(strreq);
String URL = "https://sample.com/testing/" + "dynamic value e.g ZGxb87HuJK";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, null,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
// Adding the request to the queue along with a unique string tag
MyApplication.getInstance().addToRequestQueue(jsonObjectReq, "getRequest");
Change your code like this
public void doMySearch(List<String> IDs) {
for (String Id : IDs) {
String url = "http://api.tvmaze.com/shows/" + Id + "?embed=nextepisode";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("ONREQUEST ");
try {
String name = response.getString("name");
String airdate = response.getJSONObject("_embedded").getJSONObject("nextepisode").getString("airdate");
HashMap<String, String> episodesToDisplay = new HashMap<String, String>();
episodesToDisplay.put(name, airdate);
listOfEpisodes.add(episodesToDisplay);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
System.out.println("BEFORE ADD TO REQUEST QUEUE ");
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
System.out.println("AFTER ADD TO REQUEST QUEUE ");
}
System.out.println("AFTER FOR LOOP ");
}
See my prints in the code, the output I get with 4 items in my IDs list is:
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
BEFORE ADD TO REQUEST QUEUE
AFTER ADD TO REQUEST QUEUE
AFTER FOR LOOP
ONREQUEST
ONREQUEST
ONREQUEST
ONREQUEST
The point is System.out.println("AFTER FOR LOOP "); is executed before onRequest and I want it to call a function in that place which would use a list populated inside onRequest. I thought onRequest would be executed after adding items to queue but it's not. Is there any way I can make it work in the order I expect? I cannot call funtion inside onRequest since I want it to use fully populated list and onRequest is called many times at once.
You have to create a callback to it.
Like this
public interface VolleyCallback {
void onSuccess(String string);
void onFailure(VolleyError error);
}
Then when you call your doMySearch function, you pass your callback, like this:
doMySearch(ids, new VolleyCallback() {
#Override
public void onSuccess(String response) {
Log.d("Success", response);
}
#Override
public void onFailure(VolleyError error) {
Log.e("Error", "ops thats an error!");
}
});
And finally, on your doMySearch function, where you override the onResponse and onErrorResponse listener you call your callback, like this:
public void doMySearch(List<String> IDs, final VolleyCallback callback) {
for (String Id : IDs) {
String url = "http://api.tvmaze.com/shows/" + Id + "?embed=nextepisode";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("ONREQUEST ");
callback.onSuccess("ONREQUEST");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
callback.onFailure(error);
}
});
System.out.println("BEFORE ADD TO REQUEST QUEUE ");
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
System.out.println("AFTER ADD TO REQUEST QUEUE ");
}
System.out.println("AFTER FOR LOOP ");
}
Your code block is executed async, so you have to put your code inside the onResponse method.