Android app and Database Communication: JSON Parsing and List View - java

I am developing an app that communicates with Database, to retrieve values. I am using PHP for the Backend, and developing on Android Studio, using the Volley Library.
My problem is, the values that I need to send are multiple records of a table, each with four columns, for example name, age, department, and country. I am using JSON to encode these values, but I need help with how to proceed. Should I use JSON encoded 2D Arrays? if so, how to make use PHP to construct this array, as there can be variable numbers of rows.
Also, How to parse that JSON Object/Array in Android (Java)?
As of now, this is my progress:
JSON Output in browser:
{"name0":"ABC","age0":"25","department0":"Medical","country0":"XYZ","name1":"DEF","age1":"26","department1":"Engg.","country1":"XYZ"}
Here, I named each "key" of JSON using a Loop in PHP, and encoded as JSON Object. But Having Difficulty in displaying this in Android. I have used a XML layout with 4 textviews, and LISTVIEW in the main Activity XML File.

I would suggest a different json structure for encoding. Yours will get messy pretty quick if there are a lot of records. For example you would have name0, name1, ... nameN. It would be better to make an array like so:
[
{
"name" : "ABC",
"age" : 25,
"department" : "Medical",
"country" : "XYZ"
},
{
...
}
]
Notice that there are no indices concatenated to your keys. You can get the index based on the json object node's position in the array if you need it.
As for parsing it in Android, you can refer to the documentation. There is a Json parser that comes with the SDK so all you need to do is read in your string as a json array and iterate over its object nodes as needed.
For example
String jsonResponse = " ... "; // whatever the php backend gives you when you make a call to the endpoint
JSONArray arr = new JSONArray(jsonResponse);
for (int i=0; i<arr.length(); i++) {
JSONObject obj = arr.get(i);
String name = obj.getString("name");
...
}

Related

Convert DynamoJson to something compatible with the Dynamo client

I've got a big dump of DynamoJson e.g.
{"Item": {"id":{"N":"896"}, "name": {"S": "Tom"}}}
I want to parse this JSON and put it to my DynamoDB table...
I've tried:
import com.amazonaws.services.dynamodbv2.document.Item;
Item item = Item.fromJSON(BLOB);
But unfortunately its not smart enough to parse the DynamoDB Json format and doesn't deal with the inner types (S, N etc)... When I try to put I get errors like:
Type mismatch for key id expected: N actual: M
Related Questions:
AWS DynamoDB on Android: Inserting JSON Directly?
This does not work for the DynamoJson format.
Unmarshall DynamoDB JSON
This is exactly what I need but its in NodeJS

How to convert Map created from JSON to another Map in Java?

I got JSON file like this:
{
"issues": [
{
"no1": 5509,
"date": 1451520000
},
{
"no1": 6713,
"date": 1451433600
}],
"no2": [
220380,
163950,
213330,
215250,
174300]
}
I need to create a map issues where the no1 value will be key of the map and date value will be a value of the map. I've got already method which transfers JSON to map from file, and I know how to get the issues which will be: mapFromJson.get("issues"); what I get is:
issues=[{ no1: 5509.0, date: 1.45152E9}, {no1: 6713.0, date: 1.4514336E9}]
How to convert this to map?
You can convert to JSON using JSON Library (you must to attach JAR file in your project). Also, I found a good answer for convert JSON to Map in this link. I recommended to use these functions.
Example:
JSONObject json = new JSONObject(<your_json_string>);
ArrayList issues = (ArrayList) jsonToMap(json).get("issues");
Each element in the ArrayList issues, it's already HashMap. For example, if you want to get date of no1, you could access of this way:
((HashMap)issues.get(0)).get("date")

How to make a JsonObject in a ordered way?

