Android volley posting null values to database - android

My app is supposed to send some data to my php script and the php script will in turn push it to my online db. But the app keeps sending null values and have tried my php script using a simple HTML form and it's working perfectly and posting to database.
Am still new to using the volley library.
Here is my registration class:
private void registerfunc(final String name, final String email, final String phone, final String address) {`
String url ="http://circleincoprated.com/apps/register.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("JSon data... ", response);
if (response.trim().equals("success")) {
pd.hide();
Toast.makeText(first_run.this, "registration Successful", Toast.LENGTH_LONG).show();
Intent in = new Intent(first_run.this, MainActivity.class);
startActivity(in);
} else {
pd.hide();
Toast.makeText(first_run.this, "registration Failed" + response, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Log.d("JSon Error... ", error.toString());
Toast.makeText(first_run.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> params = new Hashtable<>();
//Adding parameters
params.put("name", name);
params.put("phone", phone);
params.put("email", email);
params.put("address", address);
//returning parameters
return params;
}
};
new MySingleton(first_run.this).addToRequestQueue(stringRequest);
}
While this is my php script:
<?php
extract($_POST);
if(isset($name)){
$resp='';
include 'config.php';
$sql = "INSERT INTO users (id,name,phone,email,address)
VALUES ('','".$name."', '".$phone."', '".$email."','".$address."')";
if ($conn->query($sql) === TRUE) {
$resp="success";
echo($resp);
$sql = "INSERT INTO log (id,response) Values('','".$resp."')";
$conn->query($sql);
}else {
$resp= "Error: " . $sql . "<br>" . $conn->error;
$conn->query($sql);
echo($resp);
}}else{
echo "Empty data";
}
?>

Related

My response in Volley request always get into Error Listener

i am using volly for json response this is my java code i tried every thing but unable to find error in it. it always go to Error Listener.i really dont know why my response goes to error listener any body help me please thanks in advance
private void userLoign() {
name = Name_Et.getText().toString();
email = Email_Et.getText().toString();
password = Password_Et.getText().toString();
Toast.makeText(MainActivity.this, "enter in userlogin", Toast.LENGTH_SHORT).show();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String URL = "added-platters.000webhostapp.com/application/index.php";
Toast.makeText(MainActivity.this, "enter in Volley", Toast.LENGTH_SHORT).show();
StringRequest myReq = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("value");
Log.e("value in success", String.valueOf(success));
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.i("myTag", e.toString());
Toast.makeText(MainActivity.this, "Parsing error", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("myTag", error.toString());
Toast.makeText(MainActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "Register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("lat", "1234");
params.put("log", "1234");
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
myReq.setShouldCache(false);
queue.add(myReq);
}
and this is my json response in php
{"value":"Record Inserted Successfully"}
The Problem is URL Protocol not specified
String URL = "added-platters.000webhostapp.com/application/index.php";
to
String URL = "http://added-platters.000webhostapp.com/application/index.php";

app returning empty Toast

i am getting an empty Toast as response when i try to register a user to my sql database and no useful error hint is thrown in the logcat.
please what could possibly be the cause of this ?
registerProcess
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 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);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
web service
/**
* Adding new user to mysql database
* returns user details
*/
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
There seems to be no error in the code, as far as I can see.
You should check the response you get with curl and see, what is returned.
to get the response from your web service you don't need JSON since you're doing a POST request by Volley. Your toast is empty because simply you're interpreting the response wrong and the objects like this one String errorMsg = jObj.getString("message"); will be empty.
To get the response you should do like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
EDIT :
I managed to spot two things in your web service code.
1- why are you trying to get informations from the server of the same user when you just sent them from your app. That doesn't make sense. You should attach your data as extra to your intent as you did with the email.
2- Volley expects a String type response and you giving him different formats at the same time.
So this a modified version of your code :
Web service :
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
echo "successful";
} else {
echo "notsuccessful";
}
}
Android
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
if (response.equalsIgnoreCase("successful")) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
//add other informations you need like name ect..
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else if(response.equalsIgnoreCase("notsuccessful")) {
Toast.makeText(getApplicationContext(),"new user wasn't registered successfully", Toast.LENGTH_LONG).show();
}
}
}, 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);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
NOTE :
if you wanna know the error from your Mysql request don't show it on your app, just check it in your browser.
I hope this works for you

BasicNetwork.performRequest: Unexpected response code 400 for android on Load

Having trouble on VolleyRequest getting always error response when loading it onCreate. I want to do is when the fragment loads. but when I try it, the Logcat gives me an error 400. on this Java class, i have another function that has sending data to API. I just copied my code :). here is the code that getting a error response.
String url = "MYLINK.com";
try {
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(), "Successful send pending data", Toast.LENGTH_SHORT).show();
String qu = ("update tickets set is_send = '1' where ticket_tick_no = '" + ticket_tick_no_delayed + "'");
sqldb.execSQL(qu);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Error Response here", Toast.LENGTH_SHORT).show();
Log.e("------", String.valueOf(error.networkResponse.statusCode));
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("control_no", trip_no_delayed);
params.put("trip_no", ticket_control_no_delayed);
params.put("ticket_no", ticket_tick_no_delayed);
params.put("ticket_datetime", ticket_datetime_delayed);
params.put("ticket_kmfrom", ticket_kmfrom_delayed);
params.put("ticket_kmto", ticket_kmto_delayed);
params.put("ticket_placefrom", ticket_placefrom_delayed);
params.put("ticket_placeto", ticket_placeto_delayed);
params.put("amount", ticket_amount_delayed);
params.put("discount", ticket_discount_delayed);
params.put("trans_type", transaction_type_delayed);
params.put("passenger_type", passenger_type_delayed);
params.put("lat", ticket_lat_delayed);
params.put("long", ticket_long_delayed);
params.put("device_serial", device_serial_delayed);
return params;
}
};
queue.add(postRequest);
} catch (Exception e) {
e.printStackTrace();
}

Volley POST Request receiving wrong results

I have hosted my API on an online server. When I am testing it using the Postman app for chrome , its returning me the right results (ie. the details of the user from the database) But the below Volley request is getting wrong results (ie. Required Parameters missing);
Screenshot of Postman Request
Volley Request
private void loginUser(final String username, final String password){
String URL_REGISTER = "http://www.h8pathak.orgfree.com/jobs/login.php";
pDialog.setMessage("Logging in...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int result = jObj.getInt("result");
if(result==1){
session.setLogin(true);
JSONObject jObj2 = jObj.getJSONObject("user");
Intent i = new Intent(LoginActivity.this, EmployerActivity.class);
i.putExtra("username", jObj2.getString("username"));
i.putExtra("email", jObj2.getString("email"));
startActivity(i);
finish();
Toast.makeText(LoginActivity.this, jObj.getString("message"), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(LoginActivity.this, jObj.getString("message"),Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(LoginActivity.this, volleyError.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq);
}
The PHP Code to receive request params and return the appropriate response.
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//Get the details from the database and echo in a json response
}
else{
$message = "Required parameters missing!";
$response['result']=0;
$response['message']=$message;
echo json_encode($response);
}
What could be the possible mistake?
Something is wrong with your server configuration: http://www.h8pathak... is not responding as expected, but http://h8pathak... works. The latter is used in your postman example, use it in you Android code and it will work there too.
WWW is the answer. This must be a bug. It goes to the URL and runs it but does not POST.
http://www.example.com/myphpfile.php is wrong.
http://example.com/myphpfile.php is right.

Android volley gives BasicNetwork.performRequest: Unexpected response code 415

While doing a POST request with android volley, My serverside consumes json type in request header, I am facing error 415. Though i have set the headers here by overriding getHeaders method, I am facing this unusual error while making the request.
can any body help me here?
I have also provided the source code below:
private void registerUser( final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 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);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

Categories

Resources