Android json parsing by category wise - android

I have a Json Array like below:
[{"item":{"category Name":"T-e-PBS","SubCategory Name":"T-e-PBS"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Animals"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Birds"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Vegetables"}},
{"item":{"category Name":"T-e-PBS","SubCategory Name":"Colors"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Rhymes"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Animated Rhymes"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Cartoon Rhymes"}},
{"item":{"category Name":"Rhymes","SubCategory Name":"Prayers"}}]
I have tried but don't know how to get Category wise information as I have lots of Subcategories under Categories:
I want to Parse this JSON String and populate the data According to Category.
If I click on T-e-PBS button I should be able to get All Subcategories in a gridview like AnimalsImage, BirdsImages, etc in gridview.
And if I click on Rhymes category I should be able to get All Subcategories in a gridview.
Could anyone help?
I have tried:
JSONArray ja = new JSONArray(json);
int size = ja.length();
Log.d("tag","No of Elements " + ja.length());
for (int i = 0; i < size; i++) {
String str = ja.getString(i);
}

In the for loop, retrieve required JSON Objects using
JSONObject c = ja.getJSONObject(i);
And then store Json item in a variable using,
String str = c.getString("category Name");
JSON Objects are represented using {. So depending on your JSON structure, parse it and retrieve desired item.

You can use HashMap to store the separate Category List, and you can easily get the desired list of Category like T-e-PBS, Rhymes, etc.
// Which hold the category basis of category Type
HashMap<String, List<String>> category = new HashMap<String, List<String>>();
List<String> cat_name = new ArrayList<String>();
List<String> subcat_name = new ArrayList<String>();
try {
JSONObject script = new JSONObject("YOUR RESPONSE STRING");
JSONArray listOfCategory = script.getJSONArray("YOUR_ARRAY");
for (int j = 0; j < listOfCategory.length(); j++) {
JSONObject item = listOfCategory.getJSONObject(j).getJSONObject("item");
String cat = item.getString("category Name");
if (cat.equalsIgnoreCase("T-e-PBS")) {
cat_name.add(item.getString("SubCategory Name"));
} else if (cat.equalsIgnoreCase("Rhymes")) {
subcat_name.add(item.getString("SubCategory Name"));
}
}
category.put("T-e-PBS", cat_name);
category.put("Rhymes", subcat_name);
// To get the according to Category Name
List<String> retrieveCatList1 = category.get("T-e-PBS");//Key is T-e-PBS
List<String> retrieveCatList2 = category.get("Rhymes");//Key is Rhyme
} catch (Exception e) {
}

You can use a HashMap of ArrayLists
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
try {
JSONArray array = new JSONArray(str);
// Where str is your response in String form
for (int i=0; i<array.length(); i++){
String category = item.getString("category Name");
String subcategory = item.getString("SubCategory Name");
ArrayList<String> categoryFromMap = map.get("category");
if (categoryFromMap == null){
// Not initiated
categoryFromMap = new ArrayList<String>();
}
categoryFromMap.put(subcategory);
map.put(category, categoryFromMap);
}
} catch (JSONException ex){
ex.printStackTrace();
}
// Accessing your data
for (String key : map.keySet()){
// key contains your category names
ArrayList<String> subcategories = map.get(key);
Log.d("CATEGORY", key);
for (String subcat : subcategories){
Log.d("SUBCATEGORY", subcat);
}
}
// Getting a single category
ArrayList<String> rhymes = map.get("Rhymes");
The Log.d sentences should give this output:
CATEGORY T-e-PBS
SUBCATEGORY T-e-PBS
SUBCATEGORY Animals
SUBCATEGORY Birds
SUBCATEGORY Vegetables
SUBCATEGORY Colors
CATEGORY Rhymes
SUBCATEGORY Rhymes
SUBCATEGORY Animated Rhymes
SUBCATEGORY Cartoon Rhymes
SUBCATEGORY Prayers

Related

I am trying to get data from room database in arraylist but it shows only last record in android

I have room database in android. but when i am retrieving data from database and showing in expandable RecyclerView it shows only last records in my child list. there is one child ArrayList under the parent ArrayList.
I am adding data from database in hashmap in the key and value format in ExpandableListView
HashMap<String, List<Movies>> expandableListDetail = new HashMap<String, List<Movies>>();
ArrayList<String> moviecategoriess = new ArrayList<>();
for (int i = 0; i < tasks.size(); i++) {
childDataItems = new ArrayList<>();
String movieCategory = tasks.get(i).getMovieCategory();
String moviename = tasks.get(i).getMovieName();
String description = tasks.get(i).getMovieDescription();
String bannerimage = tasks.get(i).getMovieImage();
// String maincat=expandableListDetail.get("").get(i).
childDataItems.add(new Movies(moviename, bannerimage, description));
expandableListDetail.put(movieCategory, childDataItems);
moviecategoriess.add(movieCategory);
}
Iterator it = expandableListDetail.entrySet().iterator();
final ArrayList<MovieCategory> movieCategories = new ArrayList();
moviesArrayList = new ArrayList();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
String name = pairs.getKey().toString();
moviesArrayList = (ArrayList<Movies>) pairs.getValue();
movieCategories.add(new MovieCategory(name, moviesArrayList));
}
moviesAdapter = new MoviesAdapter(MovieActivity.this, movieCategories);
Functions.setDatatoRecyclerView(rv_movies_list, moviesAdapter, MovieActivity.this);
moviesAdapter.notifyDataSetChanged();
}
I want to show data in ArrayList like this
Parent Item: Thriller
ChildItems In List:
1) Force2
2) Sarkar2
Parent Item: Action
ChildItems In List:
1) Border
2) Battlefield
In your case problem is with for loop each time you run for loop a new array list is created as per your code so simply replace your code with this:
HashMap<String, List<Movies>> expandableListDetail = new HashMap<String, List<Movies>>();
ArrayList<String> moviecategoriess = new ArrayList<>();
childDataItems = new ArrayList<>();
for (int i = 0; i < tasks.size(); i++) {
String movieCategory = tasks.get(i).getMovieCategory();
String moviename = tasks.get(i).getMovieName();
String description = tasks.get(i).getMovieDescription();
String bannerimage = tasks.get(i).getMovieImage();
// String maincat=expandableListDetail.get("").get(i).
childDataItems.add(new Movies(moviename, bannerimage, description));
expandableListDetail.put(movieCategory, childDataItems);
moviecategoriess.add(movieCategory);
}

