getJSONObject with an Array - java

i am trying to work with android and php json , i try to get something like this , how it is shown in an example.
the example json respone is: { "android": [ { "ver": "1.5", "name": "Cupcake", "api": "API level 3" }, { "ver": "1.6", "name": "Donut", "api": "API level 4" }]}
and my json respone is:
[{"post_id":"3","user_id":"1","post_inhalt":"lolli","likes":"1"},{"post_id":"4","user_id":"1","post_inhalt":"lala","likes":"2"}]
ther is my problem, i want one object with an array;
my php code looks like this.
<?php
$con=mysqli_connect("localhost","root","","my_db");
//echo "Welcome, I am connecting Android to PHP, MySQL";
if (mysqli_connect_errno($con))
{
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = "1";
//Für die Überprüfung
$result = mysqli_query($con, "SELECT * FROM post where user_id='$user_id'");
$response = array();
// fetch data in array format
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
//$response["code"] = 1;
// Fetch data of Fname Column and store in array of row_array
/*
$row_array["post"]['post_id'] = $row['post_id'];
$row_array["post"]['user_id'] = $row['user_id'];
$row_array["post"]['post_inhalt'] = $row['post_inhalt'];
$row_array["post"]['likes'] = $row['likes'];
*/
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
//push the values in the array
array_push($response,$row_array);
}
print json_encode($response);
mysqli_close($con);
?>
i want to put this in my android list view, but everytime i run my app , the error :
'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
because of that i think the data cant be found from my android. i am not the best in android, so maybe some one can help me.
here is my update of my php code:
//while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
//$response["code"] = 1;
// Fetch data of Fname Column and store in array of row_array
/*
$row_array["post"]['post_id'] = $row['post_id'];
$row_array["post"]['user_id'] = $row['user_id'];
$row_array["post"]['post_inhalt'] = $row['post_inhalt'];
$row_array["post"]['likes'] = $row['likes'];
*/
//$row_array = array();
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
//Funktioniert auch, gib aber nur ein array zurück
//$response[] = $row;
$response["post"] = array();
//push the values in the array
array_push($response["post"],$row_array);
}
print json_encode($response);

Add the row array to your resporse like this:
$respone["android"][$i] = $row_array;
ofcouse $i is the place in the array
Something like this:
$response["android"] = array();
$i = 0;
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row_array['post_id'] = $row['post_id'];
$row_array['user_id'] = $row['user_id'];
$row_array['post_inhalt'] = $row['post_inhalt'];
$row_array['likes'] = $row['likes'];
$response["android"][$i] = $row_array;
}

Related

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/

passing special characters from mysqli database to android app using php

I have a mysqli table on a server with the configuration displayed below. The text data contains some special characters. I'm passing this to my android app using the following php file. The issue is that all the special characters are displayed as question marks in the app. I'm not sure if I need to specify that we're passing unicode characters in the php file and if so how to do that. It's not a font issue, as any special characters hardcoded into the app display as expected.
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connectmaths.php';
// connecting to db
$con = new DB_CONNECT();
$con->connect();
// get all gamelists from gamelists table
$result = mysqli_query($con->myconn, "SELECT * FROM `abcd`" ) or die(mysql_error());
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// gamelists node
$response["gamelist"] = array();
while ($row = mysqli_fetch_array($result)) {
// temp user array
$gamelist = array();
$gamelist["id"] = $row["id"];
$gamelist["zadanie"] = $row["zadanie"];
$gamelist["odp_a"] = $row["odp_a"];
$gamelist["odp_b"] = $row["odp_b"];
$gamelist["odp_c"] = $row["odp_c"];
$gamelist["odp_d"] = $row["odp_d"];
$gamelist["comment"] = $row["comment"];
$gamelist["correctanswer"] = $row["correctanswer"];
// push single gamelist into final response array
array_push($response["gamelist"], $gamelist);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no gamelists found
$response["success"] = 0;
$response["message"] = "No gamelists found";
// echo no users JSON
echo json_encode($response);
}
?>
What's Charset yours Datas ? When my Datas have e.g. charset cp1250 i have to transfer Strings to utf8. Change PHP script
...
while ($row = mysqli_fetch_array($result)) {
// temp user array
$gamelist = array();
$gamelist["id"] = $row["id"];
//$gamelist["zadanie"] = $row["zadanie"];
$gamelist["zadanie"] = iconv("CP1250", "UTF-8", $row["zadanie"]);
$gamelist["odp_a"] = $row["odp_a"];
$gamelist["odp_b"] = $row["odp_b"];
$gamelist["odp_c"] = $row["odp_c"];
$gamelist["odp_d"] = $row["odp_d"];
$gamelist["comment"] = $row["comment"];
$gamelist["correctanswer"] = $row["correctanswer"];
// push single gamelist into final response array
array_push($response["gamelist"], $gamelist);
}
...
The same before i save Datas from App to Mysql i have to transfer
...
$zadanie = iconv("UTF-8", "CP1250", $_POST['zadanie']);
...