I want to create a JSonObject with some values for call a webservice but where webservice in a order like:
{
"id" : 1
"email" : "test#test.com",
"pin" : 1234,
"age" : 25,
"firstName" : "Test First Name",
"lastName" : "Test Last Name",
"location" : "India",
"phone" : "1234567890"
}
but when I create a json object from android code it is not maintaining the order like:
requestJOB=new JSONObject();
requestJOB.put("userid",Pref.getValue(this, Const.USER_ID, requestJOB.optString("userid")));
requestJOB.put("email", Pref.getValue(this, Const.PREF_EMAIL, requestJOB.optString("email")));
requestJOB.put("pin", Pref.getValue(this, Const.PREF_PIN, requestJOB.optString("pin")));
requestJOB.put("age", Pref.getValue(this, Const.PREF_AGE, requestJOB.optString("age")));
requestJOB.put("firstname", etFirstName.getText().toString().trim());
requestJOB.put("lastname", etLastName.getText().toString().trim());
requestJOB.put("phone", etPhone.getText().toString().trim());
requestJOB.put("location", etLocation.getText().toString().trim());
I write the code my desired order but JsonObject change the order in run time. I also tried with map and LinkedList but A exception is
occured when I want to convert LIST to JsonObject.
I searched in stackoverflow where no satisfactory answer.
In this situation I don't understand exactly what I have to do.
In Android platform there is better way to serialize a object in json by using Google GSON API... Which provide all possible functionality to convert a class to their corresponding JSON. U can prepare nested jsonobject ..
Nested like json object with in a json object. Json array embedded within a json. Object
Multiple jsonarray with in a same json object. And their may be multiple variety .. Just explore this jar .. It's very easy to use and user-friendly jar. Just go and grab it .. Hopefully u feel better with this API
I used this jar in my Android project actually

Parsing json array with multiple arrays in it from php -> java

I'm having trouble parsing a json response. Its created via php and sent back to my phone via http as json.
It is an array with 3 arrays in it so...
$arr = array();
Then I search my mysql database for specific IDs relating to the query, usually about 3 results are returned with unique ids as the array index.. like this
$sql = mysql_query("Select from so and so");
while($row = mysql_fetch_assoc($sql)){
$arr[$row["ID"]] = $row;
}
print(json_encode($arr));
so now in my android (java) code I'm trying to convert the response to a json object and then parse it with
json_object.getString("FirstName")
for all 3 of the first names returned but its crashing. So i am guess I need to parse out the 3 individual arrays first which is where I am stuck.
-The question is how do I sort out the arrays returned within this one object. Each of them have the same keys, but different values
-crashing wasnt a good choice in terms, what I should have said is it cant find the value I am searching for when I use the getString method, here is the return
Agree with the comments above, would need more details.
But if you're getting back a properly formatted JSON response and it's an Array, you could always do something like ...
JSONArray results = new JSONArray(<json response string>);
for (int i=0; i<results.length(); i++) {
JSONObject obj = results.getJSONObject(i);
}
And documentation for your reference:
http://developer.android.com/reference/org/json/JSONArray.html

What is the proper format for a JSON Response?

I've worked with several different APIs where I needed to parse JSON. And in all cases the Response is constructed a bit differently.
I now need to expose some data via a JSON API and want to know the proper way to deliver that Response.
Here is an example of what I have now, however some users (one using Java) are having difficulty parsing.
{"status": "200 OK",
"code": "\/api\/status\/ok",
"result": {
"publishers": ["Asmodee", "HOBBITY.eu", "Kaissa Chess & Games"],
"playing_time": 30, "description": "2010 Spiel des Jahres WinnerOne player is the storyteller for the turn. He looks at the 6 images in his hand. From one of these, he makes up a sentence and says it out loud (without showing the card to the other players).The other players select amongst their 6 images the one that best matches the sentence made up by the storyteller.Then, each of them gives their selected card to the storyteller, without showing it to the others. The storyteller shuffles his card with all the received cards. ",
"expansions": ["Dixit 2", "Dixit 2: \"Gift\" Promo Card", "Dixit 2: The American Promo Card", "Dixit Odyssey"],
"age": 8,
"min_players": 3,
"mid": "\/m\/0cn_gq3",
"max_players": null,
"designers": ["Jean-Louis Roubira"],
"year_published": 2008,
"name": "Dixit"
}
}
The Java user in particular is complaining that they get the error:
org.json.JSONException:[json string] of type org.json.JSONObject cannot be converted to JSONArray
But in Python I am able to take in this Response, fetch "result" and then parse as I would any other JSON data.
* UPDATE *
I passed both my JSON and Twitter's timeline JSON to JSONLint. Both are valid. The Java user can parse Twitter's JSON but not mine. What I noticed with Twitter's JSON is that it's encapsulated with brackets [], signifying an array. And the error this user is getting with my JSON is that it cannot be converted to a JSON array. I didn't think I need to encapsulate in brackets.
It looks valid according to http://json.parser.online.fr/ (random json parser). Its in the other code i'd say ;)
How exactly are you generating this response? Are you doing it yourself?
I see you have a dangling comma at the end of the last element in publishers (i.e. after the value Kaissa Chess & Games).
I'd recommend using JSONLint to ensure your JSON is valid.

Categories