Parsing json array from the JSON object in Android

I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?
It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}
you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}

How to set json data to list view?

I tried to add json data to listview.But i don't know how to add the json data to list adapter.
try {
mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
String address = jsonChildNode.optString("address");
String mobile = jsonChildNode.optString("mobile");
String direction = "Direction: "+jsonChildNode.optString("direction");
String bestTime = "Best time to visite: "+jsonChildNode.optString("bestTime");
String food = jsonChildNode.optString("food");
String dress = jsonChildNode.optString("dress");
String priceRange = "Price Range: "+jsonChildNode.optString("priceRange");
String rate = jsonChildNode.optString("Rate");
String comment = "Price Range: "+jsonChildNode.optString("comment");
map.put("restName",restName);
map.put("address",address);
map.put("mobile",mobile);
map.put("direction",direction);
map.put("bestTime",bestTime);
map.put("food",food);
map.put("dress",dress);
map.put("priceRange",priceRange);
map.put("rate",rate);
map.put("comment",comment);
mylist = new ArrayList<HashMap<String, String>>();
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
// ListAdapter adapter = new SimpleAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mylist);
// list.setAdapter(adapter);
}
Can anyone tel me how to set this data to list view.?
Try this..
Your doing reversely. declear the arraylist before for loop and declear the HashMap inside the for loop .
mylist = new ArrayList<HashMap<String, String>>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
HashMap<String, String> map = new HashMap<String, String>();
String address = jsonChildNode.optString("address");
//So on
map.put("restName",restName);
//So on
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
google-gson
I would use gson for this. Check the gson project website for more details on how. This is an example for object serialisation/deserialisation:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj

How to add values to a string array in android

I have a problem with my code,
I have a json array
[{"Response":{"data":"sibin1"}},{"Response":{"data":"sibin2"}},
{"Response": {"data":"sibin3"}}]
And iam trying to extract the json data using the below code,Here i added only some parts of the coode
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
for (int i = 0; i < finalResult.length(); i++)
{
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
System.out.println(result);
}
The code is worked very well
when the value of
i=0 ,result is sibin1
i=1 ,result is sibin2
i=2 ,result is sibin3
But my problem is , i need to store the result in a string array of length finalresultlength inside the given for loop, also i need to print the values in the string array in a for loop outside the given for loop
if anybody knows please help me...........
You could do this way as well.
Create an ArrayList of size 'finalresultlengt' and the add the values in.
list.add(result); // variable 'result' in your case is the value from JSON
If you have more values to be added, create a POJO class.
class POJO {
private String dataVal;
public void setDataVal(String dataVal) {
this.dataVal = dataVal;
}
public String getDataVal() {
return dataVal;
}
}
Then create an ArrayList of type POJO.
ArrayList<POJO> list = new ArrayList<POJO>(finalresultlengt);
EDIT
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
ArrayList<String> list = new ArrayList<String>(finalresultlengt);
for (int i = 0; i < finalResult.length(); i++) {
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
list.add(result);
}
Populate values from ArrayList.
for(String value : list)
System.out.println(value);

How to get a part of a datastring from clicking a listview-item

I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).

Categories

Resources