Array always starts at one, empty zero

I'm trying to read my MySQL data and put it as JSON. But I just want a single JSON Object, it tries giving me a JSONArray, but that array is empty.
This is what it gives me, top is JSON, bottom is simple array.
[
[],
{
"id": "1",
"description": null,
"copyright": "© Ian Ransley, flickr.com\/CC BY 2.0"
}
]
Array
(
[0] => Array
(
)
[1] => Array
(
[id] => 1
[description] =>
[copyright] => © Ian Ransley, flickr.com/CC BY 2.0
)
)
As you can see, the zero index is empty for some reason, and right before my object starts there is an opening and closing bracket ([]), which makes my android app recognize that as an array instead of object.
here's my php code:
<?php
header('Content-type: text/plain');
$connection = mysqli_connect("localhost", "bananatime", "Yoyobanana", "bananatime")
or die("Error " . mysqli_error($connection));
if(isset($_GET['id'])){
$sql = "SELECT * FROM bananas WHERE id = '".$_GET['id']."' ORDER BY id";
}else{
$sql = "SELECT * FROM bananas ORDER BY id";
}
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .mysqli_error($connection));
$array[] = array();
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
array_push($array, $row);
}
array_values($array);
echo json_encode($array, JSON_PRETTY_PRINT);
echo "\n\n";
print_r($array);
mysqli_close($connection);
?>
change $array[] = array(); to $array = array();
array_push() was the problem. I had to use $array = $row;

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.

how to encode multiple rows from mysql into json using php

I am trying to encode all the rows of data i get from the DB into JSON and then process it at the client side but i can't seem to get it to work..My code is below
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output['original_title'];
$response['test'] = $output['content'];
return json_encode($response);
//return $output;
}
Then i try to print the var_dump($response) but i get null values.. Although if i var_dump($output) i get all the rows in an array..accessing the array is the problem here now..i think
NB: i am using PDO
The problem is the $output is an array that you need to go through. Like:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response['text'] = $o['original_title'];
$response['test'] = $o['content'];
}
return json_encode($response);
}
}
This is for the last response, but if you want all, do:
function getTopic($conn){
$response = array('error'=>0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
foreach ($output as $o){
$response[] = array('text'=>$o['original_title'],'test'=>$o['content']);
}
return json_encode($response);
}
}
If you are only want one row add a limit to your MySQL statement.
$output is array of results. use a loop or if only one row u need do this:
function getTopic($conn){
$response = array("error" => 0);
$qry = "SELECT original_title, content, time FROM topic WHERE vis = 1";
$result = $conn->prepare($qry);
$result->execute();
if($result->rowCount() > 0){
$output = $result->fetchall();
$response['text'] = $output[0]['original_title'];
$response['test'] = $output[0]['content'];
return json_encode($response);
//return $output;
}

Categories

Resources