ArrayList cannot be set to model class - android

I am new to android.I have a JSONArray containing images and other attributes.I am trying to set it into the model class.
MenuContent singleItem = new MenuContent();
singleItem.setContent(mContentJsonObject.getString(AppConstants.APIKeys.CONTENT));
singleItem.setContentId(mContentJsonObject.getString(AppConstants.APIKeys.PARAGRAPH_ID));
singleItem.setChapterId(mContentJsonObject.getString(AppConstants.APIKeys.CHAPTER_ID));
singleItem.setClassId(getSharedPreference(AppConstants.APIKeys.CLASS_ID));
singleItem.setLanguageId(getSharedPreference(AppConstants.APIKeys.LANGUAGE_ID));
JSONArray mGalleryimages = mContentJsonObject.getJSONArray(AppConstants.APIKeys.PARAGRAPH_GALLERY_IMAGES);
for (int k = 0; k < mGalleryimages.length(); k++) {
JSONObject mGallerycontent=mGalleryimages.getJSONObject(k);
ImageGallery imageGallery = new ImageGallery();
imageGallery.setImageId(String.valueOf(k));
imageGallery.setImagePath(mGallerycontent.getString(AppConstants.APIKeys.PARAGRAPH_GALLERY_CONTENT));
array_image.add(imageGallery);
}
singleItem.setImageGallery(array_image);
singleItem.save();
mParagraphsList.add(singleItem);
The problem is I can set all attributes except galleryimages array to the model class.But setImageGallery only is not working.I am getting null there when debugging it.This is MenuContent model class snippet
ArrayList <ImageGallery> imageGallery;
public ArrayList<ImageGallery> getImageGallery() {
return imageGallery;
}
public void setImageGallery(ArrayList<ImageGallery> imageGallery) {
this.imageGallery = imageGallery;
}
ImageGallery model class snippet
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getImagePath() {
return imagePath;
}
Can anyone tell me whats the problem?Any help is appreciated.

This code can be converted to 2 lines with well known Google Gson Library
Have a glance at this.
Type listType = new TypeToken<List<MenuContent>>() {}.getType();
List<MenuContent> yourList = new Gson().fromJson(yourJson, listType);
You dont have to write a long code with parsing with keys.

Related

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.

cannot find symbol type token in android studio?

private void loadFromAndToPlaceValues() {
String str = loadJSONFromAsset();
this.places = (List)new Gson().fromJson(str, newTypeToken<List<BusEntity>>().getType());
if (this.places != null && this.places.size() > 0) {
this.places_array = new String[this.places.size()];
for (int i = 0; i < this.places_array.length; i++) {
this.places_array[i] = ((BusEntity) this.places.get(i)).getValue();
}
}
}
You've missed {} braces. Change it like following.
this.places = (List)new Gson().fromJson(str, new TypeToken<List<BusEntity>>(){}.getType());
On a different note, question should be more constructive and descriptive. Posting plain code likely won't yield good answer most of the time.
It may help you :
Option 1 - implement java.lang.reflect.ParameterizedType yourself and pass it to Gson.
private static class ListParameterizedType implements ParameterizedType {
private Type type;
private ListParameterizedType(Type type) {
this.type = type;
}
#Override
public Type[] getActualTypeArguments() {
return new Type[] {type};
}
#Override
public Type getRawType() {
return ArrayList.class;
}
#Override
public Type getOwnerType() {
return null;
}
// implement equals method too! (as per javadoc)
}
Then simply:
Type type = new ListParameterizedType(clazz);
List<T> list = gson.fromJson(json, type);
This will work too, at least with Gson 2.2.4.
Type type = com.google.gson.internal.$Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class, clazz);

How to check arraylist contains this particular word in android?

