Cannot put Parcelable into bundle - java

My question is fairly simple. I want to pass a List of objects from an Activity to a Fragment thanks to a bundle and Parcelable.
Basically, I make a simple retrofit call from the MainActivity, get a List of objects as an answer, then pass it to the fragment.
I've implemented parcelable to my object classes, but it's not working.
public class Result implements Parcelable {
// Variables
#SerializedName("geometry")
#Expose
private Geometry geometry;
#SerializedName("icon")
#Expose
private String icon;
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("opening_hours")
#Expose
private OpeningHours openingHours;
#SerializedName("photos")
#Expose
private List<Photo> photos = new ArrayList<Photo>();
#SerializedName("place_id")
#Expose
private String placeId;
#SerializedName("rating")
#Expose
private Double rating;
#SerializedName("reference")
#Expose
private String reference;
#SerializedName("scope")
#Expose
private String scope;
#SerializedName("types")
#Expose
private List<String> types = new ArrayList<String>();
#SerializedName("vicinity")
#Expose
private String vicinity;
#SerializedName("price_level")
#Expose
private Integer priceLevel;
// Constructor
public Result(Geometry geometry, String icon, String id, String name, OpeningHours openingHours, List<Photo> photos, String placeId, Double rating, String reference, String scope, List<String> types, String vicinity, Integer priceLevel) {
this.geometry = geometry;
this.icon = icon;
this.id = id;
this.name = name;
this.openingHours = openingHours;
this.photos = photos;
this.placeId = placeId;
this.rating = rating;
this.reference = reference;
this.scope = scope;
this.types = types;
this.vicinity = vicinity;
this.priceLevel = priceLevel;
}
// Getters & Setters
/**
*
* #return
* The geometry
*/
public Geometry getGeometry() {
return geometry;
}
/**
*
* #param geometry
* The geometry
*/
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
/**
*
* #return
* The icon
*/
public String getIcon() {
return icon;
}
/**
*
* #param icon
* The icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The openingHours
*/
public OpeningHours getOpeningHours() {
return openingHours;
}
/**
*
* #param openingHours
* The opening_hours
*/
public void setOpeningHours(OpeningHours openingHours) {
this.openingHours = openingHours;
}
/**
*
* #return
* The photos
*/
public List<Photo> getPhotos() {
return photos;
}
/**
*
* #param photos
* The photos
*/
public void setPhotos(List<Photo> photos) {
this.photos = photos;
}
/**
*
* #return
* The placeId
*/
public String getPlaceId() {
return placeId;
}
/**
*
* #param placeId
* The place_id
*/
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
/**
*
* #return
* The rating
*/
public Double getRating() {
return rating;
}
/**
*
* #param rating
* The rating
*/
public void setRating(Double rating) {
this.rating = rating;
}
/**
*
* #return
* The reference
*/
public String getReference() {
return reference;
}
/**
*
* #param reference
* The reference
*/
public void setReference(String reference) {
this.reference = reference;
}
/**
*
* #return
* The scope
*/
public String getScope() {
return scope;
}
/**
*
* #param scope
* The scope
*/
public void setScope(String scope) {
this.scope = scope;
}
/**
*
* #return
* The types
*/
public List<String> getTypes() {
return types;
}
/**
*
* #param types
* The types
*/
public void setTypes(List<String> types) {
this.types = types;
}
/**
*
* #return
* The vicinity
*/
public String getVicinity() {
return vicinity;
}
/**
*
* #param vicinity
* The vicinity
*/
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
/**
*
* #return
* The priceLevel
*/
public Integer getPriceLevel() {
return priceLevel;
}
/**
*
* #param priceLevel
* The price_level
*/
public void setPriceLevel(Integer priceLevel) {
this.priceLevel = priceLevel;
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.geometry, flags);
dest.writeString(this.icon);
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeParcelable(this.openingHours, flags);
dest.writeTypedList(this.photos);
dest.writeString(this.placeId);
dest.writeValue(this.rating);
dest.writeString(this.reference);
dest.writeString(this.scope);
dest.writeStringList(this.types);
dest.writeString(this.vicinity);
dest.writeValue(this.priceLevel);
}
protected Result(Parcel in) {
this.geometry = in.readParcelable(Geometry.class.getClassLoader());
this.icon = in.readString();
this.id = in.readString();
this.name = in.readString();
this.openingHours = in.readParcelable(OpeningHours.class.getClassLoader());
this.photos = in.createTypedArrayList(Photo.CREATOR);
this.placeId = in.readString();
this.rating = (Double) in.readValue(Double.class.getClassLoader());
this.reference = in.readString();
this.scope = in.readString();
this.types = in.createStringArrayList();
this.vicinity = in.readString();
this.priceLevel = (Integer) in.readValue(Integer.class.getClassLoader());
}
public static final Parcelable.Creator<Result> CREATOR = new Parcelable.Creator<Result>() {
#Override
public Result createFromParcel(Parcel source) {
return new Result(source);
}
#Override
public Result[] newArray(int size) {
return new Result[size];
}
};
}
And the MainActivity method call (simplified)
public void initRetrofitandCall(double latitude, double longitude, int PROXIMITY_RADIUS) {
GoogleApiInterface service = GoogleMapsClient.getClient().create(GoogleApiInterface.class);
Call<Example> call = service.getNearbyRestaurants("restaurant", latitude + "," + longitude, PROXIMITY_RADIUS);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
// Response List (working as intended)
List<Result> listTest = response.body().getResults();
Log.w("Nearby Restaurants", new GsonBuilder().setPrettyPrinting().create().toJson(listTest));
// Create bundle and put listTest in it (not working)
Bundle bundle = new Bundle();
bundle.putParcelable("valuesArray", listTest);
try {
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
bundle.putParcelable("valuesArray", listTest); says "wrong 2nd argument type required android.os.Parcelable
All my model classes implements Parcelable, I'm only showing the Result.class to not make the post too long. I also tried with the Serializable way, and I get the same kind of issues. As if Parcelable or Serializable are not implemented in my model classes.
Thank you a lot for any help than you can provide me with.

You need to use ParcelableArrayList to put the list into the bundle
bundle.putParcelableArrayList("valuesArray", listTest);

Add this to build.gradle
compile 'com.google.code.gson:gson:2.8.1'
convert your Arraylist to json using Gson and pass the json string as an argument to the fragment.
Bundle bundle = new Bundle();
bundle.putString("valuesArray", new Gson().toJson(listTest));
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and then retrive the list of result in fragment like this,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
List<Result> result = new Gson().fromJson(getArguments().getString("valuesArray"),
new TypeToken<List<Result>>(){}.getType());
return inflater.inflate(R.layout.fragment, container, false);
}

This work for me:
Intent intent = new Intent(YourActivity.this, YourFragment.class);
intent.putParcelableArrayListExtra(Utils.LIST_TEST, (ArrayList<? extends Parcelable>) listTest);

Related

Gson.fromJson(json, Custom.class) empty string

i'm developing a small web application.
That's my problem:
This is executed when a user try to add a new record in my Datatable
#RequestMapping(value="/saveJokerRule", method= RequestMethod.POST, consumes= "application/json", produces = "application/json")
#ResponseBody
public String saveJokerRule(#RequestBody String json) {
System.out.println("JSON EDITOR:" + json.toString());
EditorResponse editorResponse = new EditorResponse();
JokerRuleForm jokerRuleForm = new GsonBuilder().serializeNulls().create().fromJson(json, JokerRuleForm.class);
...
}
This is the valid json received by the server and printed by a System call:
{"action":"create","data":{"0":{"jokerRule":{"group":1,"campaignPhase":"","dailyLimit":"","weeklyLimit":"","monthlyLimit":"","validFrom":"","activity":1}}}}
That's the JokerRuleForm classs
public class JokerRuleForm {
#Expose
String action;
#Expose
#SerializedName("data")
Map<String, JokerRuleView> data;
...
}
That's the JokerRuleView class
public class JokerRuleView {
String idJokerRule;
private AgentGroup group;
private JokerRule jokerRule;
private Activity activity;
public class JokerRule{
private String campaignPhase;
private Integer dailyLimit;
private Integer weeklyLimit;
private Integer monthlyLimit;
private Date validFrom;
private Date dateUpdate;
private String group;
private String activity;
/**
* #return the campaignPhase
*/
public String getCampaignPhase() {
return campaignPhase;
}
/**
* #param campaignPhase the campaignPhase to set
*/
public void setCampaignPhase(String campaignPhase) {
this.campaignPhase = campaignPhase;
}
/**
* #return the dailyLimit
*/
public Integer getDailyLimit() {
return dailyLimit;
}
/**
* #param dailyLimit the dailyLimit to set
*/
public void setDailyLimit(Integer dailyLimit) {
this.dailyLimit = dailyLimit;
}
/**
* #return the weeklyLimit
*/
public Integer getWeeklyLimit() {
return weeklyLimit;
}
/**
* #param weeklyLimit the weeklyLimit to set
*/
public void setWeeklyLimit(Integer weeklyLimit) {
this.weeklyLimit = weeklyLimit;
}
/**
* #return the monthlyLimit
*/
public Integer getMonthlyLimit() {
return monthlyLimit;
}
/**
* #param monthlyLimit the monthlyLimit to set
*/
public void setMonthlyLimit(Integer monthlyLimit) {
this.monthlyLimit = monthlyLimit;
}
/**
* #return the validFrom
*/
public Date getValidFrom() {
return validFrom;
}
/**
* #param validFrom the validFrom to set
*/
public void setValidFrom(Date validFrom) {
this.validFrom = validFrom;
}
/**
* #return the dateUpdate
*/
public Date getDateUpdate() {
return dateUpdate;
}
/**
* #param dateUpdate the dateUpdate to set
*/
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
/**
* #return the group
*/
public String getGroup() {
return group;
}
/**
* #param group the group to set
*/
public void setGroup(String group) {
this.group = group;
}
/**
* #return the activity
*/
public String getActivity() {
return activity;
}
/**
* #param activity the activity to set
*/
public void setActivity(String activity) {
this.activity = activity;
}
}
public class Activity {
String idActivity;
String name;
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the idGroup
*/
public String getIdActivity() {
return idActivity;
}
/**
* #param idGroup the idGroup to set
*/
public void setIdActivity(String idActivity) {
this.idActivity = idActivity;
}
}
public class AgentGroup {
String idGroup;
String name;
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the idGroup
*/
public String getIdGroup() {
return idGroup;
}
/**
* #param idGroup the idGroup to set
*/
public void setIdGroup(String idGroup) {
this.idGroup = idGroup;
}
}
/**
* #return the idJokerRule
*/
public String getIdJokerRule() {
return idJokerRule;
}
/**
* #param idJokerRule the idJokerRule to set
*/
public void setIdJokerRule(String idJokerRule) {
this.idJokerRule = idJokerRule;
}
/**
* #return the agentGroup
*/
public AgentGroup getGroup() {
return group;
}
/**
* #param agentGroup the agentGroup to set
*/
public void setGroup(AgentGroup group) {
this.group = group;
}
/**
* #return the jokerRule
*/
public JokerRule getJokerRule() {
return jokerRule;
}
/**
* #param jokerRule the jokerRule to set
*/
public void setJokerRule(JokerRule jokerRule) {
this.jokerRule = jokerRule;
}
/**
* #return the activity
*/
public Activity getActivity() {
return activity;
}
/**
* #param activity the activity to set
*/
public void setActivity(Activity activity) {
this.activity = activity;
}
}
JokerRuleForm jokerRuleForm = new GsonBuilder().serializeNulls().create().fromJson(json, JokerRuleForm.class);
When executing this line i got a NumberFormatException empty string and i think it dailyLimit's or date's fault because it's empty and fromJson() method can't do what he need to do.
I've read something about a TypeAdapter that seems can fit to my case, but i don't really know how to proceed and i'm not sure is a valid solution.
Can someone help me?
The limit fields e.g. dailyLimit are empty strings in your JSON. This was suggested in JsonParseException when encountering an empty value for an int or long #472 issue but Gson team closed it because it makes no sense to parse "" as int.
One of the users provided a solution in his comment which allows to leniently parse the number values. I'd not go this route myself and fix JSON instead, but it's up to you:
public static final TypeAdapter<Number> UNRELIABLE_INTEGER = new TypeAdapter<Number>() {
#Override
public Number read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
switch (jsonToken) {
case NUMBER:
case STRING:
String s = in.nextString();
try {
return Integer.parseInt(s);
} catch (NumberFormatException ignored) {
}
try {
return (int)Double.parseDouble(s);
} catch (NumberFormatException ignored) {
}
return null;
case NULL:
in.nextNull();
return null;
case BOOLEAN:
in.nextBoolean();
return null;
default:
throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
}
}
#Override
public void write(JsonWriter out, Number value) throws IOException {
out.value(value);
}
};
public static final TypeAdapterFactory UNRELIABLE_INTEGER_FACTORY = TypeAdapters.newFactory(int.class, Integer.class, UNRELIABLE_INTEGER);
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(UNRELIABLE_INTEGER_FACTORY)
.create();

