Load Json Into Recyclerview item with Spinner - java

I have two arrays
Android
PriceWeight
where Android is whole view and PriceWeight I want to show in spinner (Weight or Price).
I have done fetching it just problem is fetching data in spinner.
JSON Link
http://navsarimarket.com/API/getProductPriceWeight.php?Category=77

you can iterate over your JSON and make a string list something like below
JSONObject obj = new JSONObject(jsonString);
JSONArray androidArray = obj.getJSONArray("Android");
for(int count=0; count<androidArray.length(); count++){
JSONObject inner = androidArray.get(count);
JSONArray weight = inner.getJSONArray("PriceWeight");
List<String> spinnerArrayList = new ArrayList<String>();
for(int i=0; i<weight.length(); i++){
JSONObject temp = weight.get(i);
String value = temp.getString("Weight");
value = value + " - " + temp.getString("Price");
//pass this to your recyclerview model for showing spinner per row.
spinnerArrayList.add(value);
}
}

Inside your onBindViewHolder add below code where list is list of data you get from JSON response which will display in your spinner.
List<String> list = new ArrayList<String>();
list.add("TEST");
ArrayAdapter<String> dataAdapter =new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.siteSpinner = (Spinner) findViewById(R.id.siteSpinner);
holder.siteSpinner.setAdapter(dataAdapter);
}

Related

How to parse JSON data to model class and display in multiple recyclerview

