JSON Parsing data from 2 dimension array - android

I need to get data from house array, My json file looks like,
{
"mydata": {
"totalRoads": "13",
"noOfHouse": "5",
"house": [
{
"road": "1",
"right": [
{
"houseID": "A3",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A4",
"isPainted": "true",
"ownerGender": "female"
}
],
"left": [
{
"houseID": "A1",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A2",
"isPainted": "false",
"ownerGender": "female"
}
]
},
{
"road": "2",
"right": [
{
"houseID": "B3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "B4",
"isPainted": "true",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "B1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "B2",
"isPainted": "true",
"ownerGender": "male"
}
]
},
{
"road": "3",
"right": [
{
"houseID": "C3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "C4",
"isPainted": "false",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "C1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "C2",
"isPainted": "false",
"ownerGender": "male"
}
]
}
]
}
}
I just tried like this to parse data from json,
InputStream inputStream = getResources().openRawResource(R.raw.house_details);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("House Data", byteArrayOutputStream.toString());
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
house_ID = jArray.getJSONObject(i).getString("houseID");
is_painted = jArray.getJSONObject(i).getBoolean("isPainted");
owner_gender = jArray.getJSONObject(i).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });
}
} catch (Exception e) {
e.printStackTrace();
}
But I couldn't get what I am expecting, Please help me get all data from json.

You can use Gson lib to get the data from Json easy way and your structure will be like this
public class Response{
#SerializedName("mydata")
private Mydata mydata;
public void setMydata(Mydata mydata){
this.mydata = mydata;
}
public Mydata getMydata(){
return mydata;
}
#Override
public String toString(){
return
"Response{" +
"mydata = '" + mydata + '\'' +
"}";
}
}
public class Mydata{
#SerializedName("totalRoads")
private String totalRoads;
#SerializedName("noOfHouse")
private String noOfHouse;
#SerializedName("house")
private List<HouseItem> house;
public void setTotalRoads(String totalRoads){
this.totalRoads = totalRoads;
}
public String getTotalRoads(){
return totalRoads;
}
public void setNoOfHouse(String noOfHouse){
this.noOfHouse = noOfHouse;
}
public String getNoOfHouse(){
return noOfHouse;
}
public void setHouse(List<HouseItem> house){
this.house = house;
}
public List<HouseItem> getHouse(){
return house;
}
#Override
public String toString(){
return
"Mydata{" +
"totalRoads = '" + totalRoads + '\'' +
",noOfHouse = '" + noOfHouse + '\'' +
",house = '" + house + '\'' +
"}";
}
}
public class HouseItem{
#SerializedName("road")
private String road;
#SerializedName("left")
private List<LeftItem> left;
#SerializedName("right")
private List<RightItem> right;
public void setRoad(String road){
this.road = road;
}
public String getRoad(){
return road;
}
public void setLeft(List<LeftItem> left){
this.left = left;
}
public List<LeftItem> getLeft(){
return left;
}
public void setRight(List<RightItem> right){
this.right = right;
}
public List<RightItem> getRight(){
return right;
}
#Override
public String toString(){
return
"HouseItem{" +
"road = '" + road + '\'' +
",left = '" + left + '\'' +
",right = '" + right + '\'' +
"}";
}
}

Hi your json is not valid one
{
"mydata": {
"totalRoads": "13",
"noOfHouse": "5",
"house": [
{
"road": "1",
"right": [
{
"houseID": "A3",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A4",
"isPainted": "true",
"ownerGender": "female"
}
],
"left": [
{
"houseID": "A1",
"isPainted": "false",
"ownerGender": "female"
},
{
"houseID": "A2",
"isPainted": "false",
"ownerGender": "female"
}
]
},
{
"road": "2",
"right": [
{
"houseID": "B3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "B4",
"isPainted": "true",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "B1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "B2",
"isPainted": "true",
"ownerGender": "male"
}
]
},
{
"road": "3",
"right": [
{
"houseID": "C3",
"isPainted": "false",
"ownerGender": "male"
},
{
"houseID": "C4",
"isPainted": "false",
"ownerGender": "male"
}
],
"left": [
{
"houseID": "C1",
"isPainted": "true",
"ownerGender": "male"
},
{
"houseID": "C2",
"isPainted": "false",
"ownerGender": "male"
}
]
}
]
}
}
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj= jArray.getJSONObject(i);
JSONArray right = obj.getJSONArray("right");
JSONArray left= obj.getJSONArray("left");
for(int j=0;j<right.length();j++)
{
house_ID = right.getJSONObject(j).getString("houseID");
is_painted = right.getJSONObject(j).getBoolean("isPainted");
owner_gender = right.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted),
owner_gender });
}
for(int j=0;j<left.length();j++)
{
house_ID = left.getJSONObject(j).getString("houseID");
is_painted = left.getJSONObject(j).getBoolean("isPainted");
owner_gender = left.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted),
owner_gender });
}
}
} catch (Exception e) {
e.printStackTrace();
}

