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.
Related
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.
While I am hitting API using JSON I am getting the following error I don't know where is my error can anybody help in resolving it as I don't have much knowledge of Json Parsing
public void onPaymentSuccess(String s, PaymentData data) {
String paymentId = data.getPaymentId();
String signature = data.getSignature();
String orderId = data.getOrderId();
callvolly(paymentId,signature,orderId );
}
private void callvolly(final String paymentId,final String signature,final String orderId) {
String tag_json_obj = "json_obj_req";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("posting...");
pDialog.show();
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = "http://staging.s.com//payment/validate" ;
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_SHORT).show();
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("paymentId", paymentId);
MyData.put("signature", signature);
MyData.put("orderId", orderId);
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}
java.lang.IllegalArgumentException: Request#getParams() or
Request#getPostParams() returned a map containing a null key or value:
(signature, null). All keys and values must be non-null.
at com.android.volley.Request.encodeParameters(Request.java:478)
at com.android.volley.Request.getBody(Request.java:466)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:275)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:249)
at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:94)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:123)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:111)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:90)
I am trying to put in a delete account option in my application, however when I try to delete the account I am not getting a respsonse from the web server.
Instead I get the error:
org.json.JSONException: End of input at character 0 of
I have tried to change the request method to DELETE however I am not too familiar with android and databases so I am not sure if that would work.
I am not sure whether the problem lies with the php or the java code, when I run the debugger in android studio the String response returns:
response: ""
php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$id = $_POST['id'];
require 'conn.php';
$sql = "DELETE * FROM Patients WHERE patientID='$id'";
if(mysqli_query($conn, $sql)){
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "Error!";
echo json_encode($result);
mysqli_close($conn);
}
}
?>
Java delete method:
private void deleteAccount() {
final String name = this.name.getText().toString().trim();
final String lName = this.lName.getText().toString().trim();
final String dob = this.dob.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
final String passwordConf = this.cPassword.getText().toString().trim();
final String id = getID;
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DELETE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Toast.makeText(EditAccount.this, "Account Deleted", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(EditAccount.this, "Error: "+e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EditAccount.this, "Error: "+error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
I expect the toast to pop up and say account deleted but instead I get the error message stated at the top.
p.s. this is just a prototype so I am not worried about security at the moment.
Thanks!
Whatever the issue might be, I am going to take a guess and say if($_SERVER['REQUEST_METHOD']=='POST') is the root of your issue.
Your request may be sent wrong to the server and the method is not recognized as POST which would explain a "" response since you do not offer an alternative to what should happen at the condition failing.
Send a bad request response (400) back and you will have the ability to troubleshoot this issue in your Java code... PHP is fine.
if($_SERVER['REQUEST_METHOD']=='POST') { /* ... */ }
else {
http_response_code(400);
// exit('Bad request method.');
// or for a json response:
echo json_encode([
'success' => "0",
'message' => "Bad Request Method used."
]);
}
Also, I have to say... Security should always be a concern... It does not take but a few more lines of code to filter the user request, and make your query a bit more secure via prepared statements. It's more of an issue of habits; one day you might forget a query here or there.
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.
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 ?