I have ArrayList<String> in that I added 3-4 website names. Like, http://www.google.com, https://www.stackoverflow.com, etc. Now in my application if I type simply "google" then I want to compare that "google" word with the ArrayList<String>.
I am stuck here. Can anyone tell me how can I compare the string with the array object?
Thanks in advance.
To do so, you need to override implementation of contains(). I am giving you a simple example.
Custom ArrayList class
public class MyArrayList extends ArrayList<String> {
private static final long serialVersionUID = 2178228925760279677L;
#Override
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
#Override
public int indexOf(Object o) {
int size = this.size();
if (o == null) {
for (int i = 0; i < size ; i++) {
if (this.get(i) == null) {
return i;
}
}
} else {
for (int i = 0; i < size ; i++) {
if (this.get(i).contains(String.valueOf(o))) {
return i;
}
}
}
return -1;
}
}
How to use
MyArrayList arrayList = new MyArrayList();
arrayList.add("http://www.google.com");
arrayList.add("https://www.stackoverflow.com");
arrayList.add("http://pankajchunchun.wordpress.com");
if (arrayList.contains("google")) {
System.out.println("ArrayList Contains google word");
}
if (arrayList.contains("igoogle")) {
System.out.println("ArrayList Contains igoogle word");
} else {
System.out.println("ArrayList does not Contains igoogle word");
}
Below is output for above code example
ArrayList Contains google word
ArrayList does not Contains igoogle word
See ArrayList Source Code for more custom implementation.
ArrayList.contains() test the the String through equals. From the documentation:
public boolean contains(Object o) Returns true if this list contains
the specified element. More formally, returns true if and only if this
list contains at least one element e such that (o==null ? e==null :
o.equals(e)).
example:
boolean contains = yourArrayListInstance.contains(yourString);
Edit. If you want to check for substring you have to loop on the ArrayList's content and call String.contains
You can iterate through your ArrayList<String> like
public String getWebsiteName(String toMatchString)
{
ArrayList<String> yourArrayList = new ArrayList<String>();
for (String webSiteName : yourArrayList)
{
if (webSiteName.contains(toMatchString))
return webSiteName;
}
return null;
}
and get the matching String
Use a helper function like this
public static boolean containsSubString(ArrayList<String> stringArray, String substring){
for (String string : stringArray){
if (string.contains(substring)) return true;
}
return false;
}

Deserialization of JSON webservice in Android

I am trying to deserialize this JSON array into my android project.
[{"Name":"Ban","Price":1},{"Name":"Banana","Price":1},{"Name":"chicken","Price":14},{"Name":"pizza","Price":16},{"Name":"slice","Price":1}]
I have made this webservice in Asp.net.
The code I am using to deserialize it is below
public void onClick(View v)
{
String url="http://192.168.15.2/MyAndroid/InputCaller.aspx"; //do not use localhost
String response=callWebService(url);
List<Items> mObjectList = new ArrayList<Items>() ;
ItemsList list = null;
Gson gson = new Gson();
list = gson.fromJson(response, ItemsList.class);
// list = getItemsList(response);
Intent myIntent = new Intent(v.getContext(), Cart.class);
startActivity(myIntent);
}
public final ItemsList getItemsList (String jsonString)
{
ItemsList il = null;
Gson gson = new Gson();
il = gson.fromJson(jsonString, ItemsList.class);
return il;
}
public class ItemsList
{
private List<ItemsContainer> items = new ArrayList<ItemsContainer>();
public List<ItemsContainer> getItemsContainerList()
{
return items;
}
}
class ItemsContainer
{
Items items;
public Items getItem()
{
return items;
}
}
public class Items
{
String Name;
int Price;
}
It is not working and when I try to debug it I get this message on list = gson.fromJson(response, ItemsList.class);
Gson.class Source not found.
This is my first deserialisation program and I would really appreciate if anybody help me with it. Thank you,
Don't make things complicated by using further parent classes (as container) for Items class. Simply de-serialize all the items into a List object using Gson as below:
List<Items> listItems = (List<Items>) gson.fromJson(response,
new TypeToken<List<Items>>(){}.getType());
now you've got all the Items in a List object: listItems

Android - How to create a basic class and use it?

I have defined a class that contains properties of a specific answer object
The class look like this and is defined inside the class that is trying to use it
protected class Answer {
String QuestionId = "";
String AnswerValue = "";
String Correct = "";
public String getQuestionId() {
return QuestionId;
}
public void setQuestionId(String arg) {
QuestionId = arg;
}
public String getAnswerValue() {
return AnswerValue;
}
public void setAnswerValue(String arg) {
AnswerValue = arg;
}
public String getCorrect() {
return Correct;
}
public void setCorrect(String arg) {
Correct = arg;
}
}
Not sure if the above is OK
When I try to use the class I get null pointer errors
I'm using it like this
ArrayList<Answer> answerList = new ArrayList<Answer>();
for(int a=0;a<answers.getLength(); a++){
Element eAnswer = (Element) answers.item(a);
Answer anAnswer = new Answer;
NodeList answer_nodes = eAnswer.getChildNodes();
for (int ian=0; ian<answer_nodes.getLength(); ian++){
Node ans_attr = answer_nodes.item(ian);
String tag_name = ans_attr.getNodeName();
if(tag_name.equalsIgnoreCase("answer")){
anAnswer.setAnswerValue(ans_attr.getTextContent());
}
}
answerList.add(anAnswer);
}
Answer anAnswer = new Answer; gives a compilation error
All I'm trying to do is to create a list of answers which have a name value pair for a number of properties
Any guidance on this greatly appreciated - Especially if there is a better way
Answer anAnswer = new Answer();

Categories

Resources