1- Create a model for houseData i.e.
public class HotelEntity {
private String houseID;
private String isPainted;
private String ownerGender;
// add getter and setter here
}
2- Parse data from right and left from each house object
for (int i = 0; i < jArray.length(); i++) {
//get the data and map it object
Array.getJSONObject(i).getString("right");
for {
// add all models to list
}
Array.getJSONObject(i).getString("left");
for {
// add all models to list
}
}
3 Add it in ArrayList of your houseEntity.
Also, you can use Gson for the json to object conversion.
You don't have to manually parse data from json.

You can create object from your json String with
http://www.jsonschema2pojo.org/
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("mydata")
#Expose
private Mydata mydata;
public Mydata getMydata() {
return mydata;
}
public void setMydata(Mydata mydata) {
this.mydata = mydata;
}
}
-----------------------------------com.example.House.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class House {
#SerializedName("road")
#Expose
private String road;
#SerializedName("right")
#Expose
private List<Right> right = null;
#SerializedName("left")
#Expose
private List<Left> left = null;
public String getRoad() {
return road;
}
public void setRoad(String road) {
this.road = road;
}
public List<Right> getRight() {
return right;
}
public void setRight(List<Right> right) {
this.right = right;
}
public List<Left> getLeft() {
return left;
}
public void setLeft(List<Left> left) {
this.left = left;
}
}
-----------------------------------com.example.Left.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Left {
#SerializedName("houseID")
#Expose
private String houseID;
#SerializedName("isPainted")
#Expose
private String isPainted;
#SerializedName("ownerGender")
#Expose
private String ownerGender;
public String getHouseID() {
return houseID;
}
public void setHouseID(String houseID) {
this.houseID = houseID;
}
public String getIsPainted() {
return isPainted;
}
public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}
public String getOwnerGender() {
return ownerGender;
}
public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}
}
-----------------------------------com.example.Mydata.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Mydata {
#SerializedName("totalRoads")
#Expose
private String totalRoads;
#SerializedName("noOfHouse")
#Expose
private String noOfHouse;
#SerializedName("house")
#Expose
private List<House> house = null;
public String getTotalRoads() {
return totalRoads;
}
public void setTotalRoads(String totalRoads) {
this.totalRoads = totalRoads;
}
public String getNoOfHouse() {
return noOfHouse;
}
public void setNoOfHouse(String noOfHouse) {
this.noOfHouse = noOfHouse;
}
public List<House> getHouse() {
return house;
}
public void setHouse(List<House> house) {
this.house = house;
}
}
-----------------------------------com.example.Right.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Right {
#SerializedName("houseID")
#Expose
private String houseID;
#SerializedName("isPainted")
#Expose
private String isPainted;
#SerializedName("ownerGender")
#Expose
private String ownerGender;
public String getHouseID() {
return houseID;
}
public void setHouseID(String houseID) {
this.houseID = houseID;
}
public String getIsPainted() {
return isPainted;
}
public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}
public String getOwnerGender() {
return ownerGender;
}
public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}
}
And you can get everything with:
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
Gson g = new Gson();
Example example = g.fromJson(jObject .toString(), Example.class);
You can get value from Example.
Mydata mydata = example.getMyData();
List<House> lstHouse = mydata.getHouse();
for (i= 0; i < lstHouse.size(); i++){
House house = lstHouse.get(i);
String road = house.getRoad();
List<Right> lstRight = house.getRight();
for (j= 0; j < lstRight .size(); j++){
Right right = lstRight.get(j);
String houseID = right.getHouseID();
String isPainted = right.getIsPainted();
String ownerGender = right.getOwnerGender();
}
List<Left> lstLeft = house.getLeft();
for (k= 0; k < lstLeft .size(); k++){
Left left= lstLeft .get(k);
String houseID = left.getHouseID();
String isPainted = left.getIsPainted();
String ownerGender = left.getOwnerGender();
}
}
I hope it can help your problem!