Hello I am creating a multiple horizontal recycler view layout which holds multiple recycler view.
JSON dummy data below
{
"MyData":
[{"headerTitle":"Fruits","listItem":[{"image":"https://png.pngtree.com/element_our/png/20180903/orange-png-png_75700.jpg","name":"Orange","hname":"Fruits"},{"image":"https://www.freepngimg.com/thumb/apple/9-apple-png-image-thumb.png","name":"Apple","hname":"Fruits"},{"image":"https://5.imimg.com/data5/RM/TY/MY-13308502/fresh-watermelon-500x500.png","name":"Watermellon","hname":"Fruits"},{"image":"https://c7.uihere.com/files/947/615/656/banana-food-fruit-clip-art-bananas-png-clipart-image-thumb.jpg","name":"Banana","hname":"Fruits"},{"image":"https://png.pngtree.com/element_pic/00/16/09/0657ce7dc878850.jpg","name":"Cherry","hname":"Fruits"}]},{"headerTitle":"Pizza","listItem":[{"image":"https://www.pngarts.com/files/3/Pizza-PNG-Image.png","name":"Pizza 1","hname":"Pizza"},{"image":"https://encrypted-tbn0.gstatic.com/images?q\u003dtbn:ANd9GcSpqnkJ4gzZaWEbOYeMaqz3yV-VxRrCBplog_3t8OaBkCDf3RCRWw","name":"Pizza 2","hname":"Pizza"},{"image":"https://png.pngtree.com/element_origin_min_pic/16/11/02/4dc2c71756d114bf0f3333a33514ffa4.jpg","name":"Pizza 3","hname":"Pizza"},{"image":"https://pngimage.net/wp-content/uploads/2018/06/rebanada-de-pizza-png-1.png","name":"Pizza 4","hname":"Pizza"},{"image":"https://encrypted-tbn0.gstatic.com/images?q\u003dtbn:ANd9GcTWVHTyPRtMWuw3Wx0sn-bsOrLCYqy2di2QUfw4V75uchLbrfYT","name":"Pizza 5","hname":"Pizza"}]},{"headerTitle":"Drink","listItem":[{"image":"http://pngimg.com/uploads/cocktail/cocktail_PNG155.png","name":"Drink 1","hname":"Drink"},{"image":"https://images.vexels.com/media/users/3/135691/isolated/preview/175702226dd92b9a70d23b87ebed4a5d-cocktail-drink-by-vexels.png","name":"Drink 2","hname":"Drink"},{"image":"https://s7d9.scene7.com/is/image/SAQ/cosmo-golden-gate-ec?$saq-fiche-cocktail$","name":"Drink 3","hname":"Drink"},{"image":"https://www.belvederevodka.com/upload/maraschino-vermouth-belvedere-vodka-martini.png","name":"Drink 4","hname":"Drink"},{"image":"https://png.pngtree.com/element_origin_min_pic/16/09/27/1057e9dc08462c6.jpg","name":"Drink 5","hname":"Drink"}]},{"headerTitle":"Wine","listItem":[{"image":"http://www.probottleshots.com/wp-content/uploads/2014/03/napa-bottle-photographer-Tinacci.jpg","name":"Wine 1","hname":"Wine"},{"image":"http://www.pngpix.com/wp-content/uploads/2016/10/PNGPIX-COM-Wine-Bottle-PNG-Transparent-Image-1-500x1025.png","name":"Wine 2","hname":"Wine"},{"image":"https://pronto-core-cdn.prontomarketing.com/2/wp-content/uploads/sites/1633/2016/03/l-creek-shiraz-cab-no-vintage-transparent-background.jpg","name":"Wine 3","hname":"Wine"},{"image":"https://png.pngtree.com/element_pic/17/07/21/3f0516b906aa8dd783c6e0aefaa52567.jpg","name":"Wine 4","hname":"Wine"},{"image":"http://atlas-content-cdn.pixelsquid.com/stock-images/old-glass-bottle-corkscrew-mdnO39D-600.jpg","name":"Wine 5","hname":"Wine"}]}]
}
everything working perfectly but model class not adding data row-wise means repeating same data in all child recyclerview from JSON data.
what i want-: i want to load data separately for each recyclerview from JSON by using "listItem".
Here my codes
try {
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray dataArray = jsonObject.getJSONArray("MyData");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataobj = dataArray.getJSONObject(i);
String headerTitle = dataobj.getString("headerTitle");
JSONArray listViewData = dataobj.getJSONArray("listItem");
SectionDataModelSearch dm = new SectionDataModelSearch();
dm.setHeaderTitle(headerTitle);
// looping through All that
for (int j = 0; j < listViewData.length(); j++) {
JSONObject c = listViewData.getJSONObject(j);
image = c.getString("image");
name = c.getString("name");
singleItem.add(new SingleHandleSearchModel(name,image));
}
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);
}
}
catch( final JSONException e){
Toast.makeText(getActivity(), "FAILED" + "Json parsing error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
i know i am getting wrong data from JSON data. please help me.

ArrayList object is returing one row on ListView in java android

I am trying to add Objects from MySQL database on ArrayList Object but result gives me only one row
i am using custom adapter on my ListView, i think i could use loop multiple objects to ArrayList object but i failed , please help me,
my code :
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Looks like you are creating an ArrayList everytime you parse an object. If I understand correctly, your code should be something like that:
// ArrayList will be created only once for a json response.
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
//Now parse add all elements in json response and add to list.
for(all items in your jsonResponse List ) {
//Parse fields from json object
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
//create object
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
//Now list will have all the items, Add this list to adapter.
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<>(getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
Suppose Your Server gives a result in JSONArray say response as a String Try the following
List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>();
JSONArray jsonArray = new JSONArray(response);
int size = jsonArray.length();
if (size > 0)
{
for (int i = 0; i < size; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String driver_fullname = json.getString("driver_fullname");
String driver_phonenumber = json.getString("driver_phonenumber");
String plate_no = json.getString("plate_no");
String parking_name = json.getString("parking_name");
PaymentTiming_Items timingItems = new PaymentTiming_Items();
timingItems.setPlateNo(plate_no);
timingItems.setParkingName(parking_name);
timingItems.setDriverFullName(driver_fullname);
getAllDiverDetails.add(timingItems); // store all drivers' info to
}
}
if (getAllDiverDetails.size() !=0) {
userList = new ArrayList<> (getAllDiverDetails);
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList);
myList.setAdapter(listAdapter);
}
You must use JSONArray for getting list of items from JSON. And then populate your ArrayList with them and pass to your adapter.

How to print object array in JAVA

I want to print from object like this :
{"data":[["Tiger Nixon","System
Architect","Edinburgh","5421","2011\/04\/25","$320,800"],["Garrett
Winters","Accountant","Tokyo","8422","2011\/07\/25","$170,750"]]}
i tried in java like this :
ArrayList<String> list = new ArrayList<String>();
list.add("Tiger Nixon");
list.add("System Architect");
list.add("Edinburgh");
list.add("2011\/04\/25");
list.add("$320,800");
JSONArray stateArray = JSONFactoryUtil.createJSONArray();
JSONObject stateObject;
stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("data", list); // i got an error in here
stateArray.put(stateObject);
System.out.println(stateArray);
But, i don't know how to implement object like that.
There's anyone can help me ?
Note :- Here JSONObject class whatever i used belongs to org.json.simple Jar Only. I used this class org.json.simple.JSONObject
What you have tried is. You are trying to create a JSONObject of Type ArrayList<String> which will not give you the expected Result, because your json array format is such like that
[["","",""],["","",""],["","",""],["","",""]] // arraylist inside an arraylist.
Your format like that a ArrayList inside an ArrayList but what you try is using only one ArrayList.
Here is your Code.
ArrayList<String> list = new ArrayList<String>(); //only one arrayList.
list.add("Tiger Nixon"); // adding values to the list.
list.add("System Architect");
list.add("Edinburgh");
list.add("2011\/04\/25");
list.add("$320,800");
Your Code will give output like this..
[{"data":"["","",""]"}, {"data":"["","",""]"}, {"data":"["","",""]"}]
Try this code instead of yours (below is just for sample use please try to manipulate this logic as per your need). this will give you the expected Result.
ArrayList<ArrayList<String>> final_arrObject = new ArrayList<ArrayList<String>();
ArrayList<String> list;
for(int i=0; i<5; i++){ //demo to add 5 ArrayList<String> to an ArrayList<ArrayList<String>>.
list = new ArrayList<String>(); //only one arrayList.
//at each iteration you may change you ArrayList Values.
list.add("Tiger Nixon"); // adding values to the list.
list.add("System Architect");
list.add("Edinburgh");
list.add("2011\/04\/25");
list.add("$320,800");
final_arrObject.add(list);
}
JSONObject obj_finalJSON= new JSONObject();
obj_finalJSON.put("data", final_arrObject);
System.out.println(obj_finalJSON.toString()); //it will print your json as a String.
You can achieve your objective like this:
JSONArray stateArray = JSONFactoryUtil.createJSONArray();
stateArray.put("Tiger Nixon");
stateArray.put("System Architect");
stateArray.put("Edinburgh");
stateArray.put("2011\/04\/25");
stateArray.put("$320,800");
JSONObject stateObject;
stateObject = JSONFactoryUtil.createJSONObject();
stateObject.put("data", stateArray);
System.out.println(stateObject.toString());
ArrayList <String> list = new ArrayList <String>();
list.add("Tiger Nixon");
list.add("System Architect");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
JSONObject object = new JSONObject();
try {
obj.put("data", array);
} catch (JSONException e) {
e.printStackTrace();
}
There is a model,and some properties in it.
You can new some model info ,and add it to a List.
Then put this list to JSON,and print it json.toString().
If you want specific code, send message to me!

Android get data from json and sort

I'm trying to get data from json. I can get data at first state.
But how to get data "ascending" and "descending" and show it on another activity in listview ?
Here's My Json
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
And here's my Java code
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String table_name = c.getString(TAG_TABLE_NAME);
String item_list = c.getString(TAG_ITEM_LIST);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CATEGORY_NAME, category_name);
contact.put(TAG_TABLE_NAME, table_name);
contact.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodlistfilter.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm trying to follow this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, but i still don't fully understand.
Let me explain this.
[ means its an array.
{ is an object.
In your case it's an array whcih contains an -JSONObject with name category_name, filter_type and field_name. type and table_name and a new jsonarray with object item_list.
How can you parse this string?
Here is an example:
String str = "[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}";
JSONArray jsonArray = new JSONArray(str);
//now it holds the JSONObject.
for (int i = 0; i<= jsonArray.length(); i++) {
//now we loop through and get the jsonObject
JSONObject jsonObj = new JSONObject(jsonArray.getJsonObject(i));
//now it contains your data.
Log.d("Category_nameValue=", jsonObj.getString("category_name"));
//now we want to get the array from the item_list.
JSONArray itemList = new JSONArray(jsonObj.getString("item_list"));
//now itemList.getString(1); === Ascending while itemList.getString(2) == Descending
//now itemList contains several new objects which can also be looped as the parent one.
}
Since you now know how to create an JSONArray, you can start sorting it.
This has been answered already at Android how to sort JSONArray of JSONObjects
If you want to send those data to another Activity you can use the JSONArray.toString() method and send it via Intents.
This is easy explained at Pass a String from one Activity to another Activity in Android
Hope this helps.
If you're new, I would recommend you think about using Gson to parse your Json response directly to a java entity class. So you will avoid to manually parse all your responses.
Your JSON response
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
The entity representing the response
public class MyEntity {
String category_name;
String filter_type;
String field_name;
String type;
String table_name;
String [] item_list;
// getters / setters ...
}
Parsing the response
Gson gson = new Gson();
MyEntity myEntity = gson.fromJson(response, MyEntity.class);
Finally, to send the data, start the new Activity with extras
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("EXTRA_DATA", myEntity.getCategoryName());
startActivity(intent);
Now you recover the extra data on your AnotherActivity
Intent intent = getIntent();
String categoryName = intent.getStringExtra("EXTRA_DATA");
And you can fill the ListView using an ArrayAdapter: Example
To get a JSONArray from your JSONObject c
simply write:
JSONArray itemList = c.getJSONArray(name);
then you can iterate through that data like any other array
for (int i = 0; i < itemList.length(); i++) {
// do something
}

Parse JSONObject and JSONArray and fix them in the listview

How to parse JSONArray inside JSONObject?. Here is the JSON response I'm getting from the server.
{
"searchdata": {
"titles": [
"<b>Laptop</b> - Wikipedia, the free encyclopedia",
"<b>laptop</b> - definition of <b>laptop</b> by the Free Online Dictionary ..."
],
"desc": [
"A <b>laptop</b> computer is a personal computer for mobile use. A <b>laptop</b> has most of the same components as a desktop computer, including a display, a keyboard, a ...",
"lap·top (l p t p) n. A portable computer small enough to use on one&apos;s lap. <b>laptop</b> [ˈlæpˌtɒp], <b>laptop</b> computer. n (Electronics & Computer Science / Computer ..."
],
"links": [
"http://en.wikipedia.org/wiki/Laptop",
"http://www.thefreedictionary.com/laptop"
],
"nextpage": ""
}
}
I'm able to get JSONObject but how to get JSONArray one by one, so that I can fix them in the listview.
I want to show the values of each array in a single row of the listview and so on....
Any help will be appreciated.
Very easy..
you need to fix code like this:
//jsonString is your whole JSONString which you have shown above
JSONObject jObj = new JSONObject(jsonString);
JSONObject jSearchData = jObj.getJSONObject("searchdata");
JSONArray jTitles = jSearchData.getJSONArray("titles");
JSONArray jDesc= jSearchData.getJSONArray("desc");
JSONArray jLinks= jSearchData.getJSONArray("links");
String nextPage = jSearchData.getString("nextpage");
//and so on and so forth
For fetching the array items and show it into a listview:
//you can iterate over each item and add it to an ArrayList like this:
//i am showing you a single one,follow the same process for other arrays:
ArrayList titlesArray = new ArrayList();
for (int i = 0; i < jTitles.length(); i++) {
String item = jTitles.getString(i);
titlesArray.add(item);
}
Next you make this arraylist a source to a listview like this:
// Get a handle to the list view
ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setAdapter(new ArrayAdapter<string>((Your activity class).this,
android.R.layout.simple_list_item_1, titlesArray));
Consider that your top level JSON will be parsed into a JSONObject, and that subsequently you can request to receive from it, any sub level objects and/or arrays via the methods getJSONObject(name) and getJSONArray(name). Your arrays of interest are two levels deep in the JSON hierarchy, so you will need something like this:
String json = ...;
JSONObject rootObj = new JSONObject(json);
JSONObject searchObj = rootObj.getJSONObject("searchdata");
JSONArray titlesObj = searchObj.getJSONArray("titles");
JSONArray descsObj = searchObj.getJSONArray("desc");
JSONArray linksObj = searchObj.getJSONArray("links");
You can iterate any of the arrays as such (using titles as an example):
for(int i = 0; i < titlesObj.length(); i++) {
String title = titlesObj.getString(i);
}
it will be help:
JSONArray titles = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("titles");
JSONArray desc = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("desc");
JSONArray links = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("links");

Categories

Resources