Volley library has caused exception - android

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'

Related

Calling a function inside onRespons method

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

ReCaptcha V2 response error 12008 in Android

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.

Error on progressDialog and Toast with custom recyclerview adapter file

I need help for showing toast and progress dialog inside volley request, and I use a custom adapter file when click on the card will send data with volley, please give better flow or fixing this code.
this is my onBindViewHolder inside adapter file
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final DataPicking task = taskList.get(position);
holder.numberid.setText(task.getNomorid());
holder.nama.setText(task.getNamakonsumen());
holder.rate.setText(task.getRate());
holder.tanggal.setText(task.getTanggal());
holder.salesman.setText(task.getSalesman());
holder.cardList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setTitle("Proses Picking")
.setMessage("Apakah kamu yakin ingin memproses picking data ini?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String nomorid = taskList.get(position).getNomorid();
PickingActivity picking = new PickingActivity();
picking.kirimData(nomorid);
}})
.setNegativeButton(android.R.string.no, null).show();
}
});
}
and this is kirimData function for send data with volley
public void kirimData(final String nomorid){
// Log.e("ini kirimdata ",nomorid);
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Loading ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Constants.URL_SET_PICKING, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Picking Response: " + response.toString());
//hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Log.e(TAG, "obj: " + jObj.toString());
String error = jObj.getString("status");
Log.e(TAG, "obj: " + error);
// Check for error node in json
if (error.equals("1")) {
// user successfully logged in
// Create login session
mAdapter.notifyDataSetChanged();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getBaseContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/*Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();*/
Log.e(TAG, "Proses Picking Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Proses Picking Failed", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("nomorid", nomorid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
and this is the error log
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.sip.gotrack.PickingActivity.kirimData(PickingActivity.java:167)
at com.sip.gotrack.PickingAdapter$1$1.onClick(PickingAdapter.java:69)
please help me for this error
Where is your pDialog being initialized?
Inside kirimData, initialize pDialog like this in the beginning.
pDialog = new ProgressDialog(context);
It seems pDialog is not initialized before this method is called.

Cast Error Mongodb Nodejs

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[...]

Android - trouble updating SQLite after success webrequest on return statement

I have a function that uses StringRequest to send a post request to my server. The script on the server side updates the database with the user's new settings.
The server side script returns 1 on success and 0 on failure, with appropriate message too. What I have tried to do with the StringRequest function is a similar thing.
public int updateLiveSettings(Switch discoverySwitch, Switch menSwitch, Switch womenSwitch) {
// Tag used to cancel the request
final String email = db.getFromTable(getActivity(), "email", SQLiteHandler.TABLE_LOGIN, "WHERE _id="+uid);
final String discovery = switchValue(discoverySwitch);
final String men = switchValue(menSwitch);
final String women = switchValue(womenSwitch);
final String tag_string_req = "update_settings";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_UPDATE_SETTINGS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt("success");
// Check for error node in json
if (success == 1) {
Log.i(tag_string_req, success+" - yes");
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
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("tag", tag_string_req);
params.put("account", discovery);
params.put("men", men);
params.put("women", women);
params.put("email", email);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return success;
}
Success is always returned as either 1 or 0. I then use this to update the stored settings in the SQLite database.
womenSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
//Log.i("live attempt", updateLiveSettings(discoverySwitch, menSwitch, womenSwitch)+"");
if(updateLiveSettings(discoverySwitch, menSwitch, womenSwitch) == 1){
Log.i("womenswitch", "live update success");
if(isChecked==true){
Log.i("womenswitch", "is checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=1", "uid="+uid);
}else{
Log.i("wpmenswitch", "is not checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=0", "uid="+uid);
if(menSwitch.isChecked()==false){
menSwitch.setChecked(true);
db.update(SQLiteHandler.TABLE_SETTINGS, "men=1", "uid="+uid);
}
}
}
}
});
The problem I'm having is that even when the update is successful and the correct int is returned the local database isn't updated.
It basically never gets passed if(updateLiveSettings(discoverySwitch, menSwitch, womenSwitch) == 1) I get nothing in the LogCat so I can only assume I'm doing this incorrectly.
Any help would be great :)
This is the nature of an asynchronous request.
When you look at the image at Send a Request (and at your code), you can see that the request is put into a request queue. Only when the request is performed or a result taken from the cache, it will return to your main thread in the form of the onResponse or onErrorResponse method.
But when the result is delivered to your application, your method updateLiveSettings has already returned and delivered whatever was in the success variable. You can see this order of events, when you add a Log output after the if statement.
To update the database based on the success result, you must do this inside the onResponse method, e.g.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// ...
updateLiveSettings(discoverySwitch, menSwitch, womenSwitch, isChecked);
}
and in updateLiveSettings()
public void onResponse(String response) {
Log.d("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("success");
// Check for error node in json
if (success == 1) {
Log.i(tag_string_req, success+" - yes");
if (isChecked==true){
Log.i("womenswitch", "is checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=1", "uid="+uid);
} else {
Log.i("wpmenswitch", "is not checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=0", "uid="+uid);
}
} else {
// ...

Categories

Resources