How to properly parse JSON Array in Android - android

Im trying to find an easy way to parse JSON data that are in an array. Ive been able to do this before with pure JSON Objects and OkHttp.
What I plan to do is make a simple recycler view that each row will contain the data from the JSON Array.
Note: there will be keys in each array that may or may not have a "viewers" parameter. If it does not exist I plan to make a default value of 0.
JSON example:
{
status_code: 200,
status_text: "OK",
errors: [ ],
data: {
items: [
{
stream: "channel1",
status: 1,
channel: 527,
provider: "akamai"
},
{
stream: "channel2",
status: 2,
channel: 565,
provider: "akamai",
viewers: 3
},
I have a class that stores the data (not sure if needed in the case of a JSON Array) called CurrentStreams.java
package com.example.concurrent;
public class CurrentStreams {
private String mStream;
private int mStatus;
private int mChannel;
private String mProvider;
private int mViewers;
public String getStream() {
return mStream;
}
public void setStream(String stream) {
mStream = stream;
}
public int getStatus() {
return mStatus;
}
public void setStatus(int status) {
mStatus = status;
}
public int getChannel() {
return mChannel;
}
public void setChannel(int channel) {
mChannel = channel;
}
public String getProvider() {
return mProvider;
}
public void setProvider(String provider) {
mProvider = provider;
}
public int getViewers() {
return mViewers;
}
public void setViewers(int viewers) {
mViewers = viewers;
}
}
In my MainActivity I initiate a new OkHttpClient and create the request and pass a method called getCurrentDetails(jsonData) which contains the following
private CurrentStreams getCurrentDetails(String jsonData) throws JSONException {
//New JSON Array
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++){
JSONObject items = jsonArray.getJSONObject(i);
String streamName = items.getString("stream_name");
int status = items.getInt("status");
int channelId = items.getInt("channel_id");
String cdn = items.getString("cdn");
int viewers = items.getInt("viewers");
}
}
I assume im kinda lost at how to properly handle the JSON Array and save the data to then later populate the view with rows of data. Any help is greatly appreciated in advanced.

I would suggest to use gson.
You maybe want to take a look at this answer or this Tutorial

Related

Recyclerview json data binding has failed

I am trying to bind JSON data on to the recyclerView , but data seems not to bind to the RecyclerView.
Surprisingly when i Toast the data i see it's available. What could be the problem?
private void parseJson(String result){
try {
if (result!=null) {
String resultTostring = "" + result;
JSONObject obj = new JSONObject(resultTostring).getJSONObject("ScheduleResource");
JSONArray arr = obj.getJSONArray("Schedule");
itemList = new ArrayList<>();
for (int i = 0; i < arr.length(); i++)
{
String DepartureAirport = arr.getJSONObject(i).getJSONObject("Flight").getJSONObject("Departure").getString("AirportCode");
String ArrivalAirport = arr.getJSONObject(i).getJSONObject("Flight").getJSONObject("Arrival").getString("AirportCode");
String Duration = arr.getJSONObject(i).getJSONObject("TotalJourney").getString("Duration");
String DepartureTime = arr.getJSONObject(i).getJSONObject("Flight").getJSONObject("Departure").getJSONObject("ScheduledTimeLocal").getString("DateTime");
String ArrivalTime = arr.getJSONObject(i).getJSONObject("Flight").getJSONObject("Arrival").getJSONObject("ScheduledTimeLocal").getString("DateTime");
String Stops = arr.getJSONObject(i).getJSONObject("Flight").getJSONObject("Details").getJSONObject("Stops").getString("StopQuantity");
FlightModel model = new FlightModel();
model.setDepartureAirport(DepartureAirport);
model.setArrivalAirport(ArrivalAirport);
model.setDuration(Duration);
model.setDeparturTimee(DepartureTime);
model.setArrivalTime(ArrivalTime);
model.setStops(Stops);
model.Stops= Stops;
itemList.add(model);
Toast.makeText(FlightListActivity.this, "DEPT : " + DepartureAirport + " Arrival " + ArrivalAirport+
" Duration : " + Duration + " Dept time : "+ DepartureTime+" Arr Time "+ ArrivalTime
+" Stops "+ Stops, Toast.LENGTH_LONG).show();
}
// Setup and Handover data to recyclerview
final FlightAdapter adapter = new FlightAdapter(FlightListActivity.this, itemList);
flights_rv.setAdapter(adapter);
flights_rv.setLayoutManager(new LinearLayoutManager(FlightListActivity.this));
}
else{
Toast.makeText(FlightListActivity.this,Config.POOR_NETWORK_CONNECTION, Toast.LENGTH_LONG).show();
}
}
catch (JSONException r){
System.out.println("ERROR PROB : "+ r);
// Toast.makeText(ListOfFlights.this,"ERROR PROB : "+ r,Toast.LENGTH_LONG).show();
}
}
In my Adapter i have attached the Layout which will have the appearance of the data in the List , and also my POJO class is set which has both getters and setters, but when i try to attach the adapter on to the RecyclerView the data doesn't bind why ?
EDIT
My Adapter Class
public class FlightAdapter extends RecyclerView.Adapter<FlightHolder> {
private List<FlightModel> itemList= Collections.emptyList();
private Context context;
public FlightAdapter(Context context,List<FlightModel> itemList) {
this.context = context;
this.itemList = itemList;
}
#Override
public FlightHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_details, parent, false);
FlightHolder rcv = new FlightHolder(layoutView, context);
return rcv;
}
#Override
public void onBindViewHolder(FlightHolder holder, int position) {
final FlightModel sr = itemList.get(position);
final String DepartureAirport = sr.getDepartureAirport();
final String ArrivalAirport = sr.getArrivalAirport();
final String Duration = sr.getDuration();
final String DepartureTime = sr.getDeparturTimee();
final String ArrivalTime = sr.getArrivalTime();
final String Stops = sr.getStops();
final String DirectFlight = sr.getDirectFlights();
holder.from_txt.setText(DepartureAirport);
holder.to_txt.setText(ArrivalAirport);
holder.duration_txt.setText(Duration);
holder.depature_txt.setText(DepartureTime);
holder.arrival_txt.setText(ArrivalTime);
holder.stops_txt.setText(Stops);
holder.dept_txt.setText(DepartureAirport);
holder.arr_txt.setText(ArrivalAirport);
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent i = new Intent(FlightAdapter.this.context, DetailsLocalLeader.class);
// context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
;
return itemList.size();
}
}
For more information , below is the link to the project :
https://github.com/huxaiphaer/FlightsApp/blob/master/app/src/main/java/adapter/FlightAdapter.java
First of all, get someone to review your code structure. Read and understand Java Standard Naming Conventions. Use a design pattern for your app, probably MVP. Use Gson library to parse JSON data for you.
To answer your question, I would say that your JSON structure is flawed. Your code outputs this error
ERROR PROB : org.json.JSONException: Value "SOME_LONG_JSON" at Flight of type org.json.JSONArray cannot be converted to JSONObject
It means that you are trying to parse a JSONArray as a JSONObject. In the Schedule array, there's 9th entry which is supposed to be a JSONObject(as seen in previous 8 entries). But, it is a JSONArray.
So, first 8 entries are like:
{
"Departure": {},
"Arrival": {},
"MarketingCarrier": {},
"Equipment": {},
"Details": {}
}
and, the 9th entry is like :
[
{
"Departure": {},
"Arrival": {},
"MarketingCarrier": {},
"Equipment": {},
"Details": {}
},
{
"Departure": {},
"Arrival": {},
"MarketingCarrier": {},
"Equipment": {},
"Details": {}
}
]
That's why you get this parsing exception in try-catch block. So, you can do this to check if your object is JSONArray or JSONObject like this in parseJson(String result):
Object departureObject = arr.getJSONObject(i).getJSONObject("Flight").get("Departure");
if (departureObject instanceof JSONObject) {
String departureAirport = ((JSONObject) departureObject).getString("Airport");
}
else if (departureObject instanceof JSONArray) {
JSONArray departures = (JSONArray) departureObject;
// use for-loop here to get data from array
}
But, seriously, use POJO with Gson and simplify parsing process. Also, if you have control over how API works, try to keep an object of one type only. If it is supposed to be a list, it better be a list even if there are no items or if there's one or more.
Try these things, it might solve this problem, but I doubt it. You will face more problems with parsing I think. Ping me after you've done this.
Also, if you try to parse all of JSON received by Server, you will see that it is not even complete. Look at the end of your JSON data.
Try something like this for your adapter:
public class FlightAdapter extends RecyclerView.Adapter<FlightAdapter.MyViewHolder> {
private List<FlightModel> mItemList;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
//TODO: Add all your views and the types hear!
Public TextView mTvName;
public MyViewHolder(View v){
super(v);
//TODO: add here for each view in your row
mTvName = (TextView)v.findViewById(R.id.tvName);
}
}
public FlightAdapter(Context context,List<FlightModel> itemList) {
this.context = context;
this.mItemList = itemList;
}
#Override
public FlightHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_details, parent, false);
return new MyViewHolder(layoutView);
}
#Override
public void onBindViewHolder(FlightHolder holder, int position) {
FlightModel model = mItemList.get(position);
//TODO: Add for each view and data point!!
String name = model.getName();
holder.mTvName.setText(name);
holder.layoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent i = new Intent(FlightAdapter.this.context, DetailsLocalLeader.class);
// context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mItemList.size();
}
}
Disclaimer!
I typed this in a text editor, so there might be a few syntax errors or misspellings. Please let me know if you have any issues.

