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.
Related
I am working on an Android app.
This is one function inside a fragment:
private void guardar_paciente() {
String tag_string_req = "req_login";
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_CHECK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
String id_paciente = jObj.getString("id");
String id_nhc = jObj.getString("nhc");
if (!error) {
editor2.putString("id_paciente", id_paciente);
editor2.putString("nhc", id_nhc);
editor2.apply();
} else {
// Error in login. Get the error message
// String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
// Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("nombre_completo", nombre_completo);
params.put("apellidos", apellidos);
params.put("tel1", tel1);
params.put("tel2", tel2);
params.put("email", email);
params.put("profesion", profesion);
params.put("sexo", sexo);
params.put("fecha_nacimiento", fecha_nacimiento);
params.put("edad", edad);
params.put("peso", peso);
params.put("talla", talla);
params.put("IMC", IMC);
params.put("consentimiento", "1");
params.put("clinica_paciente", clinica_actual);
params.put("imagen_paciente", imagen_paciente);
params.put("firma_paciente", numero+".JPG");
params.put("DNI", DNI);
params.put("direccion", direccion);
params.put("raza", raza);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
What I need is to execute another function, abrirPaciente(), just after guardar_paciente() has finished all its methods and it is safe to change the UI.
I have tried calling abrirPaciente() just after editor2.apply();, but the app crashes.
Making use of callbacks :
public class foo {
interface ExampleInterface {
void finishedServiceCallNoErrors();
void finishedServiceCallWithError(String error);
}
void guardar_paciente(ExampleInterface exampleInterface) {
...
#Override
public void onResponse(String response) {
....
//there was no error
exampleInterface.finishedServiceCallNoErrors();
//there was an error
exampleInterface.finishedServiceCallWithError("your error message here");
....
}
...
}
}
and an example of how you'd make use of this :
public class bar implements foo.ExampleInterface {
//simple example of how you'd use this
private void callingIt() {
new foo().guardar_paciente(this); //here, we can pass `this` because our class is implementing the interface
}
//these now get returned to the class making use of the service call, so you can easily handle things here, instead of worrying about the logic in your service call response
#Override
public void finishedServiceCallNoErrors() {
//TODO("Handle the response with no error");
//your call completed and everything was fine, now do something else
}
#Override
public void finishedServiceCallWithError(String error) {
// TODO("Handle the response with an error")
// there was an error, handle it here
}
}
I'm not sure if this callback pattern will be safe to use if it's being triggered from a background thread, so for that you'd need to switch threads inside the callbacks, so inside finishedServiceCallNoErrors and inside finishedServiceCallWithError you'd potentially need like a Runnable, so you can make use of the main thread, or inside the onResponse of the service call, before triggering the callbacks, you could also change there to the main thread. You can find help with something like that here
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
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[...]
I am new to firebase. I tried to store user data in firebase database using volley. However, firebase has no response regarding my volley request and the database still is null. This is the tutorial I followed.
This is the volley request I used to connect firebase.
public void executeFirebase(){
StringRequest request = new StringRequest(Request.Method.GET, FIREBASE_REGISTER_URL, new Response.Listener<String>(){
#Override
public void onResponse(String s) {
Firebase reference = new Firebase("https://tradeal-930ad.firebaseio.com/users");
if(s.equals("null")) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 1", Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject obj = new JSONObject(s);
if (!obj.has(name)) {
reference.child(name).child("password").setValue(password);
Toast.makeText(activity, "registration successful 2", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, MainPageActivity.class);
activity.startActivity(intent);
activity.finish();
loginUserActivity.finish();
} else {
Toast.makeText(activity, "username already exists", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
loading.dismiss();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println("" + volleyError );
loading.dismiss();
}
});
RequestQueue rQueue = Volley.newRequestQueue(activity);
rQueue.add(request);
}
change the rules of your database to public
{
"rules" :
{
".read" : true,
".write" : true
}
}
otherwise
{
"error" : "Permission denied"
}
this will be your response
to know more about rules you can visit security rules
I have used volley to call api's so the version I was using is "compile 'com.mcxiaoke.volley:library-aar:1.0.0'" but today almost after 5 months it seems some error has caused after I imported my project work in another laptop so I am getting error after running
W/System.err: remove failed: ENOENT (No such file or directory) :
/data/user/0/in.medma.callbin/files/.Fabric/com.crashlytics.sdk.android.crashlytics-core/log-files/crashlytics-userlog-59DC9B9B0184-0001-3355-3FD34D64056C.temp
E/UncaughtException: java.lang.NullPointerException: Attempt to invoke
virtual method 'int java.lang.String.hashCode()' on a null object
reference
at com.android.volley.Request.(Request.java:136)
at com.android.volley.toolbox.StringRequest.(StringRequest.java:43)
at in.medma.callbin.LoginActivity$5.(LoginActivity.java:0)
at in.medma.callbin.LoginActivity.requestForSMS(LoginActivity.java:203)
at in.medma.callbin.LoginActivity.validateForm(LoginActivity.java:189)
at in.medma.callbin.LoginActivity.onClick(LoginActivity.java:155)
In Fabric crashlytic I am getting this
Volley request
private void requestForSMS(final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
boolean error = responseObj.getBoolean("error");
String message = responseObj.getString("message");
// checking for error, if not error SMS is initiated
// device should receive it shortly
if (!error) {
// boolean flag saying device is waiting for sms
pref.setIsWaitingForSms(true);
viewPager.setCurrentItem(1);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Error: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing user parameters to our server
* #return
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mobile", mobile);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Compile with
compile 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
DEPRECATED
Please note, this project is deprecated and no longer being maintained, please use official version volley.
compile 'com.android.volley:volley:1.0.0'