why isn't Volley sending the variables in getParams()? - java

I'm Trying to list machines which are related to the user of the application by sending the username and password to the webpage mentioned in the code verifying the account and then sending back the information of the machines in my database.
the PHP well but the username and password are not being sent.
here is the code for the request:
private void getServerResponse(String username,String password) throws IOException {
String urlS = "http://10.0.2.2/send/sendmachines.php";
RequestQueue RQ= Volley.newRequestQueue(this);
JsonArrayRequest array_request = new JsonArrayRequest(Request.Method.POST, urlS, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
TextView proof =findViewById(R.id.proof);
for(int i=0; i<response.length(); i++){
try {
proof.setText(response.getJSONObject(0).getString("machine_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
TextView proof =findViewById(R.id.proof);
proof.setText(error.getMessage());
}
}){
protected Map<String,String> getParams(){
Map<String,String > params = new HashMap<>();
params.put("username",username);
params.put("password",password);
return params;
}
};
RQ.add(array_request);
}
the username and password were already used to log in and sent as extras to this activity.

in the end it turned out that the code isn't passing through the getParams() so i turned it to a string request and parsed the response string into a jsonArray.
i couldn't find much information about it online so IDK why all this isn't working and i cant consider this an answer so it's more of an update.

Related

How to set checks on different responses volley and get different responses when the request is string request

I'm sending post request for login user on server through volley string request. It works perfectly but the problem is that after sending request server returns me two responses one is success in which token id is given and the other one is failure in which unauthorized user is toast. Im getting the response perfectly but can use check to differentiate these responses. Kindly someone helps me Im very thakful to you.
I'm trying many times but can't get the exact solution.
RequestQueue queue = Volley.newRequestQueue(this);
String url =LOGIN_URL;
final StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
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("grant_type", grant_type);
params.put("client_id", client_id);
params.put("client_secret", client_secret);
params.put("username", email);
params.put("password", password);
return params;
}
};
queue.add(strRequest);

User profile image url is null using google firebase auth

