com.android.volley.AuthFailureError in Android - android

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.

Related

How get Firebase Device Token like string?

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);

Handle callbacks in my library

I have written an android library that does network calls to various websites and returns the necessary content. I am using Volley library which has callbacks like onResponse and onFailure. Initially this library was an app and was later changed to an library.
When it was an app I could handle the callbacks easily. Whenever the callback happens I call the required functions from there but now when I import as the library and try to use it the control returns from the library as soon as I call it and the call back is not doing anything.
public void sendForVerification(final String Response, final String Secret, final String Name) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
flag = true;
},
new Response.ErrorListener() {
#Override
public void onErrorResponse (VolleyError error){
flag = false;
}
}}) {
#Override
protected Map<String, String> getParams () throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("secret", Secret);
params.put("response", Response);
return params;
}
};
requestQueue.add(stringRequest);
}
}
When this code was a part of the app instead of returning the flag value I would call an appropriate function to handle the result. Now whenever I call these functions the value of flag is returned before the callback is done and this is causing some problem.
My question is how can I warp this around a callback so that the app that uses this library will be notified when the network call is done?
You could add your own callback(s) for your library
interface YourCallback<T> {
onResponse(T value);
}
public void sendForVerification(final String Response,final String Secret,final String Name, YourCallback<Boolean> callback){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onResponse(true);
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onResponse(false);
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params = new HashMap<>();
params.put("secret",Secret);
params.put("response",Response);
return params;
}
};
requestQueue.add(stringRequest);
}
boolean flag;
api.sendForVerification("", "", "", new YourCallback<Boolean>() {
#Override
public void onResponse(Boolean value) {
flag = value;
}
});
Volley is asynchronus, so any other upcoming process after you send the request will continue as normal without waiting for a response. That's why your flag value seems like it hasn't changed, because you probably try to access it while the request is still waiting for a response. That's the reason of callback implementations: you take certain actions as soon as you get a response, and you shouldn't try to handle values that will be returned from another method, because they will be returned before they change.

How to make use of list of registered users on mysql database to create chat app

Good day, everyone. Please, I really need an answer to this.
I am new to Android development. I am trying to develop an app meant for broadcast messaging. I have been able to create a database where registered users are stored in a table. However, I lack the idea of what to do next.
Most of the tutorials I have seen teach how to make use of users registered on the PARSE platform. But I wonder if I could be able to lift the users on MySQL database and integrate it with any chat client. Thanks.
Check out the Volley library, it's a library made by Google to make requests.
here you have some explications about Volley. You'll need to import volley library in your project.
you have to create the singleton class given by Google (Here called mySingleton) and to create a request class with code like this one :
public class MyRequest {
private Context context;
private RequestQueue queue;
public MyRequest(Context context, RequestQueue queue) {
this.context = context;
this.queue = queue;
}
public void getArticles(final GetArticlesCallback callback){
String url = "YourScriptUrl";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess("I will get this string in the activity");
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onError("erreur : " + error.toString());
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("tag", "postArgument1");
map.put("tag2", "postArgument2");
return map;
}
};
queue.add(request);
}
public interface GetArticlesCallback{
void onSuccess(String success);
void onError(String error);
}
}
And you call this class in your activity :
//queue is a RequestQueue
//request is a Myrequest
queue = VolleySingleton.getInstance(this).getRequestQueue();
request = new MyRequest(this, queue);
request.getArticles(new MyRequest.GetArticlesCallback() {
#Override
public void onSuccess(String success) {
}
#Override
public void onError(String error, String id) {
}
});

Volley Request Callback passing the wrong callback response

I've added a callback on the volley request and, I have two request started from 2 different activity. When I perform the first request, then the second return the response of the first..
This is my request and callback:
public static void RequestJsonToServer(Context ctx, final JSONObject params, final VolleyCallback callback){
MySingleVolley.getInstance(ctx).
getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,ctx.getString(R.string.defaultServerRequestUrl),params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callback.onSuccess(response);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
MySingleVolley.getInstance(ctx).addToRequestQueue(jsObjRequest);
}
public interface VolleyCallback{
void onSuccess(JSONObject string);
}
And this is one of the two starting request:
Global.RequestJsonToServer(getActivity(), jsonObject, new Global.VolleyCallback() {
#Override
public void onSuccess(JSONObject result) {
Toast.makeText(getActivity(),result.toString(), Toast.LENGTH_LONG).show();
}
});
I hope someone can help me
Thanks
Edit:
I change it like this
Global.RequestJsonToServer(getApplicationContext(), jsonObject, new Global.VolleyCallback() {
#Override
public void onSuccess(JSONObject result) {
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onSuccessCustom(JSONObject string) {
}
}, true);
And the other one with false.. But maybe is the wrong way to use it..I would like to have one single callback and reuse it, not switch between two callbacks
MY SOLUTION
I've found my own solution, the problem wasn't in the callback but was in the volley request. The response of each request was cached and i don't know why, it will be return the wrong always the wrong response.
I've just added this before adding request to queue:
jsObjRequest.setShouldCache(false);
This is happening because your callback method is common[onSuccess(...)]why don't you write 2 call backs and based on the condition use the required callback.
To implement it write 2 methods in your interface and pass some sort of flag to choose callback.
Change your interface to this.
public interface VolleyCallback{
void onSuccess(JSONObject string);
void customOnSuccess(JSONObject string);
}
And your method to this
public static void RequestJsonToServer(boolean flag,Context ctx, final JSONObject params, final VolleyCallback callback){
MySingleVolley.getInstance(ctx).
getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,ctx.getString(R.string.defaultServerRequestUrl),params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(flag){
callback.onSuccess(response);
}else{
callback.CustomOnSuccess(response);
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
MySingleVolley.getInstance(ctx).addToRequestQueue(jsObjRequest);
}
Yes its reusable use onSucces where ever you have only one callback use both when you have more than one.

ReST API security

I am creating an Android App that will communicate with ReST API . And i want to know how do I provide security to the APIs
Here is my sample API method
#GET
#Path("/count")
public String totalUserCount(){
return "100";
}
and here is my call to api from android
StringRequest stringRequesttoNearby = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String responseString) {
//response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
};
//add request to queue
Singleton.getInstance().getRequestQueue().add(stringRequesttoNearby);
So I want to know how I can add security to this API call
You could use Oauth1.0a, Oauth2 check out the link
Follow link Secure Api

Categories

Resources