How to retrieve multidimensional array using json and volley

I want to retreive data from json URL and i am face to a problem. I have this from the url :
{
-infos: (2)[
-{
value: "anderson",
-pictures: (2)[
-{
picone: "text_pic",
url: http://www.example.com
},
-{
picone: "text_pic2",
url: http://www.example.com
}
]
},
-{
value: "bryan",
-pictures: (2)[
-{
picone: "text_pic3",
url: http://www.example.com
},
-{
picone: "text_pic4",
url: http://www.example.com
}
]
},....
I have also my listview row :
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/pic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"/>
And here the volley code i used te retrieve data:
....
private List<News_Item> nNews = new ArrayList<>();
......
CustomRequest lnews = new CustomRequest(Request.Method.POST, URL, param, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray vals= response.getJSONArray("infos");
for (int i = 0; i < vals.length(); i++) {
JSONObject dats= vals.getJSONObject(i);
News_Item item = new News_Item ();
item.setmTitle(dats.getString("value"));
JSONArray overinfo = dats.getJSONArray("pictures");
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo .getJSONObject(j);
item.setmImage(links.getString("picone"));
item.setmUrl(links.getString("url"));
}
nNews.add(item);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
....
This code return only one rows (the last row) for pictures array. something like this
row 1 => anderson / text_pic2 / http://www.example.com
row 2 = bryan / text_pic4 / http://www.example.com
So please help
UPDATE
This News_Item.class
class News_Item {
String mTitle;
public News_Item (){
}
List<Picture> pictureList;
public News_Item (String mTitle, <Picture> pictureList){
this.mTitle= mTitle;
this.pictureList= pictureList;
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
class Picture {
String url;
String picone;
public Picture (String url, String picone) {
this.url= url;
this.picone= picone;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPicone() {
return picone;
}
public void setPicone(String picone) {
this.picone = picone;
}
}
}
How get pictures datas.
Like in News_Item you did
News_Item item = new News_Item ();
item.setmTitle(dats.getString("value"));
And at last added to list: nNews.add(item);
you need to add picture items too,
So inside this loop, you are adding in for loop with same object i.e. item so its overwriting those variables
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo.getJSONObject(j);
item.setmImage(links.getString("picone"));
item.setmUrl(links.getString("url"));
-- Here add in collection of links
}
UPDATE: Here this will guide what you will need to do (I wrote directly on stackoverflow editor so might have error)
News_Item item = new News_Item();
item.setmTitle(dats.getString("value"));
List <Picture> pictures = new ArrayList<>();
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo.getJSONObject(j);
Picture picture = new Picture(links.getString("picone"), links.getString("url"));
pictures.add(picture);
}
item.setmPictureList(pictures); // Create this or use constructor itself
nNews.add(item);
Try to change News_Item to have a list of Picture class.
Your code has a problem. You are overwriting new image in every looping.
JSONArray overinfo = dats.getJSONArray("pictures");
for (int j = 0; j < overinfo.length(); j++) {
JSONObject links = overinfo .getJSONObject(j);
item.setmImage(links.getString("picone"));
item.setmUrl(links.getString("url"));
}
By creating new Picture class, you can add Picture object for picone and url value from pictures data.
class News_Item {
List<Picture> pictureList;
...
class Picture {
String url;
String picone;
...
}
}
Google has developed Gson, a library which lets you convert a JSON Strings to a Objects in just one line:
Gson on GitHub
Given that these are your classes:
public class InfoResponse {
List<Info> infos;
public InfoResponse(List<Info> infos) {
this.infos = infos;
}
}
public class Info {
String value;
List<Picture> pictures;
public Info(String value, List<Picture> pictures) {
this.value = value;
this.pictures = pictures;
}
}
public class Picture {
String picone;
String url;
public Picture(String picone, String url) {
this.picone = picone;
this.url = url;
}
}
you just have to call
InfoResponse response = new Gson().fromJson(jsonString, InfoResponse.class);
This will do everything for you.

Getting Nested JsonObjects & Arrays Using Retrofit Library

I got tired using this library, this is my first time using it and made a lot of success ways, but i'm a bit confused in getting the following Json :
{
"Guides":
{
"English": {"ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
,"Arabic": {"EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
}
}
Googled and saw a lot of guides and answered, and made my List like this :
public class PostItem {
List<PostItemArabic> Arabic;
List<PostItemEnglish> English;
}
class PostItemArabic{
private String ArabicSony;
private String ArabicNexus;
private String ArabicSamsung;
private String ArabicHTC;
public String getArabicSony() {
return ArabicSony;
}
public void setArabicSony(String arabicSony) {
ArabicSony = arabicSony;
}
public String getArabicNexus() {
return ArabicNexus;
}
public void setArabicNexus(String arabicNexus) {
ArabicNexus = arabicNexus;
}
public String getArabicSamsung() {
return ArabicSamsung;
}
public void setArabicSamsung(String arabicSamsung) {
ArabicSamsung = arabicSamsung;
}
public String getArabicHTC() {
return ArabicHTC;
}
public void setArabicHTC(String arabicHTC) {
ArabicHTC = arabicHTC;
}
}
class PostItemEnglish{
private String EnglishSony;
private String EnglishNexus;
private String EnglishSamsung;
private String EnglishHTC;
public String getEnglishSony() {
return EnglishSony;
}
public void setEnglishSony(String englishSony) {
EnglishSony = englishSony;
}
public String getEnglishNexus() {
return EnglishNexus;
}
public void setEnglishNexus(String englishNexus) {
EnglishNexus = englishNexus;
}
public String getEnglishSamsung() {
return EnglishSamsung;
}
public void setEnglishSamsung(String englishSamsung) {
EnglishSamsung = englishSamsung;
}
public String getEnglishHTC() {
return EnglishHTC;
}
public void setEnglishHTC(String englishHTC) {
EnglishHTC = englishHTC;
}
}
My Model :
private class Model {
private List<PostItem> Guides;
public List<PostItem> getGuides() {
return Guides;
}
public void setGuides(List<PostItem> roms_center) {
this.Guides = roms_center;
}
}
And printing the result like this :
List<PostItem> Guides = response.body().getGuides();
for(int i = 0 ; i < Guides.size() ; i ++ ) {
for (int b = 0; b < Guides.get(i).English.size() ; b++){
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishHTC());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishNexus());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSamsung());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSony());
}
for (int b = 0; b < Guides.get(i).Arabic.size() ; b++){
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicHTC());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicNexus());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSamsung());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSony());
}
}
My work isn't correct, and getting a lot of errors,
Here's the last error i got :
`Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 3 column 18 path $.Guides
What's the way to make it correct ? `
Based on your models when you try to get the guides list your telling retrofit to populate an array. Retrofit is then getting the data and finding that it is a single object and not array. So you need to update your model to reflect the data returned. For example:
class PostItem {
List<Language> mLanguages;
}
class Language{
String mLanguageTitle; //for example english
List<String> mData; //for this is your list of data
}
Then in your activity instead of getting guides you would get just a post item for example:
response.body().getPostItem();
Hope it helps !
First of all, you can use the retrofit Gson library.
You can handle this in two ways:
Option 1: reformat your languages in your json to be an array like Doug says.
{
"Guides":
[
{"Lang":"English","ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
, {"Lang":"Arabic","EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
]
}
Then you will need to redesign your class to reflect this structure.
Like Doug sayd:
class PostItem {
List<Language> mLanguages;
}
Option 2: Create a custom json desirializer in your class. this will take the Json and break it down into whatever structure you want it to be.
public class PostItem implements JsonDeserializer
#Override
public MyDesirializer deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jarabic = (JsonObject) json.get("Arabic");
//whatever manipulations you want to do (fill with your own code)
PostItem item = new PostItem();
item.arabic = jarabic;
...
...
return item;
}

Parse JSON data into a ListView

I know that there are several similar questions already answered, but because the fact that I'm very new to Android development, I couldn't figure out how to solve this on my own. The question is pretty self-explanatory. I'm fetching data from the database over HTTP request and want to adapt that data into a listview. I'm using Volley for my HTTP requests and underneath is my onResponse -method.
Everything else works perfectly, I just haven't found a way to adapt that data into a listview.
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
// If we are getting success from server
try {
JSONObject jObject = new JSONObject(response);
int count = jObject.getInt("count");
if(count == 0) {
noEventsTextView.setText(jObject.getString("msg").toString());
noEventsTextView.setGravity(Gravity.CENTER);
noEventsImageView.setVisibility(View.VISIBLE);
} else {
JSONArray childArray = jObject.getJSONArray("lectures");
for(int i = 0; i < childArray.length(); i++) {
JSONObject finalObject = childArray.getJSONObject(i);
// TODO Adapt data to listView
}
}
} catch(JSONException e) {
e.printStackTrace();
}
}
}
And here's an example of JSON I get back from the server:
{
count: 2,
msg: "",
lectures: [
{
id: "1",
starting_at: "2015-11-30 13:00:00",
ending_at: "2015-11-30 15:00:00",
user_id: "1",
course: "Course #1",
user_name: "John Doe"
},
{
id: "2",
starting_at: "2015-11-30 13:00:00",
ending_at: "2015-11-30 15:00:00",
user_id: "1",
course: "Course #2",
user_name: "John Doe"
}
]
}
Create a class of each key value pairs of Json and the map your json to that class using Jackson and the add generic list of that class to your List Adapter .
Like
Custom Class{
String id;
String starting_at;
String ending_at;
String user_id;
String course ;
String username;
}
Map your response through Jackson to ArrayList
and then
ListAdapter(ArrayList)
https://w2davids.wordpress.com/android-json-parsing-made-easy-using-jackson/
and you are ready to go.......you can use gson also but jackson is a bit faster so you can go for anyone according to ur need......
hope it helps.
create array Variables for each key value pairs of Json.
and pass all those variable to a listview.
new Listadapter(this,id[],starting_at[],ending_at[],user_id[],course[],username[]);
or There is a concept called Gson.
which will allow you to write data to Serializable class without using array.
And after assigning data to these class you can pass the Serializable class to adapter and used it inside adapter getView method.
There is a simple tutorial on this which I wrote to assign data to serializable class, think it will give you an idea.
hope it helps.
You can have a POJO consisting of all the keys a lecture has.
DataPOJO.java
public class DataPOJO {
private int id;
private String starting_at;
private String ending_at;
private String user_id;
private String course;
private String user_name;
}
Inside your onResponse:
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
// If we are getting success from server
try {
JSONObject jObject = new JSONObject(response);
int count = jObject.getInt("count");
if(count == 0) {
noEventsTextView.setText(jObject.getString("msg").toString());
noEventsTextView.setGravity(Gravity.CENTER);
noEventsImageView.setVisibility(View.VISIBLE);
} else {
JSONArray childArray = jObject.getJSONArray("lectures");
ArrayList<DataPOJO> datas = new ArrayList<DataPOJO>();
for(int i = 0; i < childArray.length(); i++) {
JSONObject finalObject = childArray.getJSONObject(i);
DataPOJO data = new DataPOJO;
data.id = finalObject.getInt("id");
data.starting_at = finalObject.getString("starting_at");
//so on
//add data to arraylist......
datas.add(data);
}
//set adapter of your listview here, you have to have an instance of your list view
listView.setAdapter(new MyAdapter(datas, context));
}
} catch(JSONException e) {
e.printStackTrace();
}
}
}
MyAdapter.java
public class MyAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<DataPOJO> listItem;
public MyAdapter(Context mContext, ArrayList<DataPOJO> listItem) {
this.mContext = mContext;
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return listItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_items, null);
((TextView) convertView.findViewById(R.id.name)).setText(listItem.get(position).user_name);
return convertView;
}
}
list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#000"
android:textSize="18sp"/>
</RelativeLayout>