You're trying to access data from house to houseId, but you have to go through right and left structures previously.

houseID is inside the right array not in house array.
Try this :
JSONObject jObject = new JSONObject(byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray jArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObj = jArray.getJSONObject(i);
JSONArray jsonArray = jsonObj.getJSONArray("right");
for (int j = 0; j < jsonArray.length(); j++)
{
house_ID = jsonArray.getJSONObject(j).getString("houseID");
is_painted = jsonArray.getJSONObject(j).getBoolean("isPainted");
owner_gender = jsonArray.getJSONObject(j).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });
}
}

Here is a solution which is very close to your implementation, however, correct, and will also read the "left" array :)
InputStream inputStream = getResources().openRawResource(R.raw.sojson);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("House Data", byteArrayOutputStream.toString());
try {
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("mydata");
JSONArray houseArray = jObjectResult.getJSONArray("house");
String house_ID = "";
boolean is_painted = false;
String owner_gender = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < houseArray.length(); i++) {
JSONObject ob = houseArray.getJSONObject(i);
JSONArray rightArray = ob.getJSONArray("right");
for (int r = 0; r < rightArray.length(); r++) {
house_ID = rightArray.getJSONObject(r).getString("houseID");
is_painted = rightArray.getJSONObject(r).getBoolean("isPainted");
owner_gender = rightArray.getJSONObject(r).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
}
JSONArray leftArray = ob.getJSONArray("left");
for (int l = 0; l < leftArray.length(); l++) {
house_ID = leftArray.getJSONObject(l).getString("houseID");
is_painted = leftArray.getJSONObject(l).getBoolean("isPainted");
owner_gender = leftArray.getJSONObject(l).getString("ownerGender");
Log.v("house_ID", house_ID);
Log.v("is_painted", String.valueOf(is_painted));
Log.v("owner_gender", owner_gender);
data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
}
}
} catch (Exception e) {
e.printStackTrace();
}
Be sure to use valid JSON:
{
"mydata":{
"totalRoads":"13",
"noOfHouse":"5",
"house":[
{
"road":"1",
"right":[
{
"houseID":"A3",
"isPainted":"false",
"ownerGender":"female"
},
{
"houseID":"A4",
"isPainted":"true",
"ownerGender":"female"
}
],
"left":[
{
"houseID":"A1",
"isPainted":"false",
"ownerGender":"female"
},
{
"houseID":"A2",
"isPainted":"false",
"ownerGender":"female"
}
]
},
{
"road":"2",
"right":[
{
"houseID":"B3",
"isPainted":"false",
"ownerGender":"male"
},
{
"houseID":"B4",
"isPainted":"true",
"ownerGender":"male"
}
],
"left":[
{
"houseID":"B1",
"isPainted":"true",
"ownerGender":"male"
},
{
"houseID":"B2",
"isPainted":"true",
"ownerGender":"male"
}
]
},
{
"road":"3",
"right":[
{
"houseID":"C3",
"isPainted":"false",
"ownerGender":"male"
},
{
"houseID":"C4",
"isPainted":"false",
"ownerGender":"male"
}
],
"left":[
{
"houseID":"C1",
"isPainted":"true",
"ownerGender":"male"
},
{
"houseID":"C2",
"isPainted":"false",
"ownerGender":"male"
}
]
}
]
}
}

house_ID = jArray.getJSONObject(i).getString("houseID"); // WRONG WAY
I guess JSONException will occur.
You should create two FOR loop.
for (int i = 0; i < jArray.length(); i++)
{
JSONObject _jOBJ = jArray.getJSONObject(i);
JSONArray jsonArray = _jOBJ.getJSONArray("right");
for (int j = 0; j < jsonArray.length(); j++)
{
JSONObject _jOBJCHILD = jsonArray.getJSONObject(j);
String str_HOUSEID = _jOBJCHILD.getString("houseID");
}
}

