retrofit get boolean from mysql - java

I have a problem with retrofit in my android app (java) retrieving a boolean field from php/mysql webservice.
In my java model, I have a boolean field selected, declared as:
#SerializedName("selected")
#Expose
private boolean selected;
In my MySQL database, the field is declared as TINYINT
When I upload my object, it is correctly saved in the database (0 or 1).
But when I want to download the same object, I get an error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected a boolean but was NUMBER at line 11 column 22 path
$[0].selected
php code:
<?php
header('content-type:application/json');
if (isset($_GET['deviceName']) && $_GET['deviceName'] != "") {
$deviceName = $_GET['deviceName'];
$sql = "SELECT * FROM `ComList` WHERE deviceName = '$deviceName' ORDER BY clistId, ord, categOrd ASC;";
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$pdo_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
$bdd = new PDO('mysql:host=localhost;dbname=bdd', 'user', 'password', $pdo_options);
$bdd->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$bdd->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
$response = $bdd->query($sql);
$output = $response->fetchAll(PDO::FETCH_ASSOC);
echo(json_encode($output, JSON_PRETTY_PRINT));
?>
I can't modify the type of the field in the java model.
Any idea please?
Something to modify in the SQL request?
Modify the output in PHP?
The only way I found that give a good result is:
$output = $response->fetchAll(PDO::FETCH_ASSOC);
$tab = array();
foreach($output AS $value) {
$value['selected'] = $value['selected'] ? true : false;
array_push($tab, $value);
}
echo(json_encode($tab, JSON_PRETTY_PRINT));
But I think it's such a dirty process.

Related

Error parsing JSON Object from PHP web service

I seem to be getting an incomplete JSON object from my PHP web service. My PHP codes are as follows:
<?php
define('IEM_PATH', '../admin/com');
require_once('../admin/includes/config.php');
require_once('../admin/com/lib/IEM.class.php');
require_once ('../admin/com/lib/IEM/DBFACTORY.class.php');
require_once ('../admin/com/lib/IEM/baseAPI.class.php');
require_once ('../admin/com/lib/API/USERS.class.php');
require_once ('../admin/com/lib/IEM/baseRecord.class.php');
require_once ('../admin/com/lib/record/Users.class.php');
function GetLists($userid = 0, $getUnconfirmedCount = false) {
$userid = $_REQUEST['userID'];
if (!$userid) {
trigger_error('User object has no user id as parameter.', E_USER_NOTICE);
return false;
}
if (!$userid) {
$userid = $this->userid;
}
require_once('../admin/functions/api/lists.php');
$listapi = new Lists_API();
$returnA = $listapi->GetListByUserID($userid, $getUnconfirmedCount);
$returnResult1 = array();
foreach ($returnA as $key => $value) {
//$lists[] = $key;
$returnResult["contactList"][] = array("listID" => $returnA[$key]['listid'], "name" => $returnA[$key]['name']);
}
$returnResult["success"] = 1;
echo json_encode($returnResult);
}
GetLists();
However when I try to retrieve the results my logcat only shows:
E/JSON Parser: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
W/System.err: org.json.JSONException: No value for success
By doing a logging, my android returns my JSON object as follows
D/Returned JSON: {"androidid":"1"}
from these codes
// getting JSON response from PHP web service
JSONObject returnedJSONObj = listsJSONParser.makeHttpRequest(Constant.URL
+ "RetrieveList.php", "GET", params);
Log.d("Returned JSON ", String.valueOf(returnedJSONObj));
success = returnedJSONObj.getInt("success");
I don't understand why there is no value for success when my PHP does return a JSON Array as well as the success value according to the code, but the android studio java codes does not detect these values in the JSON object. What am I doing wrong here?
you should modify your android code
success = returnedJSONObj.getInt("success");
to
success = returnedJSONObj.getInt("androidid");
The problem is that there is a problem with your php file, so instead of returning a JSON object, it returns a string with the error.
You need to make sure you are sending the correct POST or GET values to the URL if you are or you check for database errors. try logging the inputstream coming from the php server to see the full error it is sending

java.lang.Integer cannot be converted to JSONObject

I am fetching status from PHP in JSON format, but always getting:
org.json.JSONException: Value 43 of type java.lang.Integer cannot be converted to JSONObject
My way of reading result from JSON
int strUserID;
......
strUserID = jsonObject.getInt("UserID");
And in php i am using:
$user_id = mysql_insert_id();
echo $user_id;
if(!$objQuery)
{
$arr['StatusID'] = "0"; // unable to create user
}
else
{
$arr['StatusID'] = "1"; // user created successfully
$arr['UserID'] = $user_id; // passing user id to android app
}
JSON sample on web:
46{"StatusID":"1","UserID":46}
But on Android side not getting data into json format, because facing exception
may i know where i am doing mistake ?
While returning the data from PHP you should encode it in JSON.
use below function
echo json_encode($arr);
In your php file remove
echo $user_id;
and use this after your else condition
echo json_encode($arr);

how get post variable in php?

i am writing a java code that http post with a parameter.that parameter is a long variable that convert to string.
ArrayList<NameValuePair> parameters =new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("MAX_ID", String.valueOf(maxNewsId)));
String result = CustomHttpClient.executeHttpPost(NewsUrl,parameters);
and i want write a php code at the server. that code should get that long number and connect to Data base and select rows that have id greater than that parameter.
i write this code but not working. what should i do?
<?php
$db_host = "localhost";
$db_uid = "**********";
$db_pass = "**********";
$db_name = "**********";
$db_con = mysql_connect($db_host,$db_uid,$db_pass,$db_name) or die('could not connect');
mysql_select_db($db_name);
$maxId = $_POST['MAX_ID'];
mysql_query("set names utf8");
$sql = "SELECT * FROM News where Nid> ".mysql_real_escape_string($maxId);
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close();
?>
A few notes about your code:
First... please don't use mysql_query anymore. Use mysqli_query or PDO. In newer PHP versions mysql_xxx is deprecated and you should use the alternative.
Second... your code is very susceptible to attack. When you use a POST or GET variable you should check if it does not contain harmful code. If your MAX_ID could only be a number i would suggest the following (note the intval-part):
$maxId = 0;
if (isset($_POST['MAX_ID'])) $maxId = intval($_POST['MAX_ID']);
It also checks if MAX_ID is not set (if so your $max_id is 0) and $maxId could only result in a number.
And last... because with above $maxId could only result in a number you don't need the mysql_real_escape_string. So this would be enough:
$sql = "SELECT * FROM News where Nid > ".$maxId;
(please note the warning at the top of the manual of this function about mysql_xxx being deprecated).
if you want greated than: you should change the "<" see in bold
$sql = "SELECT * FROM News WHERE Nid < ".mysql_real_escape_string($maxId);

