Android ArrayList getting clear automatically - android

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

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.

Print data from an ArrayList Object which is inside another ArrayList

The title might seem familiar, but the problem isn't. I've referred many posts/articles, and finally posting my question.
I receive data from JSON similar to this, and from "Home" fragment I save data to a getter setter class "StudentDetails", and then access it from another fragment "StudentFees".
PROBLEM: The last object of the inner array gets printed the number of times the outer array runs.
Below is my "Home" Fragment
public class Home extends Fragment {
private ArrayList<StudentDetails> arrayListHome;
private ArrayList<StudentDetails> arrayListTransaction;
private StudentDetails studentDetails;
private StudentDetails studentDetails1;
JSONArray jsonArrayHome = jsonObjectHome.getJSONArray("responseData");
arrayListHome = new ArrayList<StudentDetails>();
// First array
for (int a = 0; a < jsonArrayHome.length(); a++) {
JSONObject jsonObjectStudent = jsonArrayHome.getJSONObject(a);
studentDetails = new StudentDetails();
// Set student ID
if (!jsonObjectStudent.isNull("student_id")) {
studentDetails.setStudentId(jsonObjectStudent.getString("student_id"));
}
JSONArray jsonArrayTransaction = jsonObjectStudent.getJSONArray("transaction");
arrayListTransaction = new ArrayList<StudentDetails>();
// Second array
for (int j = 0; j < jsonArrayTransaction.length(); j++) {
JSONObject jsonObjectTransaction = jsonArrayTransaction.getJSONObject(j);
studentDetails1 = new StudentDetails();
// Set receipt no.
if (!jsonObjectTransaction.isNull("receipt_no")) {
studentDetails1.setReceiptNo(jsonObjectTransaction.getString("receipt_no"));
}
arrayListTransaction.add(studentDetails1);
Log.d("At Home receipt no.", arrayListTransaction.get(j).getReceiptNo()+"");
}
studentDetails1.setArrayListTransaction(arrayListTransaction);
arrayListHome.add(studentDetails);
Log.d("At Home student id", arrayListHome.get(a).getStudentId());
}
studentDetails.setArray(arrayListHome);
}
Below is "StudentDetails" class
public class StudentDetails {
private static ArrayList<StudentDetails> arrayListDetails = null;
private static ArrayList<StudentDetails> arrayListTransaction = null;
private String studentId = null;
private String receiptNo = null;
public void setArray(ArrayList<StudentDetails> arrayList) {
arrayListDetails = arrayList;
}
public ArrayList<StudentDetails> getArray() {
return arrayListDetails;
}
public void setStudentId(String sId) {
studentId = sId;
}
public String getStudentId() {
return studentId;
}
public void setArrayTransaction(ArrayList<StudentDetails> transaction){
arrayListTransaction = transaction;
}
public ArrayList<StudentDetails> getArrayTransaction (){
return arrayListTransaction;
}
public void setReceiptNo(String sReceiptNo) {
receiptNo = sReceiptNo;
}
public String getReceiptNo() {
return receiptNo;
}
Below is "StudentFees" Fragment
public class StudentFees extends Fragment {
StudentDetails studentDetails = new StudentDetails();
final ArrayList<StudentDetails> arrayListFees = studentDetails.getArray();
// First Array
for (int k = 0; k < arrayListFees.size(); k++) {
final TextView textViewId = new TextView(getActivity());
textViewId.setId(View.generateViewId());
Log.d("At Fees student id", arrayListFees.get(k).getStudentId());
textViewId.setText(arrayListFees.get(k).getStudentId());
StudentDetails studentDetails1 = new StudentDetails();
ArrayList<StudentDetails> arrayListTransaction = studentDetails1.getArrayTransaction();
TextView textViewReceiptNo = null;
// Second Array
for (int l = 0; l < arrayListTransaction.size() /*studentDetails.getArrayTransaction().size()*/; l++) {
// StudentDetails studentDetails1 = new StudentDetails();
// ArrayList<StudentDetails> arrayListTransaction = studentDetails1.getArrayTransaction();
textViewReceiptNo = new TextView(getActivity());
textViewReceiptNo.setId(View.generateViewId());
Log.d("At Fees receipt no.", arrayListTransaction.get(l).getReceiptNo());
textViewReceiptNo.setText(arrayListTransaction.get(l).getReceiptNo());
}
}
}
Data insertion log # Home fragment:
D/At Home receipt no.: R/100/2017/04/2449
D/At Home receipt no.: R/100/2017/04/2450
D/At Home student id: 201510353
D/At Home receipt no.: R/100/2017/04/2536
D/At Home receipt no.: R/100/2017/04/2537
D/At Home receipt no.: R/100/2017/11/3024
D/At Home student id: 201610113
Data retrieval # StudentFees fragment
D/At Fees student id: 201510353
D/At Fees receipt no.: R/100/2017/04/2536
D/At Fees receipt no.: R/100/2017/04/2537
D/At Fees receipt no.: R/100/2017/11/3024
D/At Fees student id: 201610113
D/At Fees receipt no.: R/100/2017/04/2536
D/At Fees receipt no.: R/100/2017/04/2537
D/At Fees receipt no.: R/100/2017/11/3024
Desired output is smilar to data inserted.
NOTE: I've referred this, but still used "static" ArrayList variable on purpose, as I need to access this ArrayList from other fragments.
JSON Data:
{
"responseCode": "200",
"status": "true",
"responseData": [{
"student_id": "201510353",
"transaction": [{
"receipt_no": "R\/100\/2017\/04\/2449"
}, {
"receipt_no": "R\/100\/2017\/04\/2450"
}]
}, {
"student_id": "201610113",
"transaction": [{
"receipt_no": "R\/100\/2017\/04\/2536"
}, {
"receipt_no": "R\/100\/2017\/04\/2537"
}, {
"receipt_no": "R\/100\/2017\/11\/3024"
}]
}]
}

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.

How to properly parse JSON Array in 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

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>

Categories

Resources