I'm trying to get data from json. I can get data at first state.
But how to get data "ascending" and "descending" and show it on another activity in listview ?
Here's My Json
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
And here's my Java code
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String table_name = c.getString(TAG_TABLE_NAME);
String item_list = c.getString(TAG_ITEM_LIST);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CATEGORY_NAME, category_name);
contact.put(TAG_TABLE_NAME, table_name);
contact.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodlistfilter.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm trying to follow this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, but i still don't fully understand.
Let me explain this.
[ means its an array.
{ is an object.
In your case it's an array whcih contains an -JSONObject with name category_name, filter_type and field_name. type and table_name and a new jsonarray with object item_list.
How can you parse this string?
Here is an example:
String str = "[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}";
JSONArray jsonArray = new JSONArray(str);
//now it holds the JSONObject.
for (int i = 0; i<= jsonArray.length(); i++) {
//now we loop through and get the jsonObject
JSONObject jsonObj = new JSONObject(jsonArray.getJsonObject(i));
//now it contains your data.
Log.d("Category_nameValue=", jsonObj.getString("category_name"));
//now we want to get the array from the item_list.
JSONArray itemList = new JSONArray(jsonObj.getString("item_list"));
//now itemList.getString(1); === Ascending while itemList.getString(2) == Descending
//now itemList contains several new objects which can also be looped as the parent one.
}
Since you now know how to create an JSONArray, you can start sorting it.
This has been answered already at Android how to sort JSONArray of JSONObjects
If you want to send those data to another Activity you can use the JSONArray.toString() method and send it via Intents.
This is easy explained at Pass a String from one Activity to another Activity in Android
Hope this helps.
If you're new, I would recommend you think about using Gson to parse your Json response directly to a java entity class. So you will avoid to manually parse all your responses.
Your JSON response
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
The entity representing the response
public class MyEntity {
String category_name;
String filter_type;
String field_name;
String type;
String table_name;
String [] item_list;
// getters / setters ...
}
Parsing the response
Gson gson = new Gson();
MyEntity myEntity = gson.fromJson(response, MyEntity.class);
Finally, to send the data, start the new Activity with extras
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("EXTRA_DATA", myEntity.getCategoryName());
startActivity(intent);
Now you recover the extra data on your AnotherActivity
Intent intent = getIntent();
String categoryName = intent.getStringExtra("EXTRA_DATA");
And you can fill the ListView using an ArrayAdapter: Example
To get a JSONArray from your JSONObject c
simply write:
JSONArray itemList = c.getJSONArray(name);
then you can iterate through that data like any other array
for (int i = 0; i < itemList.length(); i++) {
// do something
}
Related
#Override
protected void onPostExecute(String response) {
String firstName = null;
String lastName = null;
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonArray = jsonResponse.getJSONArray("");
JSONObject userInfo = jsonArray.getJSONObject(0);
firstName = userInfo.getString("id");
lastName = userInfo.getString("id");
}
catch (JSONException e){
e.printStackTrace();
}
I have this JSON file https://api.myjson.com/bins/1a5t7w
How i can acces to thats values, i used this code but it doesn`t work?
It returns #null#
You are getting a JSON array in the response.
To parse this array you need to pass the response to JSONArray object like below
try {
JSONArray rspArr = new JSONArray(response);
for(int i= 0; i< rspArr.length(); i++){
JSONObject jsonObject = (JSONObject) rspArr.get(i);
//Your logic
}
}catch (Exception e ){
//log exception
}
// since you know is an array, create a JSONArray based on your response String
JSONArray array = JSONArray(response)
// obtain the first element of your array as a JSONObject
JSONObject jsonObject = array.getJSONObject(0)
// once you get the jsonObject you can start getting the values you need
String id = jsonObject.getString("id")
Hope it helps!
Answer by Arunangshu seems correct, you need to extract the JSONArray first because the API is returning JSONArray(array of JSON objects) and not one big JSON object.
One can use http://jsonviewer.stack.hu/ for viewing JSON. It gives better understanding of the JSON structure.
For Java, one can use http://www.jsonschema2pojo.org/ for converting JSON object(not array) to Java Pojo class (select the options carefully).
Following is the first object from json array -
{"id":48191,"title":"Apple Crumble Recipe","image":"https://spoonacular.com/recipeImages/48191-312x231.jpg","imageType":"jpg","usedIngredientCount":1,"missedIngredientCount":2,"missedIngredients":[{"id":4073,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Milk, Eggs, Other Dairy","name":"margarine","original":"35 g margarine or butter","originalString":"35 g margarine or butter","originalName":"margarine or butter","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/butter-sliced.jpg"},{"id":8120,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Cereal","name":"rolled oats","original":"35 g rolled oats","originalString":"35 g rolled oats","originalName":"rolled oats","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/rolled-oats.jpg"}],"usedIngredients":[{"id":9003,"amount":400.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Produce","name":"apples","original":"400 g cooking apples peeled cored and quartered","originalString":"400 g cooking apples peeled cored and quartered","originalName":"cooking apples peeled cored and quartered","metaInformation":["cored","peeled","quartered"],"meta":["cored","peeled","quartered"],"image":"https://spoonacular.com/cdn/ingredients_100x100/apple.jpg"}],"unusedIngredients":[],"likes":965}
I am trying to add Objects from MySQL database on ArrayList Object but result gives me only one row
i am using custom adapter on my ListView, i think i could use loop multiple objects to ArrayList object but i failed , please help me,
my code :
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Looks like you are creating an ArrayList everytime you parse an object. If I understand correctly, your code should be something like that:
// ArrayList will be created only once for a json response.
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
//Now parse add all elements in json response and add to list.
for(all items in your jsonResponse List ) {
//Parse fields from json object
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
//create object
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
//Now list will have all the items, Add this list to adapter.
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<>(getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Suppose Your Server gives a result in JSONArray say response as a String Try the following
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
JSONArray jsonArray = new JSONArray(response);
int size = jsonArray.length();
if (size > 0)
{
for (int i = 0; i < size; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
You must use JSONArray for getting list of items from JSON. And then populate your ArrayList with them and pass to your adapter.
I wanna display a parsed json with my values . I mean , I wanna add some values to the json and display it . I can display all result from respond , but I wanna display just the json with my values not all data :)
here i have parsed allready my json
JSONObject jsonObject = new JSONObject(adresUrl);
JSONArray offerResources = jsonObject.getJSONArray("offerResources");
for(int y = 0; y < offerResources.length(); y++){
JSONObject currentTransfer = offerResources.getJSONObject(y);
JSONArray meetPoint = currentTransfer.getJSONArray("meetPoints");
for (int i = 0; i < meetPoint.length(); i++){
JSONObject currentMeetPoints = meetPoint.getJSONObject(i);
String startAddress = currentMeetPoints.getString("startAddress"); // here i wanna put some values , but i dont know how
// here is a litle piece of my json :)
"meetPoints": [
{
"startAddress": "....", // after the collon i have to put my value .
"startLocation": {
thank you for your help
I'm not sure if I understood your question fully but from what I got here is some solution. I simply created a string and couple of Json objects and jsonarray for adding the list of values and put it inside the main json object "jsonValueObject " and accumulate it inside meetPoints.
Accumulate(String key,Object Value) is a key value pair, meaning if key is created then Object is checked for being an array,and if this array has "values", it will be added else new array will be created. "Put" will replace the value if the key exists.
String jsonString = "{\"results\":[{\"Country\":\"value\",\"state\":\"value\" },
{ \"Country\":\"value\", \"state\":\"value\"}]}";
JSONObject meetPoints = new JSONObject(jsonDataString);
JSONObject jsonValueObject = new JSONObject();
JSONArray list = new JSONArray();
jsonValueObject.put("Country", "newValue");
jsonValueObject.put("state", "newValue");
jsonValueObject.put("city", "Chennai");
jsonValueObject.put("street", "Bharathiyar Street");
jsonValueObject.put("date", "14May2017");
jsonValueObject.put("time", "10:00AM");
list.put(jsonValueObject);
meetPoints.accumulate("values", list);
System.out.println(meetPoints);
I need to parse following nested JSON data and assign it to Spinners in my Android Activity. What would be the best way to parse this JSON data. So that i can show values inside spinners and on submitting the data ID of that particular selected value should passed.
{
"root":[
{
"genderList":[
{
"gender_id":"1",
"gender_name":"Male"
},
{
"gender_id":"2",
"gender_name":"Female"
}
]
},
{
"SocialCategory":[
{
"SOCIAL_CATEGORY_ID":"1",
"SOCIAL_CATEGORY_NAME":"General"
},
{
"SOCIAL_CATEGORY_ID":"2",
"SOCIAL_CATEGORY_NAME":"SC"
},
{
"SOCIAL_CATEGORY_ID":"3",
"SOCIAL_CATEGORY_NAME":"ST"
},
{
"SOCIAL_CATEGORY_ID":"4",
"SOCIAL_CATEGORY_NAME":"OBC"
}
]
}
]
}
The best way is to have custom classes that represent the data you want to show. Then you need to parse the JSON objects and create the instances and add them to arrays or lists. And then you need to create two adapters (one for each type of data) - the best way is to extend the BaseAdapter as a more flexible approach. After assigning the adapters to the spinners you can get the whole object from the selected position. In the same time you show only what is needed - the adapter defines the view.
This code is not tested, but you will get the idea of how to parse JSON in Android.
JSONObject responseJson = new JSONObject(response);
JSONArray rootArray = responseJson.getJSONArray("root");
JSONObject genderListWrapperJson = rootArray.getJSONObject(0);
JSONArray genderListJsonArray = genderListWrapperJson.getJSONArray("genderList");
for (int i = 0; i < genderListJsonArray.length(); i++) {
JSONObject genderJson = genderListJsonArray.getJSONObject(i);
String genderId = genderJson.getString("gender_id");
String genderName = genderJson.getString("gender_name");
// TODO: instantiate an object of custom type gender
}
JSONObject socialCategoryWrapperJson = rootArray.getJSONObject(1);
JSONArray socialCategoryJsonArray = socialCategoryWrapperJson.getJSONArray("SocialCategory");
for (int i = 0; i < socialCategoryJsonArray.length(); i++) {
JSONObject socialCategoryJson = socialCategoryJsonArray.getJSONObject(i);
String categoryId = socialCategoryJson.getString("SOCIAL_CATEGORY_ID");
String categoryName = socialCategoryJson.getString("SOCIAL_CATEGORY_NAME");
// TODO: instantiate an object of custom social category
}
"response" is the JSON text you have.
I have a JSON string like this of data for a table in an android app. one of {} is a row of data for the table. I want to separate these {}s into an array and then each element inside this array into other sub-arrays separating other elements inside {}. Please suggest an appropriate way of accomplishing this criteria using JSON. Thank you.
[
{
"nodeName":"prime_mtsc22#smpp3",
"nodeId":"MTSC3",
"tidPrefix":"4",
"optStatus":"offline",
"daStart":"1",
"daEnd":"3",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp2",
"nodeId":"MTSC58",
"tidPrefix":"1",
"optStatus":"blocked",
"daStart":"5",
"daEnd":"10",
"description":"new description"
},
{
"nodeName":"prime_mtsc22#smpp1",
"nodeId":"MTSC1",
"tidPrefix":"15",
"optStatus":"online",
"daStart":"12",
"daEnd":"20",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp0",
"nodeId":"MTSC15",
"tidPrefix":"15",
"optStatus":"offline",
"daStart":"25",
"daEnd":"30",
"description":"Description"
}
]
ok so in that case the code to use is this
String jsonString = <your jsonString>;
// THIS IS NOT NEEDED ANYMORE
//JSONObject json = new JSONObject(jsonString);
JSONArray topArray = null;
try {
// Getting your top array
// THIS IS NOT NEEDED ANYMORE
//topArray = json.getJSONArray(jsonString);
//use this instead
topArray = new JSONArray(jsonString);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
ok?
Use JSONObject for this http://developer.android.com/reference/org/json/JSONObject.html
Example
String jsonString = <your jsonString>;
JSONObject json = new JSONObject(jsonString);
JSONObject topArray = ;
try {
// Getting your top array
topArray = json.getJSONArray(TAG_ARRAY_TOP);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use the NodePOJO class to hold each row values.
public class NodePOJO {
private String nodeName;
// do for rest of the json row data
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeName() {
return this.nodeName;
}
}