MySQL insert then update table data

Hey Ive run into a little problem in my SQL/PHP/JAVA application Im hoping you guys can help :)
I have a java application that when run is connected to my website when the java application validates that it is running it talks to my website and my website assigns a session Id to both the java application and the website itself.
cool we good so far?
alright my java application sends data at regular intervals to a page called Dashboard.php what I would like to do is save the data into my Mysql table then when new data is received by Dashboard.php from my java application where the sessionID is the same I would like the table to update to the new data that was just received
here is the php i have so far although it doesnt work.
function update($script_name, $version, $runtime, $status, $ranged, $attack, $defense, $strength, $magic, $sessionID, $username)
{
global $db;
$sql = "SELECT * FROM Dashboard WHERE session_id = '$sessionID'";
try {
$results = $db->query($sql);
if ($results->rowCount() <= 0) {
$query = "INSERT INTO Dashboard (script_name, version, runtime, status, ranged, attack, defense, strength, magic, session_id, username) VALUES ('$script_name', '$version', '$runtime', '$status', '$ranged', '$attack', '$defense', '$strength', '$magic', '$sessionID', $username)";
$db->exec($query);
} else {
foreach ($results as $row) {
$timerunnew = $row['runtime'] + $runtime;
$v4new = $row['ranged'] + $range;
$v5new = $row['attack'] + $attack;
$v6new = $row['defense'] + $defense;
$v7new = $row['strength'] + $strength;
$v8new = $row['magic'] + $magic;
}
$db->exec("UPDATE Dashboard SET `runtime` = $timerunnew, `ranged` = $v4new, `attack` = $v5new, `defense` = $v6new, `strength` = $v7new, `magic` = $v8new WHERE session_id = '$sessionID'");
}
} catch (PDOException $ex) {
echo "fail";
}
}
Ive also tried experimenting with ON DUPLICATE KEY UPDATE value = VALUES(value) however I have had no luck does anyone have a solution? any help would be much appreciated
If this is the only way that records can be inserted into the Dashboard table, then it is impossible for two records to share the same session_id (save for a race hazard occurring between the SELECT and INSERT commands). In which case, you should:
Ensure that there is a UNIQUE key defined on session_id:
ALTER TABLE Dashboard ADD UNIQUE KEY (session_id);
Use INSERT ... ON DUPLICATE KEY UPDATE, ideally with a properly parameterised prepared statement:
$qry = $db->prepare('
INSERT INTO Dashboard (
script_name, version, runtime, status, ranged, attack,
defense, strength, magic, session_id, username
) VALUES (
:script_name, :version, :runtime, :status, :ranged, :attack,
:defense, :strength, :magic, :session_id, :username
) ON DUPLICATE KEY UPDATE
runtime = runtime + VALUES(runtime),
attack = attack + VALUES(status),
defense = defense + VALUES(defense),
strength = strength + VALUES(strength),
magic = magic + VALUES(magic)
');
$qry->execute([
':script_name' => $script_name,
':version' => $version,
':runtime' => $runtime,
':status' => $status,
':ranged' => $ranged,
':attack' => $attack,
':$defense' => $defense,
':strength' => $strength,
':magic' => $magic,
':session_id' => $sessionID,
':username' => $username
]);

Whitespaces in Java/PHP

Spaces not changing to underscored when sent from Java-->PHP-->SQL
Java code:
String urlString = "http://www.mysite.com/auth/verifyuser.php?name="+name.toLowerCase().replace(" ","_");
PHP code:
$name = mysql_real_escape_string($_GET['name']);
$name = str_replace(' ', '_', $name);
$query = "select * from authinfo where name LIKE '$name'";
mysql_query($query);
$num = mysql_affected_rows();
if ($num > 0) {
echo '1';
} else {
echo '0';
}
when I implement a test log on the SQL database, it somehow still seems to show up with spaces instead of underscores(even though I replace it in Java and PHP) and the PHP file returns '0' rather than '1'. I've heard the issue might be whitespaces? It seems to happen to only certain users, mostly mac users.
If your php file is returning a 0, that means your query is not getting executed. Where are you establishing a connection with the database before executing the query?
Remark: where name = '$name'
mysql_affected_rows concerns INSERT, UPDATE and DELETE.
$r = mysql_query($query);
$num = mysql_num_rows($r);
It's unsafe to pass raw name into URL without encoding it.
String urlString = "http://www.example.com/auth/verifyuser.php?name=" + URLEncoder.encode(name.toLowerCase(), "UTF-8");
In PHP you can obtain data:
$name = urldecode($_GET['name']);

Categories

Resources