How to Loop to show all cuisine data (New American, Japanese, Asia). In RestaurantRVAdapter, I used like this -
List<Restaurant> restaurant; // There is a data in restaurant holder.tv_cuisine.setText(restaurant.getCuisine().get(0).getCuisineName());
It only shows New American because I use .get(0).getCuisineName()
[
{...},
{...},
{...},
{...},
{
"restaurant_id": "41",
"restaurant_logo": "52ee9f67ce39f62d9c0b1538ca26646f.jpg",
"restaurant_name": "Shwe Lar Food Restaurant",
"street_address": "Napier Road",
"phone_no": "09940255323430",
"rating": "4.5",
"cuisine": [
{
"cuisine_name": "New American"
},
{
"cuisine_name": "Japanese"
},
{
"cuisine_name": "Asia"
}
],
}
]
In your RecyclerView Adapter update your code like this.
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Restaurant rest = restaurant.get(position);
holder.tv_cuisine.setText(rest.getCuisineName());
}
First you get jsonArray then used fori lool to get all json object then you can get exat data, like as
JSONArray jsonArray = obj.getJSONArray("cuisine");
List<JSONObject> postList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPost = jsonArray.getJSONObject(i);
postList.add(jsonPost);
}
mAdapter.updateList(postList, mStockstype);
in Adapter you make a method like
public void updateList(List<JSONObject> list, String type) {
mDataList.clear();
mDataList.addAll(list);
notifyDataSetChanged();
}
Then in adapter you get you data
JSONObject object = mDataList.get(position);
String name = object.optString("cuisine_name");
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Restaurant rest = restaurant.get(position); // get the specific restaurent
List<Cuisine> cuisineList = rest.getCuisine(); // list to carry cuisineList
String cuisineString = ""; //string to carrying cuisines
for(int i=0; i<cuisineList.size(); i++) {
cuisineString.concat(cuisineList.get(i));
cuisineString.concat(",");
}
holder.tv_cuisine.setText(strCuisine);
}
Build comma separated text for Cuisines,
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Restaurant rest = restaurant.get(position);
List<Cuisine> cuisineList = rest.getCuisine();
// Build comma separated text for Cuisines
String strCuisine = "";
for(i=0; i<cuisineList.size(); i++) {
strCuisine.concat(cuisineList.get(i).getCuisineName());
strCuisine.concat(",");
}
holder.tv_cuisine.setText(strCuisine);
}
It should like this,
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Restaurant rest = restaurant.get(position); // get the specific restaurent
List<Cuisine> cuisineList = rest.getCuisine(); // list to carry cuisineList
String cuisineString = ""; //string to carrying cuisines
for(int i=0; i<cuisineList.size(); i++) {
cuisineString.concat(cuisineList.get(i).getCuisineName());
cuisineString.concat(",");
}
cuisineString = cuisineString.substring(0, cuisineString.length() - 1);// Removes last ,
holder.tv_cuisine.setText(cuisineString);
}
Related
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.
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"
}]
}]
}
My question is when i select the state from the autocompletetextview it always return 1 as an id. but i want to get the id accordingly to the state as per shown my json. Example (StateName = Assam then StateId = 4).but i am always getting id as 1. i am using model class to set the id and get from it.but there is no change i am getting the id as a 1. If anyone know how can i resolve this problem.then please tell me. thanks in advance.
This is my jsonResponce :-
{
"ReplyCode": 1,
"Message": "Franchisee and Plans List",
"data2": [
{
"StateId": 1,
"StateName": "Andaman and Nicobar Island",
"CountryId": 1
},
{
"StateId": 2,
"StateName": "Andhra Pradesh",
"CountryId": 1
},
{
"StateId": 3,
"StateName": "Arunachal Pradesh",
"CountryId": 1
},
{
"StateId": 4,
"StateName": "Assam",
"CountryId": 1
},
This is the method by which i am getting the data from the json :-
public void volleyStatedata() {
if (mGeneralUtilities.isConnected()) {
mProgressDialog.show();
StringRequest stateRequest = new StringRequest(Request.Method.POST, GlobalData.REGISTER_DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mProgressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data2");
for (int i = 0; i < jsonArray.length(); i++) {
PojoState pojoState = new PojoState();
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String stateId = jsonObject1.getString("StateId");
String stateName = jsonObject1.getString("StateName");
mStateList.add(stateName);
mStateIdList.add(stateId);
pojoState.setmStateList(mStateList);
pojoState.setmStateId(stateId);
mpojoStateList.add(pojoState);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("error", "" + volleyError.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue stateQueue = Volley.newRequestQueue(getContext());
stateQueue.add(stateRequest);
} else {
mGeneralUtilities.showAlertDialog("Hey User !", "Please connect to the internet", "Ok");
}
}
And this is my adapter where i am applying onItemclick listner on the autocompltetextview :-
ArrayAdapter<String> mStateAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, mStateList);
mActState.setAdapter(mStateAdapter);
mActState.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mpojoStateList.get(i).getmStateId();
}
});
Your code uses i that returns in the onItemClick callback, which refers to the item you clicked from the visible items in the auto-complete list, not your original list. When you click on the first item in the auto-complete list, i=0, which means it always returns the "Andaman and Nicobar Island" item whose StateId=1.
Off the top of my head, you can get the item String from the mStateAdapter and compare it to your mpojoStateList and find the corresponding item. (Check the sample code)
final ArrayAdapter<String> mStateAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, mStateList);
mActState.setAdapter(mStateAdapter);
mActState.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String itemName = mStateAdapter.getItem(i);
for (PojoState pojo : mpojoStateList) {
if (pojo.mStateName.equals(itemName)) {
String id = pojo.getmStateId(); // This is the correct ID
break; // No need to keep looping once you found it.
}
}
}
});
It also is better if, inside your PojoState object, you override your toString() method and make it return the mStateName, and pass the mpojoStateList to the adapter without having to make 3 ArrayLists. That way, mStateAdapter.getItem(i) will return a PojoState object instead of a String, and you can use its ID without referring to the returned position (i).
My Recyclerview was working fine , what i did was simple, i fetched data from a webervice and displayed it using recyclerView
This is my code for loading more data
public void loadmoredata(int limit) {
limit++;
String url = "http://oilpeople.talenetic.com/api/SearchJob?limit="+limit+ "&jobkeyword=" + key + "&countrytext=" + coun + "&location=" +loc+ "&apikey=1111111111&siteid=1";
JsonObjectRequest loadmore = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(loadArray);
jobTitle = new String[jsonArray.length()];
salary = new String[jsonArray.length()];
companyName = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
if(loadArray.equals("Indeedjobslist")) {
String salaryLoc = c.getString("location");
jobTitle[i] = c.getString("jobtitle");
companyName[i] = c.getString("companyname");
salary[i] = salaryLoc;
} else {
String salaryLoc = c.getString("salary")+ " \u2022 " +c.getString("location");
jobTitle[i] = c.getString("jobtitle");
companyName[i] = c.getString("companyname");
salary[i] = salaryLoc;
}
// show the values in our logcat
m.setCompanyName(companyName);
m.setJobTitle(jobTitle);
m.setSalary(salary);
adapter.notifyDataSetChanged();
}
} catch(JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(SearchResults.this).add(loadmore);
}
adapter is a global variable. I am trying to load more data like this:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.fTextView.setText(jobTitle[position]);
holder.mTextView.setText(companyName[position]);
holder.sTextView.setText(jobs[position]);
if (position % 10 == 0) {
int limit = position + 5;
loadmoredata(limit);
}
}
Whenever the % of position is 0 I load more data, but I am getting indexoutofBounds error.
remove
if (position % 10 == 0) {
int limit = position + 5;
loadmoredata(limit);
}
and use this method calling to know count from your main activity then call your above cod but i think that will cause infinite loop
public int getItemCount() {
return mDataset.length;
}
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>