I am using google firebase auth method to authenticate users I am fetching users profile info using firebase method and saving it on server.
When I am trying to save users image uri on server it is showing null value.
Here is my code below:
FirebaseAuth fAuth = FirebaseAuth.getInstance();
FirebaseUser user = fAuth.getCurrentUser();
if(user != null){
saveData();
}
private void saveData(){
final String uid = user.getUid();
final String email = user.getEmail();
final Uri profileImage = user.getPhotoUrl();
final String name = user.getDisplayName();
RequestQueue requestQueue = Volley.newRequestQueue(BookForm.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
if(response.equals("Successfully inserted")){
Toast.makeText(getApplicationContext(),"Successful",Toast.LENGTH_SHORT.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse status = error.networkResponse;
Toast.makeText(getApplicationContext(),"Error:"+status,Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> map = new HashMap<>();
map.put("userId",uid);
map.put("email",email);
map.put("name",name);
map.put("profileImage", String.valueOf(profileImage));
return map;
}
};
requestQueue.add(stringRequest);
}
This is how I am sending data to the server.
router.post('/addData', (req,res) => {
var data = {
User_id: req.body.userId,
Email:req.body.email,
Profile_image:req.body.profileImage,
Name: req.body.name
};
MongoClient.connect(dburl, {useNewUrlParser:true} ,(err,client) => {
if(err){
console.log("Error".red, +err);
}
else{
var collect = client.db('my_db').collection('Example');
collect.insertOne(data, (err,resp) =>{
if(err){
console.log("Error".red, +err);
}
else{
res.send("Successfully inserted");
}
client.close();
});
}
});
});
Someone please let me know why image uri is showing null after saved to server. Any help would be appreciated.
THANKS
There is no requirement that the authentication provider must give you an image URL for the user. If the provider doesn't have one (maybe because the user never provided an image), then you will get null. Your code should be able to handle this case.
Note that the API documentation for getPhotoUrl() specifically says:
This field will be automatically populated on account creation if the
AuthCredential used on signInWithCredential(AuthCredential) contained
such information.

Make POST request to Api in Android Studio

I'm trying to make a POST request to an api that I have created in Visual Studio. The api works, and I finally managed to find some code that allows me to connect to it (and it's not deprecated). The problem is that this code was made for a GET request while I need to make a POST. I created two boxes where I insert the data I want to pass (utente, password) and I created a button that takes the data from the boxex and convert them to string.
I tried already searching a lot of examples and tutorials that show how to make a POST request but the majority are very old and doesn't work anymore in Android Studio, or at least I can't make them work.
Now, this is the function that should be sending the data, I haven't touched the code since I don't really know what to modify except for the Request Method.
private StringRequest searchNameStringRequest(String utente, String password)
{
String url = "http://192.168.1.11:57279/api/utente";
return new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject result = new JSONObject(response).getJSONObject("list");
int maxItems = result.getInt("end");
JSONArray resultList = result.getJSONArray("item");
}
catch (JSONException e)
{
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "Food source is not responding (USDA API)", Toast.LENGTH_LONG).show();
}
});
}
Can someone explain me how to take the data and send it like a JSON Object that has
keys = user, password
values = utente, password (the values are from the two boxes mentioned before)
Thank to anyone who is willing to help me and I hope that asking for so much help isn't against the site rules.
I'm using Volley since is not so complicated and because it seems to work.
Using the GET method it show me the existing json with message cannot be converted to JSON object (I don't care about that, it's just a confirmation that it connects to the api)
Using the POST method it throws the ErrorResponse at the end (Food source is not responding)
EDIT: Added OnCreate method since I need a StringRequest return
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
Button invia = findViewById(R.id.submit);
final EditText utenteInserito = findViewById(R.id.utente);
final EditText passwordInserito = findViewById(R.id.password);
invia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String utente = utenteInserito.getText().toString();
String password = passwordInserito.getText().toString();
queue.cancelAll(R.id.submit);
StringRequest stringRequest = searchNameStringRequest(utente, password);
stringRequest.setTag(R.id.submit);
queue.add(stringRequest);
}
});
}
EDIT: I have followed the suggested answer given but it doesn't seem to work
The resulting code is shown below but I get the OnErrorResponse, I don't think it's a problem with the api because trying with a GET response it gives me the exiting json array, so I think it's a problem with the code.
private StringRequest searchNameStringRequest(final String utente, final String password)
{
String url = "http://192.168.1.11:57279/api/utente";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println(response);
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String,String> map = new HashMap<>();
map.put("user", utente.trim());
map.put("password",password.trim());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
return request;
}
It's working following this question:
How to send a POST request using volley with string body?
Thanks to you all for your interest.
String url = "your url";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
dialog.dismiss();
try {
// your logic when API sends your some data
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(context,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}){
//This is how you will send the data to API
#Override
protected Map<String, String> getParams(){
Map<String,String> map = new HashMap<>();
map.put("name",username.getText().toString());
map.put("password",password.getText().toString());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
Here is a nice tutorial, I have tried it and it worked seamlessly.
Android Login and Registration with PHP, MySQL and SQLite
You can skip the sqlite and the phpMyAdmin part.

What is the best way to save a RequestQueue response?

all. First time posting here.
Anyway, I wrote an Android method that creates a RequestQueue and sends a request to my server via a PHP script to get the server time. The way I have it DOES work, but I'm almost certain it's jury rigged code and there must be a better way to do it.
Bottom Line: I want to save the onResponse response into a String time that I can return (time was a String before being changed to an ArrayList). However, it won't let me use a String from outside onResponse unless it is final. Of course that means I can't change it to response.
I think I'm going about it wrong. Maybe there's a better way to get a response from the PHP script?
The Android method:
public static String getServerTime(Context c){
//Make a final ArrayList that will hold response once received
final ArrayList<String> time = new ArrayList<String>();
//Set up the RequestQueue
RequestQueue requestQueue = Volley.newRequestQueue(c);
String requestUrl = c.getString(R.string.uploadServerUrl)+c.getString(R.string.serverRequestPath);
Response.Listener responseListener = new Response.Listener<String>() { #Override public void onResponse(String response) { time.add(response.toString()); System.out.println("onResponse: "+response.toString());}};
Response.ErrorListener errorListener = new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) {System.out.println("onErrorResponse: "+error.toString());}};
StringRequest request = new StringRequest(Request.Method.POST, requestUrl, responseListener, errorListener){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("option", "0");
return parameters;
}
};
RetryPolicy retryPolicy = new RetryPolicy(){
#Override public int getCurrentTimeout() {
return 50000;
}
#Override public int getCurrentRetryCount() {
return 50000;
}
#Override public void retry(VolleyError error) throws VolleyError {}
};
request.setRetryPolicy(retryPolicy);
requestQueue.add(request);
return time.remove(0);
}
The PHP script:
<?php
if(isset($_POST["option"])){
$option = $_POST["option"];
switch($option){
case 0:
date_default_timezone_set ("America/Chicago");
$time = time();
echo(date("Y;m;d;H;i;s", $time));
}
}
else{
echo "No option set!";
}
?>

Volley library dosent connect to server in some devices

in first i'm use Httpurlconnection and have same issue(Dosent find my Url in server in some devices and other device conncet easy) and i think bug e Httpurlconnection and i decide use Volley and same issue exist when use that
Error:
com.android.volley.VolleyError:java.lang.NullPointerException
Volley Code :
StringRequest postRequest = new StringRequest(Request.Method.POST, uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("HOOOO", response);
progressDialog.dismiss();
try {
JSONObject jsonobj = new JSONObject(response);
int success = Integer.parseInt(jsonobj.getString("success"));
String msg = jsonobj.getString("message");
check(Flag,success,msg,pass,email);
}catch (Exception e){
Snackbar snackbar1 = Snackbar.make(Mainlayout,e.toString(), Snackbar.LENGTH_LONG);
snackbar1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.i("Error Respone", error.toString());
Snackbar snackbar1 = Snackbar.make(Mainlayout,error.toString(), Snackbar.LENGTH_LONG);
snackbar1.show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
if(Flag=="Insert") {
params.put("email", email);
params.put("fact", DeviseBrand);
params.put("model", DeviseModel);
}else if((Flag=="signin") ||(Flag=="update") ){
params.put("email", email);
}
// the POST parameters:
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(this).add(postRequest);
and my uri :
http://domain.com/App/Register.php
Post data and on server get with _Request[];
Volley is a very strong API, i don't think they could have such an issue, check your code maybe in some cases it doesn't initialize the object correctly.
I used Volley for more than 1 year and didn't had such issue.
1-check that you are using the latest release from this link.
2-put your code in question so we can check it with you, also the log could be helpful to trace the issue, also what is the device you are using ?

Categories