How to Decode JSON Object File in PHP - java

I used JSON Request to send some parameters now I want to convert my json data by using json_decode but it does not allowing me to do so.
private void makeJsonObjReq() {
Map<Object, Object> postParam = new HashMap<>();
RequestQueue queue = Volley.newRequestQueue(this);
final String URL = "https://www.facilesol.com/api/test.php";
ArrayList<Map> myArray = new ArrayList<>();
Cursor data2 = dbHelper.getAllData();
if (data2.getCount() == 0)
{
Toast.makeText(getContext(), "Your cart is empty",
Toast.LENGTH_SHORT).show();
}
else if (data2.moveToFirst()) {
while (!data2.isAfterLast()) {
Map<String, String> map1 = new HashMap<>();
int pId = data2.getInt(1);
String quantity = data2.getString(3);
String price = data2.getString(4);
String priceID = data2.getString(6);
String toppingID = data2.getString(7);
map1.put("product_id", String.valueOf(pId));
map1.put("price_id", String.valueOf(priceID));
map1.put("topping_id", String.valueOf(toppingID));
map1.put("quantity", quantity);
map1.put("sale_price", String.valueOf(price));
myArray.add(map1);
data2.moveToNext();
}
}
postParam.put("branch_db",branchDb);
postParam.put("line_items", myArray);
Log.d(TAG, myArray.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(CheckOut.this, String.valueOf(response), Toast.LENGTH_SHORT).show();
try {
Log.d(TAG, response.toString());
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//Toast.makeText(CheckOut.this, "Please fill correct information and check your internet connection", Toast.LENGTH_SHORT).show();
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonObjReq.setTag(TAG);
// Adding request to request queue
queue.add(jsonObjReq);
}
////////////////////////////////////////////////////////////////////////////
API File
//////////////////////////////////////////////////////////////////////////
<?php
include(DBConn.php);
$DBName = $_GET["branch_db"];
$JsonFile = $_GET["line_items"];
$arr = json_decode($JsonFile, true);
$Query = "SELECT MAX(cartid) As MaxOrderID FROM poscustomershoppingdata".
" WHERE cartid LIKE '".date("Ymd")."%'";
$rstOdr = mysql_db_query($DBName,$Query);
if (mysql_num_rows($rstOdr) > 0)
{
$objOdr = mysql_fetch_object($rstOdr);
if($objOdr->MaxOrderID == NULL)
{
$OrderID = 0;
}
else
{
$OrderID = substr($objOdr->MaxOrderID,9,11);
}
}
$OrderID = $OrderID + 1;
$CartID = date("Ymd")."-".str_pad($OrderID, 4, "0", STR_PAD_LEFT);
//echo $CartID ." ";
$CartDate = date("Y-m-d h:i:s");
$SqlCommand = "SELECT MAX(transid) FROM poscustomershopping";
$Result = mysql_db_query($DBName,$SqlCommand);
$MaxID = mysql_fetch_array($Result);
$TransactionID = $MaxID['0'];
$TransactionID = $TransactionID + 1;
foreach ($arr as $key => $value)
{
$Query = "INSERT INTO poscustomershopping".
" (cartid, transid, productid, priceid, toppingid, cartdate, quantity, saleprice) ".
" VALUES ($CartID, $TransactionID, '".($value["product_id"])."', '".($value["price_id"])."', '".($value["topping_id"])."', NOW(), '".($value["quantity"])."', '".($value["sale_price"])."')";
//echo $Query; die;
mysql_db_query($DBName,$Query);
}
//echo $Data; die;
?>
In Android Debugger everything is fine as shown in imageDebugger Screenshot but when I tried to decode_json file received via parameter I can't be able to insert data in mySQL although there is no error at all. Please brief me where is the issue and how can identify it for solution purposes.

Related

value br of type java.lang.string cannot be converted to jsonarray

I am trying to register users in the SQL database through Android using java. But before registering, I want to check if the user is already registered or not.
This is my code to check. But is returning error: value br of type java.lang.string cannot be converted to jsonarray. The response from server is not in the form of JsonArray.
Please help me to solve it.
registerActivity.java
StringRequest stringRequest = new StringRequest(Request.Method.POST, IsUserExist, new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
//Toast.makeText(getApplicationContext(), "Number Already Registered", Toast.LENGTH_SHORT).show();
if (jsonObject.getString("status").equals("true")) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Number Already Registered", Toast.LENGTH_SHORT).show();
} else {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "HELLO", Toast.LENGTH_SHORT).show();
register(mobilenumber);
// PhoneAuthProvider.getInstance().verifyPhoneNumber(
// mobilenumber,
// 120,
// java.util.concurrent.TimeUnit.SECONDS,
// getActivity(),
// mCallbacks);
}
}
} catch (JSONException e) {
e.printStackTrace();
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error Please tyr again" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
params.put("mobile", mobilenumber);
return params;
}
};
Volley.newRequestQueue(RegisterActivity.this).add(stringRequest);
isUserExists.php
$mobile = mysqli_real_escape_string($con, $_POST["mobile"]);
$query= "SELECT * from users WHERE mobile =$mobile";
$rows = mysqli_query($con,$query);
if(mysqli_num_rows($rows) < 0){
$response[] = array(
"status" => "true",
"message" => "User already exists"
);
return response($response);
}else{
$response[] = array(
"status" => "false",
"message" => "User donot exists");
return response($response);
}

