java.lang.IndexOutOfBoundsException: Invalid index 18, size is 18 [duplicate] - java

This question already has answers here:
Java - IndexOutOfBoundsException: Index: 1, Size: 0
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
int i = 0; //used for getting item position
for (Iterator<CustomObject> iterator = mAdapter.getItemsData().iterator(); iterator.hasNext();) {
if (mAdapter.getItemsData().get(i).getPriceTier() != 1) { //if statement throws error
// Remove the current element from the iterator and the list.
iterator.remove();
mAdapter.removeFromItemsData(i);
}
i++;
}
Using this stackoverflow answer, I iterate through my arraylist of CustomObject. Custom object is just a POJO class with setters and getters. The setters and getters have different data types, such as int, String, double etc.
mAdapter.getItemsData returns the araylist from the adapter class.
//method just notifies the RecyclerView that an item was removed.
public void removeFromItemsData(int position){
notifyItemRemoved(position);
}
Here is the exception
java.lang.IndexOutOfBoundsException: Invalid index 18, size is 18
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308) at
com.test.TestActivity$5.onClick(TestActivity.java:280) at
android.view.View.performClick(View.java:4780) at
android.view.View$PerformClick.run(View.java:19866) at
android.os.Handler.handleCallback(Handler.java:739) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:135) at
android.app.ActivityThread.main(ActivityThread.java:5254) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
CustomObject class
public class CustomObject{
private String name;
private int distance;
private String category;
private String id;
private double rating;
private String ratingColor;
private String prefix;
private String suffix;
private int priceTier;
private String currency;
private String phone;
private String twitter;
private String url;
private String menu;
String address;
String city;
String state;
String postalCode;
double lat;
double lng;
String review;
int reviewCount;
String firstName;
String lastName;
String userIconPrefix;
String userIconSuffix;
String secondsReview;
public CustomObject() {
this.name = "";
this.distance = 0;
this.setCategory("");
this.id = "";
this.rating = 0;
this.ratingColor = "";
this.prefix = "";
this.suffix = "";
this.priceTier = 0;
this.currency = "";
this.phone = "";
this.twitter = "";
this.url = "";
this.menu = "";
this.address = "";
this.city = "";
this.state = "";
this.postalCode = "";
this.lat = 0;
this.lng = 0;
this.review = "";
this.reviewCount = 0;
this.firstName = "";
this.lastName = "";
this.userIconPrefix = "";
this.userIconSuffix = "";
this.secondsReview = "";
}
public void setSecondsReview(String secondsReview){
this.secondsReview = secondsReview;
}
public String getSecondsReview(){
return secondsReview;
}
public void setUserIconSuffix(String userIconSuffix){
this.userIconSuffix = userIconSuffix;
}
public String getUserIconSuffix(){
return userIconSuffix;
}
public void setUserIconPrefix(String userIconPrefix){
this.userIconPrefix = userIconPrefix;
}
public String getUserIconPrefix(){
return userIconPrefix;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
//todo if String firstNAme == null, then return "a foursquare user"
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getLastName(){
return lastName;
}
public void setReviewCount(int reviewCount){
this.reviewCount = reviewCount;
}
public int getReviewCount(){
return reviewCount;
}
public void setReview(String review){
this.review = review;
}
public String getReview(){
return review;
}
public void setLng(double lng){
this.lng = lng;
}
public double getLng(){
return lng;
}
public void setLat(double lat){
this.lat = lat;
}
public double getLat(){
return lat;
}
public void setPostalCode(String postalCode){
this.postalCode = postalCode;
}
public String getPostalCode(){
return postalCode;
}
public void setState(String state){
this.state = state;
}
public String getState(){
return state;
}
public void setCity(String city){
this.city = city;
}
public String getCity(){
return city;
}
public void setAddress(String address){
this.address = address;
}
public String getAddress(){
return address;
}
public void setMenuUrl(String menu){
this.menu = menu;
}
public String getMenuUrl(){
return menu;
}
public void setUrl(String url){
this.url = url;
}
public String getUrl(){
return url;
}
public void setTwitter(String twitter){
this.twitter = twitter;
}
public String getTwitter(){
return twitter;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getPhone(){
return phone;
}
public String getCurrency(){
return currency;
}
public void setCurrency(String currency){
this.currency = currency;
}
public int getPriceTier(){
return priceTier;
}
public void setPriceTier(int priceTier){
this.priceTier = priceTier;
}
public String getSuffix(){
return suffix;
}
public void setSuffix(String suffix){
this.suffix = suffix;
}
public String getPrefix(){
return prefix;
}
public void setPrefix(String prefix){
this.prefix = prefix;
}
public double getRating(){
if(rating > 0){
return rating;
}
return 0; //TODO display symbol if rating not found
}
public void setRating(double rating){
this.rating = rating;
}
public Integer getDistance() {
if (distance >= 0) {
return distance;
}
return 0; //TODO display symbol if distance not found, like N/A
}
public void setDistance(int distance) {
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
How data is added
In onCreate of activity, I instantiate Recyclerview. RecyclerView takes an arraylist, so I pass an empty one.
List listTitle = new ArrayList(); //empty arraylist
mAdapter = new Fragment1Adapter(listTitle);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
Later on in an AsyncTask, I add the items to the Adapter.
for (int i = 0; i < jsonArray.length(); i++) {
CustomObject poi = new CustomObject ();
if (jsonArray.getJSONObject(i).has("venue")) {
poi.setName(jsonArray.getJSONObject(i).getJSONObject("venue").getString("name"));
poi.setId(jsonArray.getJSONObject(i).getJSONObject("venue").getString("id"));
}
mAdapter.addItem(poi);
}
Here is the addItem class
Declared at top of adapter class private final List<FoursquareVenue> itemsData;
public void addItem(FoursquareVenue data) {
itemsData.add(data);
notifyItemInserted(itemsData.size() - 1);
}

Edit
Since you our chat and your edits:
You need to add and remove the items to your ArrayList and them notify adapter of change.
CustomObject poi = new CustomObject ();
if (jsonArray.getJSONObject(i).has("venue")) {
poi.setName(jsonArray.getJSONObject(i).getJSONObject("venue").getString("name"));
poi.setId(jsonArray.getJSONObject(i).getJSONObject("venue").getString("id"));
}
listTitle.addItem(poi);// Add to ListArray
Then loop through your ArrayList to remove items.
You've just muddled yourself up a bit in how you are trying to access your data.
There is a problem that you are creating an iterator of CustomObjects, and parsing it to the data type of mAdapter.getItemsData().
Removing the element from the iterator should remove it from the list.
for (Iterator<CustomObject> iterator = mAdapter.iterator(); iterator.hasNext();) {
CustomObject itemsData = iterator.next();
if (itemsData.getItemsData().get(i).getPriceTier() != 1) { //if statement throws error
// Remove the current element from the iterator and the list.
iterator.remove();
}
i++;
}
CustomObject itemsData = iterator.next();
Let me know if this helps.

Related

Why does the int in my model class return null

I am just wondering why my getTotal_Score() is null in my model class but I can retrieve it successfully from the database...I have tried both capital Integer and just a normal int, but that doesn't work...I have also tried Long type but I still get a null variable..The other thing that is puzzling me too is that when I use int type instead of long, it doesn't work.... Can you retrieve the numbers as int simple by doing:
int score = (int) snapshop.child("Glen Family Medical Centre").child("Total Score");
I can only get the above to work with long type...
public class Information { // variables have to match in firebase database or it will show null
private String Address;
private String Name;
private String Phone_No;
private String Suburb;
private String State;
private String Postcode;
private String Doctor;
private int Total_Score;
#SuppressWarnings("unused")
public Information() {
}
#SuppressWarnings("unused")
public Information(String address, String name, String phone_No, String suburb, String state, String postcode, String doctor, int total_score) {
Address = address;
Name = name;
Phone_No = phone_No;
Suburb = suburb;
State = state;
Postcode = postcode;
Doctor = doctor;
Total_Score = total_score;
}
public int getTotal_Score() {
return Total_Score;
}
public void setTotal_Score(int total_Score) {
Total_Score = total_Score;
}
public String getAddress() {
return Address;
}
#SuppressWarnings("unused")
public void setAddress(String address) {
Address = address;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone_No() {
return Phone_No;
}
#SuppressWarnings("unused")
public void setPhone_No(String phone_No) {
Phone_No = phone_No;
}
public String getSuburb() {
return Suburb;
}
#SuppressWarnings("unused")
public void setSuburb(String suburb) {
Suburb = suburb;
}
public String getState() {
return State;
}
#SuppressWarnings("unused")
public void setState(String state) {
State = state;
}
public String getPostcode() {
return Postcode;
}
#SuppressWarnings("unused")
public void setPostcode(String postcode) {
Postcode = postcode;
}
public String getDoctor() {
return Doctor;
}
#SuppressWarnings("unused")
public void setDoctor(String doctor) {
Doctor = doctor;
}
}
In my other class, I have used:
Information info = snapshot.getValue(Information.class);
assert info != null;
String txt = "Medical Clinic: " + info.getName() + "Total Score: " + info.getTotal_Score();
list.add(txt);

ObjectMapper can't map the variables of inner class

ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.
Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.

Storing an arraylist of custom objects (which have Strings, Dates, Lists, and more as fields) in shared preferences

I am trying to save an arraylist of clients in shared preferences, however I am getting out of memory error. I am new to this and can't figure out how to do this? I looked at a lot of pages on stackoverflow, but couldn't find one that would work for me or that also had an ArrayList of custom objects, where every object contains more ArrayLists with custom objects.
client object:
public class Client implements Serializable, Comparable<Client> {
private int clientID;
private String name;
private String phone;
private String email;
private String url;
private Double turnover;
private String visitAddress;
private String visitCity;
private String visitZipcode;
private String visitCountry;
private String postalAddress;
private String postalCity;
private String postalZipcode;
private String postalCountry;
private Drawable clientImage;
private List<Contact> contactList = new ArrayList<Contact>();
private List<Project> projectList = new ArrayList<Project>();
private List<Task> taskList = new ArrayList<Task>();
private List<Order> orderList = new ArrayList<Order>();
public Client(int clientID, String Name, String Phone, String Email, String URL, Double Turnover,
String VisitAddress, String VisitCity, String VisitZipcode, String VisitCountry,
String PostalAddress, String PostalCity, String PostalZipcode, String PostalCountry,
List contactList, List projectList, List taskList, List orderList){
super();
this.clientID = clientID;
this.name = Name;
this.phone = Phone;
this.email = Email;
this.url = URL;
this.turnover = Turnover;
this.visitAddress = VisitAddress;
this.visitCity = VisitCity;
this.visitZipcode = VisitZipcode;
this.visitCountry = VisitCountry;
this.postalAddress = PostalAddress;
this.postalCity = PostalCity;
this.postalZipcode = PostalZipcode;
this.postalCountry = PostalCountry;
this.contactList = contactList;
this.projectList = projectList;
this.taskList = taskList;
this.orderList = orderList;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}
public String getUrl() {
return url;
}
public Double getTurnover() {
return turnover;
}
public String getVisitAddress() {
return visitAddress;
}
public String getVisitCity() {
return visitCity;
}
public String getVisitZipcode() {
return visitZipcode;
}
public String getVisitCountry() {
return visitCountry;
}
public String getPostalAddress() {
return postalAddress;
}
public String getPostalCity() {
return postalCity;
}
public String getPostalZipcode() {
return postalZipcode;
}
public String getPostalCountry() {
return postalCountry;
}
public List<Contact> getContactList(){
return contactList;
}
public List<Project> getProjectList(){
return projectList;
}
public List<Task> getTaskList(){
return taskList;
}
public List<Order> getOrderList() {
return orderList;
}
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setEmail(String email) {
this.email = email;
}
public void setUrl(String url) {
this.url = url;
}
public void setTurnover(Double turnover) {
this.turnover = turnover;
}
public void setVisitAddress(String visitAddress) {
this.visitAddress = visitAddress;
}
public void setVisitCity(String visitCity) {
this.visitCity = visitCity;
}
public void setVisitZipcode(String visitZipcode) {
this.visitZipcode = visitZipcode;
}
public void setVisitCountry(String visitCountry) {
this.visitCountry = visitCountry;
}
public void setPostalAddress(String postalAddress) {
this.postalAddress = postalAddress;
}
public void setPostalCity(String postalCity) {
this.postalCity = postalCity;
}
public void setPostalZipcode(String postalZipcode) {
this.postalZipcode = postalZipcode;
}
public void setPostalCountry(String postalCountry) {
this.postalCountry = postalCountry;
}
public Drawable getClientImage() {
return clientImage;
}
public void setClientImage(Drawable clientImage) {
this.clientImage = clientImage;
}
public int getClientID() {
return clientID;
}
public void setClientID(int clientID) {
this.clientID = clientID;
}
underlying project object: (also with list of custom objects)
public class Project implements Serializable, Comparable<Project>{
private String clientName;
private String projectName;
private String projectDiscription;
private String projectStatus;
private GregorianCalendar projectDate;
private List<TimeSheet> projectTimeRegestrationList = new ArrayList<>();
private List<WorkOrder> workOrderList = new ArrayList<WorkOrder>();
public Project(String clientName, String projectName, String projectDiscription, String projectStatus, GregorianCalendar projectDate, List projectTimeRegestrationList, List workOrderList) {
this.projectName = projectName;
this.projectDiscription = projectDiscription;
this.projectStatus = projectStatus;
this.projectDate = projectDate;
this.clientName = clientName;
this.projectTimeRegestrationList = projectTimeRegestrationList;
this.workOrderList = workOrderList;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDiscription() {
return projectDiscription;
}
public void setProjectDiscription(String projectDiscription) {
this.projectDiscription = projectDiscription;
}
public String getProjectStatus() {
return projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public GregorianCalendar getProjectDate() {
return projectDate;
}
public void setProjectDate(GregorianCalendar projectDate) {
this.projectDate = projectDate;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public List<TimeSheet> getProjectTimeRegestrationList() {
return projectTimeRegestrationList;
}
public List<WorkOrder> getWorkOrderList() {
return workOrderList;
}
now my specific question: is it possible to save this inside shared preferences, if yes, how do i do this, if no, how should i then locally safe this data.
you can use json to store them as a string in sharedpreference
for example if you want to store an object of your client class contaning a url ,country and phone
just write the following
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
jsonArray.put(object1);
//adding another object
JSONObject object2=new JSONObject();
object2.put("url","anotherurl");
object2.put("phone","anotherphonenumber");
object2.put("country","anothercountry");
jsonArray.put(object2);
} catch (JSONException e) {
e.printStackTrace();
}
and than simply save it as a string by calling jsonArray.toString() in sharedpreference
and if your object that you want to store contains a list of another object you can easily save like for example if you have a url, country, and phone number which you want to save plus a list of another object containing the first and lastname you can save list as json object itself just like you did for the url,phone number and country as shown below
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
//saving a list of another object contaning firstname and lastname
JSONArray listArray=new JSONArray();
//supposing your list contains 10 objects
for(int f=0;f<10;f++){
JSONObject listobject=new JSONObject();
listobject.put("firstname","myfirstname");
listobject.put("lastname","mylastname");
listArray.put(listobject);
}
//now the list array we added as an object of the jsonArray variable
JSONObject object2=new JSONObject(); //object2 containing the list of firstname and lastname
object2.put("list",listArray.toString());
jsonArray.put(object1);//object1 contains the url, phone, and country
jsonArray.put(object2);//object2 contains the list of firstname and lastname
} catch (JSONException e) {
e.printStackTrace();
}

Constructor ClipData.Item is undefined Android

im trying to create a item for a list, to display on a listview some pictures.
The codes is the following:
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (int i = 0; i < pictures.size(); i++) {
Item item = new Item(pictures.get(i).getID(),pictures.get(i).getAddress(),pictures.get(i).getDescription(),pictures.get(i).getPath());
items.add(item);
}
return items;
}
What i'm trying to do in this is to create an item for each picture on database. (getDescription would be to get the picture description from a database handler, same for address and path)
However im getting the following error in the line where i use the "gets"
The constructor ClipData.Item(int, String, String, String) is undefined.
What could this be? Thank you!
Picture Class
public class Picture {
int _id;
String _name;
String _address;
String _description;
String _path;
// Empty constructor
public Picture(){
}
// constructor
public Picture(int id, String name, String _address, String _description, String _path){
this._id = id;
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// constructor
public Picture(String name, String _address, String _description){
this._name = name;
this._address = _address;
this._description = _description;
this._path = _path;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
public void setDescription(String description){
this._description = description;
}
public String getDescription(){
return this._description;
}
// getting phone number
public String getAddress(){
return this._address;
}
// setting phone number
public void setAddress(String phone_number){
this._address = phone_number;
}
public String getPath(){
return this._path;
}
public void setPath(String path){
this._path = path;
}
}
try to use for each loop
public static List<Item> getItemList(List<Picture> pictures, Context context)
{
List <Item> items = new ArrayList<Item>();
for (Picture pic:pictures) {
int id = pic.getID();
String address = pic.getAddress();
String desc= pic.getDescription();
String path= pic.getPath();
Item item = new Item(id ,address ,desc,path);
items.add(item);
}
return items;
}

Unable to parse Json array using Gson

I have this json array:
[
{
"id":18,
"city":"הרצליה",
"street":"החושלים 1",
"zipcode":121209,
"state":"IL",
"lat":32.158138,
"lng":34.807838
},
{
"id":19,
"city":"הרצליה",
"street":"אבא אבן 1",
"zipcode":76812,
"state":"IL",
"lat":32.161041,
"lng":34.810410
}
]
And i have this class to hold the data:
public class MapData {
private int id;
private String city;
private String street;
private String state;
private int zipcode;
private double lat;
private double lng;
public MapData(int id, String city, String street, String state,
int zipcode, double lat, double lng) {
this.id = id;
this.city = city;
this.street = street;
this.state = state;
this.zipcode = zipcode;
this.lat = lat;
this.lng = lng;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
}
I'm trying to convert the json into a List of MapData objects:
Type type = new TypeToken<List<MapData>>(){}.getType();
return gson.fromJson(jsonString, type);
But i get this error:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.deliveries.models.MapData
What am i doing wrong?
I suspect that the method calling fromJson is returning the wrong type. It should return a List<MapData> instead of MapData.
Something like:
public static List<MapData> getData(){
Gson gson = new Gson();
String jsonString = "[{\"id\":18,\"city\":\"test\",\"street\":\"test 1\",\"zipcode\":121209,\"state\":\"IL\",\"lat\":32.158138,\"lng\":34.807838},{\"id\":19,\"city\":\"test\",\"street\":\"1\",\"zipcode\":76812,\"state\":\"IL\",\"lat\":32.161041,\"lng\":34.810410}]";
Type type = new TypeToken<List<MapData>>(){}.getType();
return gson.fromJson(jsonString, type);
}
I have a fully working example of your issue in this Gist
string Json="some Json String";
JavaScriptSerializer Js = new JavaScriptSerializer();
MapData ObjMapDat = new MapData ();
ObjMapDat =Js.Deserialize<MapData>(Json);

Categories

Resources