Android ArrayList getting clear automatically

This is kind of weird issue i am having,
I am getting response from web service in this manner
"course": [
{
"id": 1,
"cou_name": "Engineering",
"L1": [
{
"id": 3,
"cou_name": "B.Tech",
},
{
"id": 4,
"cou_name": "M.Tech",
}]
},
{ ...... } ]
I have created POJO class to handle this response in this way
public class FilterCourseDetail {
public static final String ID = "id";
public static final String COU_NAME = "cou_name";
public static final String LEVEL_ONE = "L1";
public int id;
public String courseName;
public ArrayList<FilterCourseDetail> mLevelOneArrayList = new ArrayList<>();
public FilterCourseDetail(JSONObject object) {
setId(object.optInt(ID));
setCourseName(object.optString(COU_NAME));
try {
JSONArray jsonLevelOneArray = object.optJSONArray(LEVEL_ONE);
if(jsonLevelOneArray != null){
for (int i = 0; i < jsonLevelOneArray.length(); i++) {
mLevelOneArrayList.add(new FilterCourseDetail(jsonLevelOneArray.getJSONObject(i)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Normal getter setter
public ArrayList<FilterCourseDetail> getLevelOneArray() {
return this.mLevelOneArrayList;
}
}
And i am storing it in following manner
private ArrayList<FilterCourseDetail> mFilterCourseList = new ArrayList<>();
JSONArray jsonSearchFilterArray = jsonSearchFilterObject.getJSONArray("course");
for (int i = 0; i < jsonSearchFilterArray.length(); i++) {
mFilterCourseList.add(new FilterCourseDetail(jsonSearchFilterArray.getJSONObject(i)));
}
Retrieving it :
private ArrayList<FilterCourseDetail> mFilterLevelOneArray = new ArrayList<>();
mFilterLevelOneArray = mFilterCourseList.get(position).getLevelOneArray();
Problem :
When i check the size of mFilterCourseList for first time, it's fine,
but using it again by
mFilterLevelOneArray = mFilterCourseList.get(position).getLevelOneArray();
and checking the size, it returns 0, means it's automatically been cleared.
I don't understand this. also is this the proper way to handle Inner JSONArray ? please help me out when i am wrong

Categories

Resources