How to parse json data with retrofit on Android

ill try to be specific here. So i have created the most basic possible code just to test it and i am still unable to get the data, please help! Here is my code :
this is json output on my local server :
http://localhost:8080/KokosinjacRestfull/rest/textService/mudriPevci
[{"id":1,"subCategory":"MudriPevci","title":"Mujo i
haso","description":"Krenuli do
Grada","author":"luka","date":"2016-06-13"},{"id":3,"subCategory":"mudriPevci","title":"Perica","description":"Pa
on je napravio Haos","author":"luka","date":"2016-06-13"}]
Text.class :
package kokosinjac.com.digiart.koktest.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Text {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("subCategory")
#Expose
private String subCategory;
#SerializedName("title")
#Expose
private String title;
#SerializedName("description")
#Expose
private String description;
#SerializedName("author")
#Expose
private String author;
#SerializedName("date")
#Expose
private String date;
/**
* No args constructor for use in serialization
*
*/
/**
*
* #param id
* #param author
* #param title
* #param subCategory
* #param description
* #param date
*/
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* #return
* The subCategory
*/
public String getSubCategory() {
return subCategory;
}
/**
*
* #param subCategory
* The subCategory
*/
public void setSubCategory(String subCategory) {
this.subCategory = subCategory;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The description
*/
public String getDescription() {
return description;
}
/**
*
* #param description
* The description
*/
public void setDescription(String description) {
this.description = description;
}
/**
*
* #return
* The author
*/
public String getAuthor() {
return author;
}
/**
*
* #param author
* The author
*/
public void setAuthor(String author) {
this.author = author;
}
/**
*
* #return
* The date
*/
public String getDate() {
return date;
}
/**
*
* #param date
* The date
*/
public void setDate(String date) {
this.date = date;
}
}
Api interface.class :
package kokosinjac.com.digiart.koktest.retrofit;
import java.util.ArrayList;
import kokosinjac.com.digiart.koktest.models.Text; import
retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path;
public interface RetrofitAPInterface {
#GET("rest/textService/{subCategory}")
Call<ArrayList<Text>> getText(#Path("subCategory") String subCat);
}
class that displays data on the phone (you do not need to pay attention on some Strings, just look at the retrofit part,i;ve made it as simple as i can,
subCatData.class:
public static final String BASE_URL ="http://localhost:8080/KokosinjacRestfull/";
HashMap<String,String> dataArr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_cat_data);
final TextView tView = (TextView) findViewById(R.id.textView);
Intent intent = getIntent();
String urlSecondPartBefore = intent.getStringExtra("passedSubCat");
String urlSecondPartAfter = urlSecondPartBefore.replaceAll("\\s", "");
String urlFirstPart = intent.getStringExtra("passedUrlFirstPart");
String catName = intent.getStringExtra("passedCatName");
String data = null;
// TextView test = (TextView) findViewById(R.id.test);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitAPInterface apiService = retrofit.create(RetrofitAPInterface.class);
Call<ArrayList<Text>> call = apiService.getText("mudriPevci");
call.enqueue(new Callback<ArrayList<Text>>() {
#Override
public void onResponse(Call<ArrayList<Text>> call, Response<ArrayList<Text>> response) {
int statusCode = response.code();
ArrayList<Text> textArray = response.body();
for (Text t : textArray){
tView.setText(t.getDescription());
}
// Log.i("DATA", "onResponse: "+text.getId());
}
#Override
public void onFailure(Call<ArrayList<Text>> call, Throwable t) {
}
});
}
}
I am aware that the whole bunch of data is going to a simple label , but it is for testing purposes. Still i can not retrieve anything and i do not get any errors as well. Help would be much appreciated. Thanks!
I think problem with your URL if you are testing your App with android emulator then try like "http://10.0.2.2:8080/" . but if you are testing with device then you need to pass Your machine IP address like "http://192.143.1.0/". and make sure that your device is connected with your machine on which your database is exits.
To parse JSON data on Android I highly recommend using JSOUP which you can find by clicking here it is simple, straight forward, and user friendly. Very easy to learn. Hope this helps you!
The problem might be in your BASE_URL Change your BASE_URL to
BASE_URL ="http://<your_local_ip_address>/KokosinjacRestfull/";
i hope the below example might help
public void startFetching() {
mApiManager.getFlowerApi().getFlowers(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Flower flower = new Flower.Builder()
.setCategory(object.getString("category"))
.setPrice(object.getDouble("price"))
.setInstructions(object.getString("instructions"))
.setPhoto(object.getString("photo"))
.setName(object.getString("name"))
.setProductId(object.getInt("productId"))
.build();
mListener.onFetchProgress(flower);
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
the problem is with your URL Android can't hit your localhost ie http://localhost:8080/KokosinjacRestfull/rest/textService/mudriPevci
up your server in specific IP and the run.The new IP would be like
http://192.168.1.1/KokosinjacRestfull/rest/textService/mudriPevci
use ip address instead of localhost (replace localhost from url and place your computer's ipaddress for ip address open cmd and type ipconfig and replace localhost).

Volley parsing Json response is null Android

I am trying to parse JSON Object using volley but it is giving all the values as null
I am using GsonRequest custom class to parse using GSON library
public class GsonRequest < T > extends JsonRequest < T > {
/** Charset for request. */
private static final String PROTOCOL_CHARSET = "utf-8";
/** Content type for request. */
private static final String PROTOCOL_CONTENT_TYPE = String.format("application/json; charset=%s", PROTOCOL_CHARSET);
private final Gson mGson;
//private final String mBody;
private final Class < T > clazz;
private final Listener < T > listener;
private final Map < String,
String > headers;
private final String mBody;
public GsonRequest(int method, String url, String body, Class < T > clazz, Map < String, String > headers, Response.Listener < T > listener, Response.ErrorListener errorListener) {
super(method, url, (body == null) ? null: body, listener, errorListener);
this.clazz = clazz;
this.mBody = body;
this.headers = headers;
this.listener = listener;
mGson = new Gson();
}#Override
public Map < String,
String > getHeaders() throws AuthFailureError {
return headers != null ? headers: super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response < T > parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(mGson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
} catch(UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch(JsonSyntaxException e) {
Log.e("JsonSyntaxException", " " + e);
return Response.error(new ParseError(e));
}
}
}
I have created model class using http://www.jsonschema2pojo.org/ below is my model class
public class ModelConnection {
private List < Datum > data = new ArrayList < Datum > ();
private Integer code;
private Object message;
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The data
*/
public List < Datum > getData() {
return data;
}
/**
*
* #param data
* The Data
*/
public void setData(List < Datum > data) {
this.data = data;
}
/**
*
* #return
* The code
*/
public Integer getCode() {
return code;
}
/**
*
* #param code
* The Code
*/
public void setCode(Integer code) {
this.code = code;
}
/**
*
* #return
* The message
*/
public Object getMessage() {
return message;
}
/**
*
* #param message
* The Message
*/
public void setMessage(Object message) {
this.message = message;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public class Datum {
private Integer userID;
private String firstName;
private String lastName;
private String title;
private String organization;
private String industry;
private String location;
private String profileSummary;
private String imagePath;
private List < Object > interests = new ArrayList < Object > ();
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The userID
*/
public Integer getUserID() {
return userID;
}
/**
*
* #param userID
* The UserID
*/
public void setUserID(Integer userID) {
this.userID = userID;
}
/**
*
* #return
* The firstName
*/
public String getFirstName() {
return firstName;
}
/**
*
* #param firstName
* The FirstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* #return
* The lastName
*/
public String getLastName() {
return lastName;
}
/**
*
* #param lastName
* The LastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The organization
*/
public String getOrganization() {
return organization;
}
/**
*
* #param organization
* The Organization
*/
public void setOrganization(String organization) {
this.organization = organization;
}
/**
*
* #return
* The industry
*/
public String getIndustry() {
return industry;
}
/**
*
* #param industry
* The Industry
*/
public void setIndustry(String industry) {
this.industry = industry;
}
/**
*
* #return
* The location
*/
public String getLocation() {
return location;
}
/**
*
* #param location
* The Location
*/
public void setLocation(String location) {
this.location = location;
}
/**
*
* #return
* The profileSummary
*/
public String getProfileSummary() {
return profileSummary;
}
/**
*
* #param profileSummary
* The ProfileSummary
*/
public void setProfileSummary(String profileSummary) {
this.profileSummary = profileSummary;
}
/**
*
* #return
* The imagePath
*/
public String getImagePath() {
return imagePath;
}
/**
*
* #param imagePath
* The ImagePath
*/
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
/**
*
* #return
* The interests
*/
public List < Object > getInterests() {
return interests;
}
/**
*
* #param interests
* The Interests
*/
public void setInterests(List < Object > interests) {
this.interests = interests;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
}
This is the response from rest client
{
-"Data": [2]
-0: {
"UserID": 124
"FirstName": "Mixer"
"LastName": "Development"
"Title": "Flipdex Architect "
"Organization": "CoStrategix"
"Industry": "Software "
"Location": "Bengaluru Area, India"
"ProfileSummary": "Mixer#^*+~|Software engineer?????????? 123456789"#&$)(;:/-.,?!ASDFZgZhXjZkZlZXCVZbNZmQWERTYUIOZp[]{}#%^*+¥£€><~|\_.,?! "
"ImagePath": "https://media.licdn.com/mpr/mprx/0_tiUBxkxpFtDhAIKrczfJBnzj6FMhlWiAOiiJJAUpF8YTlJayP3DBA3Mp5NrycIrrczfJ48nymk-3-DwljKYwBKBKIk-8-DErYKYNylCgh5F24Rlu-3HVpLuuwAHKUDj3c1VURiTsxsU"
"Interests": [0]
}
-1: {
"UserID": 153
"FirstName": "Mixer"
"LastName": "Android"
"Title": "Assistant Manager at CoStrategix"
"Organization": "CoStrategix"
"Industry": "Software"
"Location": "Bengaluru Area, India"
"ProfileSummary": "We have worked with over 35+ product companies and bring the critical thinking and technology expertise to launching your product. We have l"
"ImagePath": "https://media.licdn.com/mpr/mprx/0_0EwKKqh9nkV0X1t3pmPYj6B9ncH0T_TTJy0K9h29KnTYT1u8zElOR_C9q3zGb1gDJyjY4_SnOQUOGFf8zJmuZhhsUQUxGFHTzJmPP3zBKbm1HA1jMe4j1vRQR1T7wFxKysoyq1W3CaQ"
"Interests": [0]
}
"Code": 1
"Message": null
}
finally this is the way I am calling the api
GsonRequest request = new GsonRequest(Request.Method.GET, newConnectionAPI,null, ModelConnection.class, getHeaders(),
new Response.Listener<ModelConnection>() {
#Override
public void onResponse(ModelConnection response) {
if (listener != null) {
listener.networkResponseSuccessful(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("volley error", "" + error);
}
});
request.setTag(tag);
request.setRetryPolicy(new DefaultRetryPolicy(15000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
when I debug I get all the values as null
Can anyone please help me out
Thought of answering my own question, may be someone can get help through this...
I created my Model class using jsonschema2pojo where I had to select JSON along with GSON(Which I forgot to select).
you can see the difference if you compare the Model classes posted above and below
public class ModelConnection {
#SerializedName("Data")#Expose
private List < Datum > data = new ArrayList < Datum > ();#SerializedName("Code")#Expose
private Integer code;#SerializedName("Message")#Expose
private Object message;
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The data
*/
public List < Datum > getData() {
return data;
}
/**
*
* #param data
* The Data
*/
public void setData(List < Datum > data) {
this.data = data;
}
/**
*
* #return
* The code
*/
public Integer getCode() {
return code;
}
/**
*
* #param code
* The Code
*/
public void setCode(Integer code) {
this.code = code;
}
/**
*
* #return
* The message
*/
public Object getMessage() {
return message;
}
/**
*
* #param message
* The Message
*/
public void setMessage(Object message) {
this.message = message;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public class Datum implements Serializable {
#SerializedName("UserId")#Expose
private Integer userID;#SerializedName("FirstName")#Expose
private String firstName;#SerializedName("LastName")#Expose
private String lastName;#SerializedName("Title")#Expose
private String title;#SerializedName("Organization")#Expose
private String organization;#SerializedName("Industry")#Expose
private String industry;#SerializedName("Location")#Expose
private String location;#SerializedName("ProfileSummary")#Expose
private String profileSummary;#SerializedName("ImagePath")#Expose
private String imagePath;#SerializedName("Interests")#Expose
private ArrayList < Interest > interest = new ArrayList < Interest > ();
private Map < String,
Object > additionalProperties = new HashMap < String,
Object > ();
/**
*
* #return
* The userID
*/
public Integer getUserID() {
return userID;
}
/**
*
* #param userID
* The UserID
*/
public void setUserID(Integer userID) {
this.userID = userID;
}
/**
*
* #return
* The firstName
*/
public String getFirstName() {
return firstName;
}
/**
*
* #param firstName
* The FirstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* #return
* The lastName
*/
public String getLastName() {
return lastName;
}
/**
*
* #param lastName
* The LastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The organization
*/
public String getOrganization() {
return organization;
}
/**
*
* #param organization
* The Organization
*/
public void setOrganization(String organization) {
this.organization = organization;
}
/**
*
* #return
* The industry
*/
public String getIndustry() {
return industry;
}
/**
*
* #param industry
* The Industry
*/
public void setIndustry(String industry) {
this.industry = industry;
}
/**
*
* #return
* The location
*/
public String getLocation() {
return location;
}
/**
*
* #param location
* The Location
*/
public void setLocation(String location) {
this.location = location;
}
/**
*
* #return
* The profileSummary
*/
public String getProfileSummary() {
return profileSummary;
}
/**
*
* #param profileSummary
* The ProfileSummary
*/
public void setProfileSummary(String profileSummary) {
this.profileSummary = profileSummary;
}
/**
*
* #return
* The imagePath
*/
public String getImagePath() {
return imagePath;
}
/**
*
* #param imagePath
* The ImagePath
*/
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
/**
*
* #return
* The interests
*/
public ArrayList < Interest > getInterest() {
return interest;
}
/**
*
* #param interests
* The Interests
*/
public void setInterest(ArrayList < Interest > interests) {
this.interest = interests;
}
public Map < String,
Object > getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
public class Interest {
#SerializedName("Name")#Expose
private String name;
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The Name
*/
public void setName(String name) {
this.name = name;
}
}
}
May be because the objects were not properly serialized so GSON was unable to parse the JSON String properly.
Others advice over the above assumption is most welcome.

passing custom object in retrofit2

i am trying to pass a custom object via retrofit2, and my question is that does the server writes my custom object to json automatically or do i have to write a php file for that. In the meanwhile I am posting successfully to the server but unable to write to json.
My aim is to write custom object to server, and write the contents of custom objects to json file.
Here is my Retrofit Api
public interface ApsaraCatalogAPI {
#GET("/apsaratrendz/data/apsara_json_document_v2.json")
Call<List<ApsaraCatalogModel>> getFeed();
#POST("/apsaratrendz/data/apsara_json_orders_document.json")
Call<Void> setOrder(#Body OrderModel orderModel);
}
Here is my calling api function
#Override
public void onClick(View v) {
int total = 0;
if(v.getId()==R.id.fabButtonCart && cartlist.size()!=0)
{
// get details from shared preferences
OrderModel orderModel = new OrderModel();
orderModel.setDate(getDate());
orderModel.setName("ssdfs");
orderModel.setEmail("sdf#gmail.com");
orderModel.setNoofitems(String.valueOf(cartlist.size()));
orderModel.setOrderno("32335");
orderModel.setPhone("9896566444");
for(int i=0; i<cartlist.size();i++){
Productdetail pd = new Productdetail();
pd.getSellingprice(String.valueOf(cartlist.get(i).getSellingPrice()));
pd.getPid(cartlist.get(i).getEANCode());
total += cartlist.get(i).getSellingPrice();
orderModel.getProductdetails().add(pd);
}
//
// now go for insertion using retrofit
requestData(orderModel);
Toast.makeText(getApplicationContext(), "Total Price : Rs."+total+"/-", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Cart is Empty", Toast.LENGTH_LONG).show();
}
}
And here is my service request for retrofit api, I am passing the newly created POJO OrderModel class.
private void requestData(OrderModel orderModel) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApsaraCatalogAPI service = retrofit.create(ApsaraCatalogAPI.class);
Call<Void> call = service.setOrder(orderModel);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if(response.isSuccessful()){
Log.d("InApi","Yipppie");
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
Log.d("InApi","Kaboom");
}
});
}
My POJO Class is given below:
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class OrderModel {
private String name;
private String email;
private String phone;
private String orderno;
private String date;
private String noofitems;
private List<Productdetail> productdetails = new ArrayList<Productdetail>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* #param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* #return
* The phone
*/
public String getPhone() {
return phone;
}
/**
*
* #param phone
* The phone
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
*
* #return
* The orderno
*/
public String getOrderno() {
return orderno;
}
/**
*
* #param orderno
* The orderno
*/
public void setOrderno(String orderno) {
this.orderno = orderno;
}
/**
*
* #return
* The date
*/
public String getDate() {
return date;
}
/**
*
* #param date
* The date
*/
public void setDate(String date) {
this.date = date;
}
/**
*
* #return
* The noofitems
*/
public String getNoofitems() {
return noofitems;
}
/**
*
* #param noofitems
* The noofitems
*/
public void setNoofitems(String noofitems) {
this.noofitems = noofitems;
}
/**
*
* #return
* The productdetails
*/
public List<Productdetail> getProductdetails() {
return productdetails;
}
/**
*
* #param productdetails
* The productdetails
*/
public void setProductdetails(List<Productdetail> productdetails) {
this.productdetails = productdetails;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
productdetails class :
import java.util.HashMap;
import java.util.Map;
public class Productdetail {
private String pid;
private String sellingprice;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The pid
* #param s
*/
public String getPid(String s) {
return pid;
}
/**
*
* #param pid
* The pid
*/
public void setPid(String pid) {
this.pid = pid;
}
/**
*
* #return
* The sellingprice
* #param s
*/
public String getSellingprice(String s) {
return sellingprice;
}
/**
*
* #param sellingprice
* The sellingprice
*/
public void setSellingprice(String sellingprice) {
this.sellingprice = sellingprice;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Retrofit generates the json based on your POJO and set it on the post payload.
So, in this case:
#POST("/apsaratrendz/data/apsara_json_orders_document.json")
Call<Void> setOrder(#Body OrderModel orderModel);
the body of the post will be a json representation of orderModel.
If you need to change the names of the atributtes generated in the json you can use SerializedName Annotation, its very useful:
public class OrderModel {
#SerializedName("other_name_for_json")
private String name;
Hope it helps.

Having trouble using strings outside of Volley request onResponse

I have a search dialog in my MainActivity that when used sends the user query to a SearchActivity. From there I send a JSON request using volley and then deserialize the JSON using GSON. all of this is working good and I can even print, for an example, the latitude value of my request using:
System.out.println(cam[0].getLat());
However, all of this must be done within the onResponse of the volley request. I'm trying to send some of the values back to my MainActivity which I know how to do already. I just need to know how to store some of the strings so that I can access them outside of onResponse.
Method that sends request and deserializes it:
private void fetchJsonResponse() {
JsonArrayRequest req = new JsonArrayRequest(myUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Gson gson = new Gson();
String nominatimData = response.toString();
NominatimModel[] cam = gson.fromJson(nominatimData, NominatimModel[].class);
// i'd like to using cam[0].getLat(); outside of this method
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
mRequestQueue.add(req);
}
NominatimModel.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class NominatimModel {
#SerializedName("place_id")
#Expose
private String placeId;
#Expose
private String licence;
#SerializedName("osm_type")
#Expose
private String osmType;
#SerializedName("osm_id")
#Expose
private String osmId;
#Expose
private List<String> boundingbox = new ArrayList<String>();
#Expose
private String lat;
#Expose
private String lon;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("class")
#Expose
private String _class;
#Expose
private String type;
#Expose
private Double importance;
#Expose
private String icon;
/**
* #return The placeId
*/
public String getPlaceId() {
return placeId;
}
/**
* #param placeId The place_id
*/
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
/**
* #return The licence
*/
public String getLicence() {
return licence;
}
/**
* #param licence The licence
*/
public void setLicence(String licence) {
this.licence = licence;
}
/**
* #return The osmType
*/
public String getOsmType() {
return osmType;
}
/**
* #param osmType The osm_type
*/
public void setOsmType(String osmType) {
this.osmType = osmType;
}
/**
* #return The osmId
*/
public String getOsmId() {
return osmId;
}
/**
* #param osmId The osm_id
*/
public void setOsmId(String osmId) {
this.osmId = osmId;
}
/**
* #return The boundingbox
*/
public List<String> getBoundingbox() {
return boundingbox;
}
/**
* #param boundingbox The boundingbox
*/
public void setBoundingbox(List<String> boundingbox) {
this.boundingbox = boundingbox;
}
/**
* #return The lat
*/
public String getLat() {
return lat;
}
/**
* #param lat The lat
*/
public void setLat(String lat) {
this.lat = lat;
}
/**
* #return The lon
*/
public String getLon() {
return lon;
}
/**
* #param lon The lon
*/
public void setLon(String lon) {
this.lon = lon;
}
/**
* #return The displayName
*/
public String getDisplayName() {
return displayName;
}
/**
* #param displayName The display_name
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* #return The _class
*/
public String getClass_() {
return _class;
}
/**
* #param _class The class
*/
public void setClass_(String _class) {
this._class = _class;
}
/**
* #return The type
*/
public String getType() {
return type;
}
/**
* #param type The type
*/
public void setType(String type) {
this.type = type;
}
/**
* #return The importance
*/
public Double getImportance() {
return importance;
}
/**
* #param importance The importance
*/
public void setImportance(Double importance) {
this.importance = importance;
}
/**
* #return The icon
*/
public String getIcon() {
return icon;
}
/**
* #param icon The icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
}
Example JSON:
[{"place_id":"115063146","licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright","osm_type":"way","osm_id":"258132245","boundingbox":["29.7156836","29.7278762","-95.3520172","-95.3349753"],"lat":"29.7214917","lon":"-95.3440202128152","display_name":"University of Houston, 4800, Calhoun Road, Houston, Harris County, Texas, 77004, United States of America","class":"amenity","type":"university","importance":0.84733963787614,"icon":"http:\/\/nominatim.openstreetmap.org\/images\/mapicons\/education_university.p.20.png"}]
I'm fairly new to java and Android development so if someone can help me out a bit i'd appreciate it and if I left out any information let me know.
Figured I'd answer this question now that time has passed and I've learned a ton about Android, including how to accomplish this. So I had all my models implement Serializable, and then just bundled the response data and passed it to the other activity. I later, got rid of this and was able to accomplish everything I needed within the onResponse.
I'd steer away from using Serializable if you must do what I was trying to accomplish and instead check out the Parcelable interface, it has the advantage of being faster.
Hope this helps to anyone who comes across this question!

Categories