how to read this json array in java - java

i have a json array generated by this php:
$filtros=mysql_query("SELECT id_transporte FROM user_trans WHERE id_usuario = '".$id_usuario ."'");
for($i=0; $i<=mysql_num_rows($filtros); $i++){
$rs[]= mysql_fetch_array($filtros,MYSQL_ASSOC);
}
foreach($rs as $valor){
if (is_array($valor)) {
foreach($valor as $valor1){
$reportes[]= mysql_query("
SELECT * FROM transportes
WHERE id_transporte='".$valor1."'
ORDER BY fecha_reporte DESC ");
}
}
}
foreach($reportes as $valor){
if($valor != false){
for($i=0; $i<=mysql_num_rows($valor); $i++){
$row[]= mysql_fetch_array($valor,MYSQL_ASSOC);
}
}
}
print_r (json_encode($row));
which returns:
[{"id_report":"73","id_transport":"624","txt_report":"Report0"},
{"id_report":"46","id_transport":"624","txt_report":"Report1"},false,
{"id_report":"74","id_transport":"9999","txt_report":"Report2"},
{"id_report":"52","id_transport":"9999","txt_report":"Report3"},false]
well, i try to read that, but java only read until "false"...
that array are 2 arrays which joined and printed, so i try this:
$row1=str_replace ( "false" , '{"salto":1}' , $row );
$row1[]=false;
print_r (json_encode($row1));
that returns the sames but "" instead "false" and a "false" in the end
but java continues reading until now the ""
i use that for read json
if (jdata!=null && jdata.length() > 0){
JSONObject json_data = null;
try{
System.out.println( jdata.length() );//java there print all the array length ignoring the "false" o ""
for (int i=0; i < jdata.length(); i++){
reportsId[i]=jdata.getJSONObject(i).getString("id_report");
transportId[i]=jdata.getJSONObject(i).getString("id_transport");
txt_report[i]=jdata.getJSONObject(i).getString("txt_report");
System.out.println( " i= "+ i);
}
}
}catch(Exception e3){}
so my question is how read this, or change some lines on php

First of all in your PHP you shouldn't use mysql_* functions as they are deprecated and dangerous. Your code could be vulnerable to SQL Injection. Consider using PDO
You could probably make this much faster by running a single query that would also get rid of the false values. You certainly don't need to stuff everything into an array and then loop over it.
Here's my take:
$resp = mysql_query("SELECT t.* FROM transportes t
JOIN user_trans ut ON t.id_transporte=ut.id_transporte
WHERE ut.id_usuario='$id_usuario'
ORDER BY fecha_reporte DESC");
if(!$resp) {
// handle the error!
die(mysql_error())
}
$output = [];
while( $row = mysql_fetch_assoc($resp) ) {
$output[] = $row;
}
print_r(json_encode($output));
This should solve your problem with false values because they are likely due to the second query not being checked for errors.

The JSON in not well formed.
There's a comma missing after "id_report":"46"

Related

Class still pass the old array in PHP

I have an android program that passes 2 value to mySQL, that is Time in and Time out. I don`t know what happen but I have a scenario that the data passed is incomplete. For example i will create a record and the only need to put is time in after i type the time i will click save so the record is time in has a data and time out is null. After saving, my auto passer sends that data to mySQL. The next thing I will do is to edit that record to add Time Out so both of them has a data. auto passer will run after checking to my database my both of columns has a data. Now this is where the error begins, I have a button call refresh which will retrieve my data from mySQL,create a JSON of that then send it in my android after the process the returned data has no Time Out and when i check it the data in mySQL has no time out also even i add it. I dont know what happened
What I did in my Java is to create a JSONArray the convert it to string the pass it in my php file then my php file decodes it then loop it while saving to database.
This is how i create a json
JSONArray vis_array = new JSONArray();
Cursor unsync_vis = Sync.Unsync_Visit_All();
while (unsync_vis.moveToNext()) {
JSONObject vis_data = new JSONObject();
try {
vis_data.put("t1", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t1"))));
vis_data.put("t2", formatInsert_n(unsync_vis.getString(unsync_vis.getColumnIndex("t2"))));
vis_array.put(vis_data);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Auto Sync Error", e.getMessage());
}
}
public String formatInsert_n(String data) {
if (TextUtils.isEmpty(data) || data.length() == 0) {
data = "null";
} else {
data = data.replace("'", "''");
data = data.replace("null", "");
if (data.toString().matches("")) {
data = "null";
} else {
data = "'" + data + "'";
}
}
return data;
}
after creating that json, i will convert it to string the pass it using stringRequest then in my php i will decode it use for loop the save it in mySQL
Here is the php code
<?php
header('Content-Type: application/json');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$insert_visit_new = isset($_POST['insert_visit_new']) ? $_POST['insert_visit_new'] : "";
if ($insert_visit_new != "") {
$vis_array = json_decode($insert_visit_new, true);
$vis_count = count($vis_array);
for ($i = 0; $i < $vis_count; $i++) {
$vis = $vis_array[$i];
$t1 = $vis['t1'];
$t2 = $vis['t2'];
$ins_sql = "INSERT INTO table t1,t2 VALUES ('$t1','$t2') ON DUPLICATE KEY UPDATE t1 = $t1,t2 = $t2"
$stmt = $DB->prepare($ins_sql);
$stmt->execute();
}
}
echo "done";
?>
by the way the code above is inside an AsyncTask and the class is a BroadcastReceiver
is the cause is i dont unregister my BroadcastReceiver?
or my jsonArray name from this class and inside my refresh button are same?
my question is whats wrong? looks like it still passes the old data. any help is appreciated TYSM

Java/Mysql: Get all resulted lines from a stored procedure and not only the last

I have a stored procedure in mysql that returns more than one lines.
My java code to execute it is:
preparedStmt = conn.prepareCall(queryString);
preparedStmt.setString(1, String.valueOf(patient_id));
//System.out.print("select patient data java file 1 ");
boolean results = preparedStmt.execute();
int rowsAffected = 0;
// Protects against lack of SET NOCOUNT in stored procedure
while (results || rowsAffected != -1) {
if (results) {
rs = preparedStmt.getResultSet();
break;
} else {
rowsAffected = preparedStmt.getUpdateCount();
}
results = preparedStmt.getMoreResults();
}
int i = 0;
obj = new JSONObject();
while (rs.next()) {
JSONArray alist = new JSONArray();
alist.put(rs.getString("patient_id"));
alist.put(rs.getString("allergy"));
alist.put(rs.getString("allergy_description"));
alist.put(rs.getString("allergy_onset_date"));
alist.put(rs.getString("agent_description"));
alist.put(rs.getString("agent"));
alist.put(rs.getString("severity"));
obj.put("ps_allergies", alist);
i++;
}
conn.close();
At the end, ps_allergies json object contains only the last line of the query. This is the print output:
["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]
I want ps_allergies to contain something similar to
[["1","hydrogen peroxide","Nuts","2017-07-04","Nursing profressionals","43","Paramedical practinioners"],["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]...]
Do you know how to fix this?
Not exactly knowing what library you use, but it might have something to do with this line:
obj.put("ps_allergies", alist);
A put method in general associates the specified value with the specified key in a map. Since you are constantly overwriting you key 'ps_allergies' in the loop it will only retain the last value.
You might want to associate a list/array to ps_allergies and you then add every alist object in this list/array.
I found the solution. Instead of put I'm using append method.
obj.append("ps_allergies", alist);
The resulted output now is:
[["1","hydrogen peroxide","Nuts","2017-07-04","Nursing professionals","43","Paramedical practitioners"],["1","chlorhexidine","test123","2017-07-15","mobile contact","test232","pager"],["1","Resistance to unspecified antibiotic","Feb3","2017-03-02","mobile contact","test232","pager"],["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]]

Best way to transfer more values from one server to another via an HTTP call?

I've to transfer data from one machine to another machine connected on a network. May be some 10-20 values to be transfered and that depends. All I do is pack up/ marshal the values in a json and transfer it to another server (say which is another machine connected on a network) via a http post call. Say the data flows from ServerA to ServerB in ServerA I have to pack up all the data to construct the json and in the ServerB I have to unmarshal it which eats up most of my code like the following
String student_id = json.getString("sid");
String student_role_number = json.getString("rnumber");
String student_name = json.getString("name");
String isDayScholar = json.optString("dayscholar", "false");
String stream = json.optString("stream", "");
String class_section = json.getString("section");
It's light when the value is 4-5 when there are more number of values like 20-25 I feel quite heavy in doing this get/set operations.Is there any better way to avoid/minimise this?
It's light when the value is 4-5 when there are more number of values like 20-25, If you could just hardcode all the required keys in some data structure then that might help. For example in your case all the necessary keys are sid,rnumber,name,dayscholar etc.
Keep a separate hardcoded data struct for your keys
org.json.JSONObject jsonObject = new org.json.JSONObject();
java.util.Map<String , Object> otherMap = new java.util.HashMap<>();
String[] myLovedKeys = {"sid" , "rnumber" , "name" , "dayscholar" , "stream" , "section"};
for( int x = 0; x < myLovedKeys.length; x++ )
{
if( myLovedKeys[x].equals("dayscholar") || myLovedKeys[x].equals("stream") )
{
String value = "";
if( myLovedKeys[x].equals("dayscholar") )
{
value = json.optString( myLovedKeys[x] , "false" );
jsonObject.put( myLovedKeys[x] , value );
otherMap.put( myLovedKeys[x] , value );
}
else
{
value = json.optString( myLovedKeys[x] , "" ); // stream key-value
jsonObject.put( myLovedKeys[x] , value );
otherMap.put( myLovedKeys[x] , value );
}
}
else
{
String keyValue = json.getString( myLovedKeys[x] );
jsonObject.put( myLovedKeys[x] , keyValue );
otherMap.put( myLovedKeys[x] , keyValue );
}
}
This will allow you to exactly know which key is currently being processed inside the loop and you can handle diverse behaviors depending on which key you are interested in dealing with
Now the reason why I have declared a JSONObject and a java.util.Map is because I simply want to elaborate the fact that if you are missing org.json.* library, then you can easily get away by using a java.util.Map, but if you have the org.json* library, then you can also deal with problem in a more comfortable manner. Now lets say we wanted to access the data then we could easily try things like
for( int x = 0; x < myLovedKeys.length; x++ )
{
System.out.println( "java.util.Map: [" myLovedKeys[x] + "=" + otherMap.get( myLovedKeys[x] ) );
System.out.println( "org.json.JSONObject: " + myLovedKeys[x] + "=" + jsobObject.getJSONObject( myLovedKeys[x] ) );
}
In a similar fashion, you can modify and update those values
otherMap.put( myLovedKeys[0] , "SomeValue");
otherMap.put( myLovedKeys[1] , "Other Value" );
otherMap.put( "sid" , "SomeValue" );
otherMap.put( "rnumber" , "toSomeName");
//myLovedKeys[0] = "sid" , myLovedKeys[1] = "rnumber"
Similarly you can have the some changes reflected in the jsonObject variable. What you have to realize is that you have to deal with the pain of hardcoding all the key-names somewhere in your code, and yes that is going to take some typing :), Please let me know if that is still not enough to help your case

getJSONObject and subsequent getString returns null

This is a very straightforward question, but this error is very mysterious to me as I have not been able to find a solution or anyone else who has had this problem. I've also used a very similar technique in another activity and it worked just fine. I am making an android application which makes a POST request to a server. The response is a JSONObject that must be parsed into a number and another JSONObject which must also be parsed, and its values assigned to an array of CurrentGame objects. The first call to getJSONObject works fine, but calling getString on that JSONObject returns the following error:
java.lang.NullPointerException: Attempt to write to field 'java.lang.String com.xxxxx.xxxxx.CurrentGame.oppEmail' on a null object reference
Here is my java code:
private void handleResponse(JSONObject response){
int numGroups = 0;
try{
numGroups = response.getInt("Number");
}catch(JSONException e){
e.printStackTrace();
}
Log.i("Number of Groups", String.valueOf(numGroups));
CurrentGame[] currentGames = new CurrentGame[numGroups];
JSONObject current;
int yourTurn = 0;
for(int i = 0; i < numGroups; i++){
try{
current = response.getJSONObject(String.valueOf(i));
Log.i("Current JSONObject: ", String.valueOf(current));
if(current.has("OppEmail")){
currentGames[i].oppEmail = current.getString("OppEmail");
}
if(current.has("OppName")) {
currentGames[i].oppName = current.getString("OppName");
}
if(current.has("Group")) {
currentGames[i].group = current.getString("Group");
}
if(current.has("YourTurn")) {
yourTurn = current.getInt("YourTurn");
}
if(yourTurn == 0){
currentGames[i].yourTurn = true;
}
else{
currentGames[i].yourTurn = false;
}
}
catch (JSONException e){
e.printStackTrace();
}
}
}
Shouldn't the JSONObject.has() check at least be preventing this error?
I know the first getInt() and getJSONObject are working. Heres the Log:
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx D/Response:﹕ {"Number":2,"0":{"Group":"Test Group 1","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0},"1":{"Group":"Test Group 2","OppEmail":"xxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":1}}
06-21 21:58:56.644 20116-20116/com.xxxxxx.xxxxxt I/Number of Groups﹕ 2
06-21 21:58:56.644 20116-20116/com.xxxxx.xxxxx I/Current JSONObject﹕ {"Group":"Test Group 1","OppEmail":"xxxxxx#xxxxx.edu","OppName":"MikeyP","YourTurn":0}
Here's the server code:
$games['Number'] = $numgames;
if($numgames > 0){
$i = 0;
while($row = mysqli_fetch_array($getgames)){
$currGame['Group'] = $row['GroupName'];
// Get the opponent's email and username
if($row['Player1'] != $email){
$opponent = $row['Player1'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
else if($row['Player2'] != $email){
$opponent = $row['Player2'];
$currGame['OppEmail'] = $opponent;
$sql = "SELECT Username FROM users WHERE Email = '".$opponent."'";
$username = mysqli_query($conn, $sql);
$row2 = mysqli_fetch_assoc($username);
$currGame['OppName'] = $row2['Username'];
}
// Determine if it is this player's turn
if($row['CurrentPlayer'] != $email){
$currGame['YourTurn'] = 0;
}
else{
$currGame['YourTurn'] = 1;
}
$games[$i] = $currGame;
$i++;
}
}
//Echo array of groups
header('Content-Type: application/json');
$response = json_encode($games);
echo $response;
Thank you in advance for any ideas as to what I'm doing wrong here. I know similar questions have been asked about getString() returning null, but having read them all I'm still very stumped.
Problem is caused by :
currentGames[i].oppEmail = current.getString("OppEmail");
line.
Because currentGames Array is initialized with size 2 but not added any item of type CurrentGame.
Instead of using currentGames[i].oppEmail create a object of CurrentGame class add all values then add it in currentGames Array like:
CurrentGame objCurrentGame=new CurrentGame();
if(current.has("OppEmail")){
objCurrentGame.oppEmail = current.getString("OppEmail");
}
... same for other fields
...
//Add objCurrentGame to Array
currentGames[i]=objCurrentGame;
Parsing json this way is not robust and error prone, it is recommended to use such libraries as
Gson
Jackson
Retrofit
as these open source libraries offer stable implementation for such purposes and there is no need to reinvent the wheel yourself.
example:
YourPojoClass obj = new Gson().fromJson("{SomeJsonString}", YourPojoClass.class);
In this way, you get the strongly typed pojo instance.You don't even need write the POJO class yourself, and there are many online service that can generate the POJO class out of json strings:
http://www.jsonschema2pojo.org/
http://pojo.sodhanalibrary.com/

Retrieve separate elements from a mySQL array field and iterate to create map

Because I'm using a map interface in Limesurvey, my mySQL database populates a "text" field in my table 'geo' like this:
27.059125784374068;-102.65625;CITY;STATE;COUNTRY;
The code I use in the presentation map looks for specific lat/lon information to iterate through the placemarks:
$encodedString = "";
$x = 0;
$result = mysql_query("SELECT * FROM `geo`");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if ( $x == 0 )
{
$separator = "";
}
else
{
$separator = "****";
}
$encodedString = $encodedString.$separator.
"<p class='content'>
<br><b>Lon:</b> ".$row[0].
"<br><b>Lat:</b> ".$row[1].
"<br><b>SiteName: </b>".$row[2].
"<br><b>Country: </b>".$row[4].
"<br><b>PI: </b>".$row[5].
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
Am I making my life harder by trying to extract the lat/lon values from geoBlob? Is there a way to use the text field as it is?
I'm extracting the lon value like this:
$result = mysql_query("SELECT geoBlob FROM `geo`");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$breakEmUp = explode(";", $v);
$lon = $breakEmUp[0];
$arr[] = $lon;
}
$lonArray = join (", " , $arr);
But I don't know how to put the pieces together.
Getting way over my head here. Uncle! Any help appreciated.
Better you put each your text into differrent field, so make it easier than you must use string separator.

Categories

Resources