i am facing this Problem E/catch ===: org.json.JSONException: No value for SorrySignUpFirst

I am Building a Project with PHP, MYSQL, java Volley Library
Problem is that it doesn't work all 3 at the same time getting this error
E/catch ===: org.json.JSONException: No value for SorrySignUpFirst
SorrySignUpFirst,
SorrySignUpFirst,
LoginPasswordWrong
If I comment 2 then run my Emulator its works so how to solve this Problem
PHP CODES
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
require_once("connection.php");
$data_array = array();
$login_email = $_POST['email'];
$login_email = strip_tags($login_email);
$login_email = str_replace(' ', '', $login_email); // remove spaces
$login_password = $_POST['password'];
$login_password = strip_tags($login_password);
$email = str_replace(' ', '', $login_password); // remove spaces
$db_email = mysqli_query($connection, "SELECT * FROM users WHERE email ='$login_email'");
if (mysqli_num_rows($db_email) == 0)
{
$data_array['SorrySignUpFirst'] = "1";
echo json_encode($data_array);
mysqli_close($connection);
}
else
{
$data = mysqli_fetch_array($db_email);
if (password_verify($login_password, $data['password']))
{
$data_array['LoginSuccessfull'] = "1";
$data_array['id'] = $data['id'];
$data_array['email'] = $data['email'];
echo json_encode($data_array);
mysqli_close($connection);
}
else
{
$data_array['LoginPasswordWrong'] = "1";
echo json_encode($data_array);
mysqli_close($connection);
}
}
}
?>
LoginActivity.java codes
final StringRequest LoginstringRequest = new StringRequest(Request.Method.POST, URLS.LOGIN_API, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String SorrySignUpFirst = jsonObject.getString("SorrySignUpFirst");
String LoginSuccessfull = jsonObject.getString("LoginSuccessfull");
String LoginPasswordWrong = jsonObject.getString("LoginPasswordWrong");
if (SorrySignUpFirst.contains("1")) {
Intent goToHomeScreenIntent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(goToHomeScreenIntent);
Toast.makeText(LoginActivity.this, "User Doen't Exist Sign Up", Toast.LENGTH_LONG).show();
}
if (LoginSuccessfull.contains("1")) {
String id = jsonObject.getString("id");
String fname = jsonObject.getString("email");
Intent goToHomeScreenIntent = new Intent(LoginActivity.this, HomeScreenActivity.class);
startActivity(goToHomeScreenIntent);
Toast.makeText(LoginActivity.this, "id = " + id + "email == " + fname, Toast.LENGTH_LONG).show();
}
if (LoginPasswordWrong.contains("1")) {
Toast.makeText(LoginActivity.this, "Password Wrong", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(LoginActivity.this, "if else if Error", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(LoginActivity.this, "catch -- " + e.toString(), Toast.LENGTH_LONG).show();
Log.e("catch === ", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error= 116" + error.toString(), Toast.LENGTH_LONG ).show();
Log.i("Catch error 116 ====", error.toString());
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> loginParams = new HashMap<>();
loginParams.put("email", Email);
loginParams.put("password", Password);
return loginParams;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(LoginstringRequest);
It seems to me that there is no attribute called SorrySignUpFirst on your jsonObject.
Try placing a breakpoint on this line:
String SorrySignUpFirst = jsonObject.getString("SorrySignUpFirst");
Inspect the jsonObject and check to see whether or not SorrySignUpFirst exists on it.

How to fix this Problem org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONObject

i am using Volley library php mysql to build login system and i am facing this problem
Registration Error= 156 org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONObject
and when i check my database user details inserted successfully
i already tried these ways
<?php
$result = array();
$allValues = array();
$values = array();
if (mysqli_query($connection, $sql)) {
$values['status'] = 'true';
$values['message'] = 'successful';
} else {
$values['status'] = 'false';
$values['message'] = 'failed';
}
$allValues[] = $values;
$result['result'] = $allValues;
echo json_encode($result);
?>
change my java codes
JSONArray jsonArray =response.getJSONArray("result");
for(int i = 0 ; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i("jsonsingleImage",jsonObject.toString());
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
JSONObject jo = new JSONObject(success.substring(1, success.length()-1));
new JSONObject(success.substring(success.indexOf("{"), success.lastIndexOf("}") + 1));
My Registration.php Codes
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
require_once("connection.php");
$first_name = $_POST['firstName'];
$first_name = strip_tags($first_name);
$first_name = ucfirst(strtolower($first_name)); // uppercase first letter
$first_name = str_replace(' ', '', $first_name); // remove spaces
$last_name = $_POST['lastName'];
$last_name = strip_tags($last_name);
$last_name = ucfirst(strtolower($last_name)); // uppercase first letter
$last_name = str_replace(' ', '', $last_name); // remove spaces
$email = $_POST['email'];
$email = strip_tags($email);
$email = str_replace(' ', '', $email); // remove spaces
$password = $_POST['password'];
$password = mysqli_real_escape_string($password);
$password = strip_tags($password);
$password = str_replace(' ', '', $password); // remove spaces
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$sql = "INSERT INTO users (firstName, lastName, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')";
if (mysqli_query($connection, $sql)) {
$result['success'] = "True";
$result['message'] = "Successfully";
echo json_encode($result);
mysqli_close($connection);
} else {
$result['success'] = "False";
$result['message'] = "Failed";
echo json_encode($result);
mysqli_close($connection);
}
}
?>
SignActivity.java Codes
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLS.SIGNUP_API, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("True")) {
Toast.makeText(SignupActivity.this, "Registration successfully", Toast.LENGTH_LONG).show();
Log.i("Registration ======= ", "Registration successfully");
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SignupActivity.this, "Registration Error= 156 " + e.toString(), Toast.LENGTH_LONG).show();
Log.i("Catch error 156 ======", e.toString());
}
}
},
'''
Refer Following Code
Here is Connection php file
<?php
$conn = mysqli_connect("localhost", "root", "", "rfid") or die('connection error');
?>
Here is Login php file
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$parent_user = $_POST['username'];
$parent_pass = $_POST['password'];
include('connect.php');
$sql = "SELECT * FROM parent WHERE parent_user='$parent_user' AND
parent_pass='$parent_pass' ";
$response = mysqli_query($conn, $sql);
if (mysqli_num_rows($response)==1) {
while($row=mysqli_fetch_assoc($response)){
$result["id"] = $row['parent_id'];
}
$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);
}
}
?>
Here is Login class
private void LogMeIn() {
final String Username = Utxt.getText().toString().trim();
final String Password = Ptxt.getText().toString().trim();
StringRequest SR = new StringRequest(Request.Method.POST, url, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
Log.d("test", "onResponse: "+jsonObject.toString(4));
String success=jsonObject.getString("success");
Log.d("test", "onResponse: "+success);
if (success.equals("1")){
String Id =jsonObject.getString("id");
session.createLoginSession(""+Id);
Intent intent=new Intent(LoginActivity.this,MainActivity.class);
intent.putExtra("Id",Id);
startActivity(intent);
Toast.makeText(LoginActivity.this, "******Welcome*******",
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(LoginActivity.this, "Invalid Username OR
Password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Register
unsuccessful"+e.toString(), 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() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", Username);
params.put("password", Password);
return params;
}
};
RequestQueue RQ = Volley.newRequestQueue(LoginActivity.this);
RQ.add(SR);
}

using volley to post username and password to php, parsing the returned json array into shared preferences

I'm trying to send the username and password to the server, with the server returning a json array of the users information. I am then trying to store the information passed into shared preferences. Here is my attempt. I tried to Toast out the information at the bottem of the code, but the String values are coming up as null.
private void jsonParse() {
String url = "http://178.128.166.68/getUserInfo.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("profileData");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject profileData = jsonArray.getJSONObject(i);
id = profileData.getString("id");
fNameGet = profileData.getString("fName");
lNameGet = profileData.getString("lName");
phoneGet = profileData.getString("phone");
joinedDateGet = profileData.getString("joined");
noOfTripsGet = profileData.getString("noOfTrips");
}
SharedPreferences settings = getSharedPreferences("myData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("phone", phoneGet);
editor.putString("fName", fNameGet);
editor.putString("lName", lNameGet);
editor.putString("joined", joinedDateGet);
editor.putString("Trips", noOfTripsGet);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_name", username);
params.put("password", password);
return params;
}
};
mQueue.add(request);
Toast.makeText(this, id + fNameGet + lNameGet, Toast.LENGTH_LONG).show();
}
}
PHP code
$username = $_POST["user_name"];
$pass = $_POST["password"];
$qry = "select * from user where phone like '$username' and pass = '$pass';";
$result = mysqli_query($conn, $qry) or die (mysqli_error($conn));
$rows=array();
while($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
echo json_encode(array('profileData' =>$rows));
mysqli_close($conn);
?>
As i am quite inexperienced with this any criticism or help is greatly appreciated.

Unable to update MySQL with PHP

I'm making an android app using MySQL and PHP for registration, and my MySQL database is not updating. I am getting to the php methods, but am not successfully updating the table. Here is the important snippet of java code:
public void updateGroupName() {
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText groupName = (EditText) dialog.findViewById(R.id.group);
final String name = groupName.getText().toString();
System.out.println("Name of group is: " + name);
updateUser(name);
System.out.println("Trying to update user group");
if (!name.isEmpty()) {
//add to sqlite database
updateUser(name);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
String tag_string_req = "req_update";
//showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Update Response: " + response.toString());
//hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
System.out.println("User group successfully updated in mysql");
// User successfully stored in MySQL
} else {
System.out.println("The use group failed to update");
// 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, "Update Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
// hideDialog();
}
}) {
String email = db.getUserDetails().get("email");
#Override
protected Map<String, String> getParams() {
System.out.println("trying to return params");
// Posting params to register url
Map<String, String> params = new HashMap<>();
params.put("tag", "update");
params.put("user_group", name);
params.put("email", email);
return params;
}
};
System.out.println("updating group to mysql database");
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
// System.out.println("here1");
// System.out.println("user group: " + db.getUserDetails().get("user_group"));
dialog.dismiss();
}
});
//System.out.println("here2");
}
Here are the important portions of my PHP code:
else if ($tag == "update") {
$user_group = $_POST['user_group'];
$uid = $_POST['email'];
//update user
$user = $db->updateUser($user_group, $email);
if ($user) {
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["user_group"] = ["user"]["user_group"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo "The update User function was called and a user was returned";
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Error occured in Updating user group";
echo json_encode($response);
}
public function updateUser($user_group, $email) {
$result = mysql_query("UPDATE users SET user_group = '$user_group' WHERE email = '$email'");
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;
}
}
You are passing $email to your method updateUser but the email address is stored in $uid.
Please change
$user = $db->updateUser($user_group, $email);
to
$user = $db->updateUser($user_group, $uid);

Categories