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);
Related
java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
i have tried for the last 2 hours to update the coordinates but it ain't working keeps throwing this error
java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
at retrofit2.Utils.methodError(Utils.java:52)
at retrofit2.Utils.methodError(Utils.java:42)
at retrofit2.RequestFactory$Builder.parseHttpMethodAndPath(RequestFactory.java:251)
at retrofit2.RequestFactory$Builder.parseMethodAnnotation(RequestFactory.java:224)
at retrofit2.RequestFactory$Builder.build(RequestFactory.java:171)
at retrofit2.RequestFactory.parseAnnotations(RequestFactory.java:67)
at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:26)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)
at retrofit2.Retrofit$1.invoke(Retrofit.java:149)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy0.UpdateCoordinates(Unknown Source)
at com.example.charlo.jkuat_mobile_app.util.LocationService$1.onLocationResult(LocationService.java:54)
Model classes
the update model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GpsUpdate {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("data")
#Expose
private Data data;
#SerializedName("message")
#Expose
private String message;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
model class
the data model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("driverid")
#Expose
private Integer driverid;
#SerializedName("companyid")
#Expose
private Integer companyid;
#SerializedName("vehicleid")
#Expose
private Integer vehicleid;
#SerializedName("warehouseid")
#Expose
private Integer warehouseid;
#SerializedName("orders")
#Expose
private Integer orders;
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("latitute")
#Expose
private String latitute;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("tripdate")
#Expose
private String tripdate;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
public Data(String latitute, String longitude) {
this.latitute = latitute;
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDriverid() {
return driverid;
}
public void setDriverid(Integer driverid) {
this.driverid = driverid;
}
public Integer getCompanyid() {
return companyid;
}
public void setCompanyid(Integer companyid) {
this.companyid = companyid;
}
public Integer getVehicleid() {
return vehicleid;
}
public void setVehicleid(Integer vehicleid) {
this.vehicleid = vehicleid;
}
public Integer getWarehouseid() {
return warehouseid;
}
public void setWarehouseid(Integer warehouseid) {
this.warehouseid = warehouseid;
}
public Integer getOrders() {
return orders;
}
public void setOrders(Integer orders) {
this.orders = orders;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getLatitute() {
return latitute;
}
public void setLatitute(String latitute) {
this.latitute = latitute;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getTripdate() {
return tripdate;
}
public void setTripdate(String tripdate) {
this.tripdate = tripdate;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
}
Interface
interface class
#PUT("update_driver/{dispatchid}?")
Call<GpsUpdate> UpdateCoordinates(#Path("dispatchid") int id, #Field("latitude") String latitude, #Field("longitude") String longitude );
location service class
the update class which sends the coordinates to the backend
#Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = ApiClient.createService(ApiInterface.class);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
double lat = locationResult.getLastLocation().getLatitude();
double lng = locationResult.getLastLocation().getLongitude();
String latitude = String.valueOf(lat);
String longitude = String.valueOf(lng);
Data data = new Data(latitude,longitude);
Call<GpsUpdate> call = service.UpdateCoordinates(tokenManager.getToken().getDispatchid(),data.getLatitute(), data.getLongitude());
call.enqueue(new Callback<GpsUpdate>() {
#Override
public void onResponse(Call<GpsUpdate> call, Response<GpsUpdate> response) {
}
#Override
public void onFailure(Call<GpsUpdate> call, Throwable t) {
}
});
I think I should have marked this as a duplicate:
Retrofit: how fix "only one http method is allowed. found: get and get"?
Try changing the
#Path("dispatchid") int id
to
#Path("dispatchid") int dispatchid
How to post JSON array using retrofit2 in Android?
here i attatch format of data
{
"lat": 11.024,
"lon": 75.054,
"maxdistance": 5000,
"amintyArray": [
"5ad251cfe601aa22a8f48d98",
"5ad251dae601aa22a8f48d99",
"5ad251ece601aa22a8f48d9a"
],
"starArray": [
"5ad252b1e601aa22a8f48db1"
]
}
pojo class like blow..
public class Example {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lon")
#Expose
private Double lon;
#SerializedName("maxdistance")
#Expose
private Integer maxdistance;
#SerializedName("amintyArray")
#Expose
private List<String> amintyArray = null;
#SerializedName("starArray")
#Expose
private List<String> starArray = null;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Integer getMaxdistance() {
return maxdistance;
}
public void setMaxdistance(Integer maxdistance) {
this.maxdistance = maxdistance;
}
public List<String> getAmintyArray() {
return amintyArray;
}
public void setAmintyArray(List<String> amintyArray) {
this.amintyArray = amintyArray;
}
public List<String> getStarArray() {
return starArray;
}
public void setStarArray(List<String> starArray) {
this.starArray = starArray;
}
}
make request pojo class like below it define array or single value..
public class JsonData {
#SerializedName("createdAt")
private long createdAt;
#SerializedName("firstName")
private String firstName;
#SerializedName("password")
private String password;
#SerializedName("users")
private List<User> users;
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
after that make api for requesting ..
#POST("linke")
Call<Response> passJsonData(#Body JsonData jsonData);
after insert data into Json data object then pass only json data.
The result variable contains corrected parsed JSON.
But after deserialization List contains correct amount of items but all of them are empty.
How to fix it?
Gson gson = new Gson();
List<UnitView> unitViews = new ArrayList<UnitView>();
// https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type
Type typeToken = new TypeToken<List<UnitView>>() { }.getType();
unitViews = gson.fromJson(result,typeToken);
Even if I do like
UnitView[] unitViews = gson.fromJson(result, UnitView[].class);
The fields of items are empty as well.
UnitView
public class UnitView implements Serializable {
public String id ;
public String name ;
public String description ;
public String deviceTypeName ;
public String categoryID ;
public String lastOnline ;
public String latitude ;
public String longitude ;
public String atTime ;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getDeviceTypeName() {
return deviceTypeName;
}
public String getCategoryID() {
return categoryID;
}
public String getLastOnline() {
return lastOnline;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public String getAtTime() {
return atTime;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setDeviceTypeName(String deviceTypeName) {
this.deviceTypeName = deviceTypeName;
}
public void setCategoryID(String categoryID) {
this.categoryID = categoryID;
}
public void setLastOnline(String lastOnline) {
this.lastOnline = lastOnline;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public void setAtTime(String atTime) {
this.atTime = atTime;
}
}
JSON DATA
[{"ID":"294","Name":"Foton Tunland № F110","Description":null,"DeviceTypeName":"Техника ТО","CategoryID":"18","LastOnline":"19.12.2017 20:38:04","Latitude":"11,40119","Longitude":"11,42403","AtTime":"19.12.2017 20:38:04"},{"ID":"295","Name":"DML LP1200 № 9793","Description":null,"DeviceTypeName":"Буровой станок дизельный","CategoryID":"15","LastOnline":null,"Latitude":null,"Longitude":null,"AtTime":null}]
Ok , the problem is that the parser is case-sensitive, you can change the name of your attributes to match the name of the json value of you could use the SerializedName annotation like this:
#SerializedName("ID")
public String id ;
#SerializedName("Name")
public String name ;
#SerializedName("Description")
public String description;
...
or
public String ID ;
public String Name ;
public String Description ;
...
I think you're having this problem because of null values in your json.
Check it. Source
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.
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.