I want to send device Token information when sending membership information to server.
But how should I go because getToken is no longer in use?
I've been using this before:
params.put("deviceToken", FirebaseInstanceId.getInstance().getToken());
Easy and worked but getToken is deprecated
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("deviceToken", deviceTokenID); <<<---- DEVICE ID TOKEN
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
To solve this, you need to use a success listener like in the following lines of code:
FirebaseInstanceId.getInstance().getInstanceId()
.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String tokenId = instanceIdResult.getToken();
//Do what you need to do with the token
}
});
String deviceToken= FirebaseInstanceId.getInstance().getToken();
params.put("deviceToken", deviceToken);
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.
private void register(final String name, final String city, final String bloodgroup, final String password, final String mobileno)
{
StringRequest stringRequest = new
StringRequest(Request.Method.POST,Endpoints.register_url,new
Response.Listener<String>(){
#Override
public void onResponse(String response) {
if (response.equals("Success")){
Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show();
startActivity (new Intent (RegisterActivity.this, MainActivity.class));
finish ();
}else{
Toast.makeText(RegisterActivity.this, response, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Something went wrong :(", Toast.LENGTH_SHORT).show();
Log.d("VOLLEY",error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name", name);
params.put("city", city);
params.put("bloodgroup", bloodgroup);
params.put("password", password);
params.put("number", mobileno);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
I want to start a new activity from this activity.But it didnt show up after showing "success". I don't know what's the problem in this code.
try remove finish () ;
I hope it will work with you.
I am trying to use Google Speech api to translate text from any language to English. There is no error in api connection but
volley
is giving me error.
Thanks for help.
My Activity code:
private void Translate(String s) {
//trim out translate
final String stringToTranslate = s.substring(9);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CONNECTION,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(TO_TRANSLATE, stringToTranslate);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
My PHP Server file, it is in the server and link to this file is provided by URL_CONNECTION Constant
<?php
use Google\Cloud\Translate\TranslateClient;
if($_SERVER['REQUEST_METHOD']=='POST'){
$fb = $_POST['toTranslate'];
require 'vendor/autoload.php';
$translate = new TranslateClient([
'key' => 'My TranslateApi key'
]);
$result = $translate->translate($fb, [
'target' => 'en'
]);
$conversion = $result['text'];
echo $conversion;
}
?>
When i run this activity it toast com.android.volley.AuthFailureError
I googled but i didn't get the relevant answers.
I've had a similar problem. It turned out I was overriding the wrong method to pass parameters. I should send them by the Header, so I changed my code to
"#override public Map<String, String> getHeaders()"
instead of
"#override protected Map<String, String> getParams()"
Maybe it's also your case, you need pass by the header of the message.
I have 3 functions that are uploading images and setting the name of an image on a server. The thing is, I can't get all functions to work at a time. Only one function works and the other throws a NullPointerException that aren't pointing to anything specific but just the first line in the function.
private void uploadMainImage()
{
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest ppRequest = new StringRequest(Request.Method.POST,URL_IMAGE_MAIN , new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println("Response[Job Image Main]: " + response.toString());
uploadThumbImage();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
System.out.println("Job Image profile Error: " + error.getMessage());
progressDialog.hide();
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("ImageName",jobID + "-1.jpg");
params.put("base64", pp_finalImage);
return params;
}
};
queue.add(ppRequest);
}
private void uploadThumbImage()
{
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest ppRequest = new StringRequest(Request.Method.POST,URL_IMAGE_THUMB , new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println("Response[Job Image Thumb]: " + response.toString());
//updateImageName();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
System.out.println("Job Thumb Image profile Error: " + error.getMessage());
progressDialog.hide();
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("ImageName",jobID + "-1.jpg");
params.put("base64", thumb_finalImage);
return params;
}
};
queue.add(ppRequest);
}
private void updateImageName()
{
SharedPreferences prefs = getActivity().getSharedPreferences("USER_DETAILS", Context.MODE_PRIVATE);
String userID = prefs.getString("USER_ID", "NO_SESSION");
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
Map<String, String> params = new HashMap<String, String>();
params.put("postpicture ", jobID + "-1.jpg");
params.put("userid", "1");
params.put("postjobid ", jobID);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,URL + "updateJobPostImage" ,new JSONObject(params), new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(LOG_TAG,"Response[Image Name Update Job]: " + response.toString());
try
{
String status = response.getString("result");
if(status.equals("Success"))
{
progressDialog.hide();
progressDialog.dismiss();
}
else
{
Log.d(LOG_TAG," Image Name Update Failed, Aborting.");
progressDialog.hide();
progressDialog.dismiss();
}
}
catch (JSONException e)
{
Log.d(LOG_TAG,e.getMessage());
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
progressDialog.hide();
progressDialog.dismiss();
Log.d(LOG_TAG, "Image Name Update Error: " + error.getMessage());
}
});
queue.add(request);
}
This is the log
04-30 00:41:29.074 14041-14041/com.antisaby.trackit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antisaby.trackit, PID: 14041
java.lang.NullPointerException
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at fragments.homefragments.AddServiceFragment.uploadThumbImage(AddServiceFragment.java:397)
at fragments.homefragments.AddServiceFragment.access$1100(AddServiceFragment.java:50)
at fragments.homefragments.AddServiceFragment$8.onResponse(AddServiceFragment.java:368)
at fragments.homefragments.AddServiceFragment$8.onResponse(AddServiceFragment.java:363)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5322)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
The uploadMainImage function executes first. If the response is good, it calls uploadThumbImage. If the result of uploadThumbImage is good, it calls updateImageName. If i don't comment out any function, the exception occurs in the uploadThumbImage function. If i comment out the first function, exception occurs in the last function. If I try to catch the exception, the message comes out to be null.
A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
Source
I recently wrote a android app with volley to do the http request,
At first,I used local host to work as a server,it worked perfectly.
However, as I moved my node.js code to heroku server, my app will often get timeout error.
The log from heroku like
2016-04-23T00:59:01.653405+00:00 heroku[router]: at=info method=POST path="/ispassword" host=lit-island-38801.herokuapp.com request_id=1273b9e7-6632-4117-b68f-5d7d8eb83b52 fwd="152.3.43.156" dyno=web.1 connect=1ms service=27ms status=200 bytes=224
2016-04-23T00:59:33.426223+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/ispassword" host=lit-island-38801.herokuapp.com request_id=e861aa6f-c40b-440c-af1c-3a24eded9c2c fwd="152.3.43.156" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0
And my android app request code is like this
RequestQueue queue = Volley.newRequestQueue(Login.this);
StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d(TAG,response);
if(response.equals("no")){
onLoginFailed();
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show(); //show the toast for a long time
Intent intent = new Intent(Login.this, Login.class);
startActivity(intent);
finish();
}
//Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
String del =":";
String []res = response.split(del);
fetched_pw = res[1].replaceAll("\\}","").replaceAll("\"","").replaceAll("\\]","");
Log.i(TAG,fetched_pw);
Log.i(TAG,password);
Log.i(TAG,"version1");
if(password.equals(fetched_pw)){
progressDialog.show();
onLoginSuccess();
progressDialog.dismiss();
}
else{
onLoginFailed();
progressDialog.dismiss();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
return params;
}
};
queue.add(strRequest);
}
And my node.js code to handle this is like
app.post('/ispassword', function (req, res) {
var pg = require('pg');
var ans;
pg.defaults.ssl = true;
pg.connect("postgres://abcdefghij:ev0Y_GVqmX5zd22oM3KQ8smXS5#ec2-11-11-11-111-1-1.compute-1.amazonaws.com:5432/d4drnop61h6hv7", function(err, client) {
if (err) throw err;
console.log('Get to Function ispassword');
var email = req.param('email');
client.query("select password from USER_TABLE where email = $1;",[email],function (error,results) {
if(results.rowCount>0){
var que = client.query("select password from USER_TABLE where email = $1;",[email]);
//var que = client.query("select password from USER_TABLE");
que.on("row", function (row, result) {
//console.log(row);
result.addRow(row);
});
que.on("end", function (result) {
res.send(result.rows);
});
console.log("send");
}
else{
res.send('no');
}
});
});
});
Can someone save my day please??