Related

Grouping jsonObjects in an jsonArray Android

I have a jsonArray with a bunch of jsonObjects that I'd like to group via the market_id such that objects with similar market_id's are held separately in their own list or array. How can i achieve this?
[
{
"product_id": "12301",
"selection": "No",
"sales": "31",
"market_id": "10",
},
{
"product_id": "12302",
"selection": "No",
"sales": "24",
"market_id": "43",
},
{
"product_id": "12303",
"selection": "Yes",
"sales": "121",
"market_id": "10",
},
{
"product_id": "12304",
"selection": "No",
"sales": "0",
"market_id": "43",
},
{
"product_id": "12305",
"selection": "Yes",
"sales": "20",
"market_id": "43",
},
]
In order to achieve something like this:
[{
"product_id": "12304",
"selection": "No",
"sales": "0",
"market_id": "43",
},
{
"product_id": "12305",
"selection": "Yes",
"sales": "20",
"market_id": "43",
},
{
"product_id": "12302",
"selection": "No",
"sales": "24",
"market_id": "43",
},]
First create a Product model class that implements Comparator interface so allows you to sort ProductList, in this case by marketId.
Product.java
public class Product implements Comparator<Product> {
public String productId;
public String selection;
public String sales;
public String marketId;
public Product() {
super();
}
#Override
public int compare(final Product p1, final Product p2) {
if (!TextUtils.isEmpty(p1.marketId) && !TextUtils.isEmpty(p2.marketId)) {
return p1.marketId.compareTo(p2.marketId); //Ascending order
}
return 0;
}
}
Second, create a Product parser class that parses your product list JSONArray to Product type list and from Product type list to grouped Product JSONArray.
ProductParser.java
public class ProductParser {
private static final String TAG = ProductParser.class.getSimpleName();
private static final String PRODUCT_ID = "product_id";
private static final String SELECTION = "selection";
private static final String SALES = "sales";
private static final String MARKET_ID = "market_id";
private static final String HELPER_ID = "-1";
public ProductParser() {
super();
}
public List<Product> parseProductArrayToProductList(final JSONArray productArray) {
final List<Product> productsList = new ArrayList<>();
if (null != productArray) {
try {
final int productCount = productArray.length();
for (int i = 0; i < productCount; ++i) {
final JSONObject productJson = productArray.getJSONObject(i);
final Product product = new Product();
product.productId = productJson.getString(PRODUCT_ID);
product.selection = productJson.getString(SELECTION);
product.sales = productJson.getString(SALES);
product.marketId = productJson.getString(MARKET_ID);
productsList.add(product);
}
} catch (final JSONException e) {
Log.e(TAG, e.toString());
}
}
return productsList;
}
public JSONArray parseProductListToGroupedProductArray(final List<Product> productList) {
final JSONArray groupedProductArray = new JSONArray();
if (null != productList && !productList.isEmpty()) {
final int productCount = productList.size();
String currentMarketId = HELPER_ID;
JSONArray productArray = null;
for (int i = 0; i < productCount; ++i) {
final Product product = productList.get(i);
if (null != product) {
if (!currentMarketId.equals(product.marketId)) {
currentMarketId = product.marketId;
if (null != productArray) {
groupedProductArray.put(productArray);
}
productArray = new JSONArray();
}
try {
final JSONObject productObject = new JSONObject();
productObject.put(PRODUCT_ID, product.productId);
productObject.put(SELECTION, product.selection);
productObject.put(SALES, product.sales);
productObject.put(MARKET_ID, product.marketId);
productArray.put(productObject);
} catch (final JSONException e) {
Log.e(TAG, e.toString());
}
}
}
if (null != productArray) {
groupedProductArray.put(productArray);
}
}
return groupedProductArray;
}
}
Finally, in your activity or wherever you need to implement this feature, use provided clases.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String data = "\r\n\r\n[\r\n {\r\n \"product_id\": \"12301\",\r\n \"selection\": \"No\",\r\n \"sales\": \"31\",\r\n \"market_id\": \"10\"\r\n },\r\n {\r\n \"product_id\": \"12302\",\r\n \"selection\": \"No\",\r\n \"sales\": \"24\",\r\n \"market_id\": \"43\"\r\n },\r\n {\r\n \"product_id\": \"12303\",\r\n \"selection\": \"Yes\",\r\n \"sales\": \"121\",\r\n \"market_id\": \"10\"\r\n },\r\n {\r\n \"product_id\": \"12304\",\r\n \"selection\": \"No\",\r\n \"sales\": \"0\",\r\n \"market_id\": \"43\"\r\n },\r\n {\r\n \"product_id\": \"12305\",\r\n \"selection\": \"Yes\",\r\n \"sales\": \"20\",\r\n \"market_id\": \"43\"\r\n }\r\n]\r\n\r\n";
final List<Product> productList = getProductList(data);
Collections.sort(productList, new Product());
final JSONArray sortedProductArray = getProductArray(productList);
Log.e(TAG, sortedProductArray.toString()); // Here you have!
}
private List<Product> getProductList(final String data) {
List<Product> productList = new ArrayList<>();
try {
final JSONArray productArray = new JSONArray(data);
final ProductParser parser = new ProductParser();
productList = parser.parseProductArrayToProductList(productArray);
} catch (final JSONException e) {
Log.e(TAG, e.toString());
}
return productList;
}
private JSONArray getProductArray(final List<Product> productList) {
final ProductParser parser = new ProductParser();
return parser.parseProductListToGroupedProductArray(productList);
}
}
I ended up simply looping through every object in the jsonArray and adding objects that share similar market_id's into their own jsonArray. It's not pretty but it works.
try {
JSONArray jsonArray = new JSONArray(mainjson);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String market_id = jsonObject.getString("market_id");
if (market_id.equalsIgnoreCase("43")) {
JSONObject json = new JSONObject();
json.put("match_id", jsonObject.getString("product_id"));
json.put("selection", jsonObject.getString("selection"));
json.put("sales", jsonObject.getString("sales"));
json.put("market_id", jsonObject.getString("market_id"));
new_json.put(json);
} else if (market_id.equalsIgnoreCase("10")) {
....

How to get the id of the sorted item of the spinner?

I am getting data from the json. I have sorted the country name accordingly alphabetically.but when i click on the spinner item i am getting the worng id of the item.can anyone tell me how can i get the id of the sorted item of the spinner.
This is my json:-
{
"Status": 1,
"StatusMessage": "Country and Country Area List",
"data": [
{
"CountryID": "1",
"CountryName": "India",
"CountryArea": [
{
"CountryID": "1",
"AreaID": "1",
"AreaName": "Kuwait City(Capital)"
},
{
"CountryID": "1",
"AreaID": "2",
"AreaName": " Hawally"
},
]
},
{
"CountryID": "2",
"CountryName": "Dubai",
"CountryArea": [
{
"CountryID": "2",
"AreaID": "6",
"AreaName": " Jeddah"
},
{
"CountryID": "2",
"AreaID": "7",
"AreaName": " Riyadh"
This is the method by which i am getting data from the json :-
public void requestDataCountry() {
mProgressDialog.show();
StringRequest countrylistrequest = new StringRequest(Request.Method.GET, GlobalData.COUNTRYLISTURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
mProgressDialog.dismiss();
final JSONObject jObject = new JSONObject(response);
if (jObject.getString("Status").equals("1")) {
JSONArray jsonArray = jObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
mCountryName = jsonObject.getString("CountryName");
mId = jsonObject.getString("CountryID");
mCountryList.add(mCountryName);
Collections.sort(mCountryList);
getCountryId.add(mId);
JSONArray jsonArray1 = jsonObject.getJSONArray("CountryArea");
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
String countryAreaId = jsonObject1.getString("CountryID");
mAreaName = jsonObject1.getString("AreaName");
mAreaList.add(mAreaName);
}
}
countryAdapter.notifyDataSetChanged();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
};
RequestQueue countryqueue = Volley.newRequestQueue(getContext());
countryqueue.add(countrylistrequest);
}
This is my Spinner Code :-
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
this.menu = menu;
MenuItem menuItem = menu.findItem(R.id.menu_spinner).setVisible(true);
mCountrySpinner = (Spinner) MenuItemCompat.getActionView(menuItem);
countryAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, mCountryList);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mCountrySpinner.setAdapter(countryAdapter);
mCountrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mCountrySerachId = getCountryId.get(position);
mEditor.putString(KEY_COUNTRY_ID, mCountrySerachId);
mEditor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
My problem is when i click on the spinner item like i click on Dubai(CountryName)as per my json then i am getting the id 1(CountryID).while i click on the Dubai(CountryName) it should get the id 2(CountryID). i knew the problem i sorted the CountryName but i did not sort the CountryID.then my question is how can i sort the CountryID according to the CountryName.
Save your parsed values(ID and Country name) in a Hashmap. Then sort the hashmap using the code below.
public LinkedHashMap<Integer, String> sortHashMapByValues(
HashMap<Integer, String> passedMap) {
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<String> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<Integer, String> sortedMap =
new LinkedHashMap<>();
Iterator<String> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
String val = valueIt.next();
Iterator<Integer> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Integer key = keyIt.next();
String comp1 = passedMap.get(key);
String comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}

After Getting object/array from json, how can i shuffle it (Randomize)

I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}

Parsing some array from json and some items in it in android

i want to parse userinfo Array and some string in it. and getuserlistdata array and some string in it. please help me how to parse this response.This is my respons.
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test",
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India"
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
},
],
]
}
}
Sir, This my code.
protected Void doInBackground(Void...arg0) {
// Creating service handler class instance
ServiceHandler2 sh = new ServiceHandler2();
String url_links = "http://192.168.0.65/hostandguest/android/viewprofile?uid=77";
Log.d("url_links: ", "> " + url_links);
String jsonStr = sh.makeServiceCall(url_links, ServiceHandler2.GET);
Log.v("Profile:", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
status = obj.getString("status");
data = obj.getString("data");
if (status.equalsIgnoreCase("false")) {
} else {
jsonarr = obj.getJSONArray("userinfo");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject c = jsonarr.getJSONObject(i);
String fname = c.getString("firstname");
Datein_arr.add(fname);
String id = c.getString("id");
}
jsonarr2 = obj.getJSONArray("getuserlistdata");
for (int j = 0; j < jsonarr2.length(); j++) {
JSONObject jo = jsonarr2.getJSONObject(j);
address = jo.getString("address");
Log.v("address", "" + address);
Log.v("Profile:", "777777777777777777777777777777777777");
hostimgrr2 = obj.getJSONArray("hostImage");
if (hostimgrr2.length() == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
det_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/user_12707aaf22_original.jpg");
} else {
for (int k = 0; k < hostimgrr2.length(); k++) {
JSONObject js = hostimgrr2.getJSONObject(k);
img = js.getString("images");
Log.v("img", "" + img);
if (k == 0) {
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
ch_img.add("https://s3-ap-southeast-1.amazonaws.com/nanoweb/hostguesthome/uploadedfile/hostImages/" + img);
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try like below code to parse JSONArray.
try {
private ArrayList<UserInfo> userInfoList = new ArrayList<UserInfo>();
JSONObject jsonObject = new JSONObject(jsonData); // jsonData is your reponse string
JSONArray userinfo = jsonData.getJSONArray("userinfo");
for(int i = 0; i < userinfo.length(); i++) {
JSONObject jObject = userinfo.getJSONObject(i);
UserInfo userInfo = new UserInfo();
userInfo.setId( jObject.getString("id") );
userInfo.setFirstname( jObject.getString("firstname") );
userInfoList.add(userInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
UserInfo class as follow.
public class UserInfo {
public String id = "";
public String firstname = "";
public String getID() {
return coursePrice;
}
public void setID(String id) {
this.id = id;
}
public String getFirstname() {
return coursePrice;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
First you have to validate your jsondata.
You can goto JSONLint to check whether your json is valid or not
{
"status": "true",
"data": {
"userinfo": [
{
"id": "77",
"firstname": "Test"
}
],
"getuserlistdata": [
{
"address": "Kasauli, Himachal Pradesh, India",
"hostImage": [
{
"id": "551",
"hostid": "122",
"images": "user_21t657.jpg",
"description": ""
},
{
"id": "3954",
"hostid": "122",
"images": "user_251541535.jpg",
"description": ""
}
]
}
]
}
}
And You are parsing a JSONObject as String.
ie, it should be obj.getJSONObject("data"); instead of obj.getString("data");
Also check for other parsing issues like this.

Parsing nested arrays in array

I've usually use Retrofit to do all parsing "dirty" work, but recently I've decided to parse json "by the hands". And I can't figure out how to parse nested arrays in array, there is my json:
[
{
"title":"Phone",
"subs":[
{
"id":157291,
"title":"Cell Phone Service"
},
{
"id":524624,
"title":"Landline Phone Service"
},
{
"id":157298,
"title":"Voice Over IP"
}
]
},
{
"title":"TV and Internet",
"subs":[
{
"id":157292,
"title":"Hardwire Internet"
},
{
"id":178472,
"title":"Television"
},
{
"id":524625,
"title":"Wireless Internet"
}
]
},
{
"title":"Entertainment",
"subs":[
{
"id":522695,
"title":"Music and Movies"
}
]
},
{
"title":"Bill Payment",
"subs":[
{
"id":179845,
"title":"Home Utilities"
}
]
},
{
"title":"Games and Social",
"subs":[
{
"id":157297,
"title":"Games",
"subs":[
{
"id":525000,
"title":"Category:Casual"
},
{
"id":525001,
"title":"Category:Online Games"
},
{
"id":525002,
"title":"Category:Action and Shooter Games"
},
{
"id":525003,
"title":"Category:RPG"
},
{
"id":525005,
"title":"Category:Strategy"
},
{
"id":525006,
"title":"Category:Adventure"
},
{
"id":525008,
"title":"Category:Simulators"
},
{
"id":525171,
"title":"Category:Portals and Services"
},
{
"id":525265,
"title":"Category:Game artefacts"
}
]
},
{
"id":524626,
"title":"Social Networks"
},
{
"id":522901,
"title":"Dating"
}
]
},
{
"title":"Finances",
"subs":[
{
"id":522747,
"title":"Loan Repayment"
}
]
},
{
"title":"Everyday Purchases",
"subs":[
{
"id":288993,
"title":"Beauty, Health, and Sports"
}
]
},
{
"title":"Travel",
"subs":[
{
"id":523297,
"title":"Travel Reservations"
},
{
"id":524634,
"title":"Travel Agencies"
}
]
},
{
"title":"Websites",
"subs":[
{
"id":160550,
"title":"Advertising"
},
{
"id":233554,
"title":"Domain Hosting"
}
]
},
{
"title":"And also:",
"subs":[
{
"id":179843,
"title":"Charity"
},
{
"id":524635,
"title":"Online auctions"
},
{
"id":522887,
"title":"Miscellaneous"
}
]
}
]
I've got the second-level nested array, using this piece of code, but how can I get the third-level array?
String response = RequestManager.makeRequest();
StringBuilder sbResponse = new StringBuilder();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
}
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}
And, by the way, how should I store this data in the database - I'm using Realm and I've created Category and SubCategory models, do I need to create another subcategory model for saving data from the third-level array?
Categoty model:
public class Category extends RealmObject {
#PrimaryKey
private String title;
private SubCategory subCategory;
//Getters and setters
}
And SubCategory model:
public class SubCategory extends RealmObject {
#PrimaryKey
private int id;
private String title;
//Getters and setters
}
String response = RequestManager.makeRequest();
StringBuilder sbResponse = new StringBuilder();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
Category c=new Category();
JSONObject jsonObject = jsonArray.getJSONObject(i);
c.setTitle(jsonObject.getString("title"));
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
SubCategory s=new SubCategory();
JSONObject nestedObject= nestedArray.getJSONObject(i);
s.setId(nestedObject.getString("id"));
s.setTitle(nestedObject.getString("title"));
}
c.setSubCategory(s);
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
JSONObject nestObj = nestedArray.getJSONObject(j);
if(nestObj.has("subs"))
{
JSONArray insideArray = nestObj.getJSONArray("subs");
for (int k = 0; k < insideArray .length(); k++) {
}
}
}
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources