java.lang.RuntimeException: Parcelable encountered IOException writing
serializable object (name = com.luzian.recipeapp.Recipe)
I've already searched for answers for this problem but they all seem to be fixed by letting both classes implement from Serializable - which I'm doing - without success.
My two Classes Recipe and Ingredient:
public class Recipe implements Serializable
{
private String name;
private String time;
private String instructions;
private ArrayList<Ingredient> ingredients;
public Recipe(String name, String time, String instructions, ArrayList<Ingredient> ingredients)
{
this.name = name;
this.time = time;
this.instructions = instructions;
this.ingredients = ingredients;
}
}
public class Ingredient implements Serializable
{
private String value;
private String unit;
private String name;
public Ingredient(String value, String unit, String name)
{
this.value = value;
this.unit = unit;
this.name = name;
}
}
Starting new Activity:
Intent intent = new Intent(context, RecipeDisplayActivity.class);
intent.putExtra("recipe", recipes.get(position)); // recipes.get(position) returns a Recipe object
context.startActivity(intent);
I changed the Serializable to Parcelable and overwrote to required methods - Now it works!
Thanks #Swayangjit
public class Recipe implements Parcelable
{
private String name;
private String time;
private String instructions;
private ArrayList<Ingredient> ingredients;
public Recipe(String name, String time, String instructions, ArrayList<Ingredient> ingredients)
{
this.name = name;
this.time = time;
this.instructions = instructions;
this.ingredients = ingredients;
}
protected Recipe(Parcel in)
{
name = in.readString();
time = in.readString();
instructions = in.readString();
ingredients = in.readArrayList(Ingredient.class.getClassLoader());
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>()
{
#Override
public Recipe createFromParcel(Parcel in)
{
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size)
{
return new Recipe[size];
}
};
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(name);
dest.writeString(time);
dest.writeString(instructions);
dest.writeList(ingredients);
}
}
public class Ingredient implements Parcelable
{
private String value;
private String unit;
private String name;
public Ingredient(String value, String unit, String name)
{
this.value = value;
this.unit = unit;
this.name = name;
}
protected Ingredient(Parcel in)
{
value = in.readString();
unit = in.readString();
name = in.readString();
}
public static final Creator<Ingredient> CREATOR = new Creator<Ingredient>()
{
#Override
public Ingredient createFromParcel(Parcel in)
{
return new Ingredient(in);
}
#Override
public Ingredient[] newArray(int size)
{
return new Ingredient[size];
}
};
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(value);
dest.writeString(unit);
dest.writeString(name);
}
}
Related
I have 3 classes: MainActivity, homePage and createPage; and a list List<Recipe> recipeList = new ArrayList<>() in MainActivity.
The user enters the homePage from the MainActivity. From homePage, the user can enter createPage and create a new recipe. This new recipe is intended to be passed back to MainActivity.
I've searched online and came across parcels. But when I tried, I get a NullPointerException.
Code for createPage where the list is passed on
ArrayList<Recipe> rList = new ArrayList<>();
Recipe r = new Recipe(...);
rList.add(r)
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelableArrayList("recipe", (ArrayList<? extends Parcelable>) rList);
i.putExtras(b);
i.setClass(createPage.this, homePage.class);
startActivity(i);
Code for homePage where the list is received.
Is there something wrong with the getIntent()? Because when moving from MainActivity to homePage, it doesn't receive a bundle. Is this causing the error?
Intent intent = getIntent();
Bundle b = this.getIntent().getExtras();
if (b != null) {
Recipe r = b.getParcelable("recipe");
recipeList.add(r);
}
Code for Recipe class
public class Recipe implements Parcelable {
private String name;
private String description;
private String ingredients;
private int duration;
private String steps;
private int thumbnail;
protected Recipe(Parcel in) {
name = in.readString();
description = in.readString();
ingredients = in.readString();
duration = in.readInt();
steps = in.readString();
thumbnail = in.readInt();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getSteps() { return steps; }
public void setSteps(String steps) { this.steps = steps; }
public int getThumbnail() { return thumbnail; }
public Recipe() {}
public Recipe(String name, int duration, String ingredients, String description, String steps, int thumbnail) {
this.name = name;
this.description = description;
this.ingredients = ingredients;
this.duration = duration;
this.steps = steps;
this.thumbnail = thumbnail;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(description);
parcel.writeString(ingredients);
parcel.writeInt(duration);
parcel.writeString(steps);
parcel.writeInt(thumbnail);
}
}
you are writing into Parcelable whole array under "recipe" key
b.putParcelableArrayList("recipe", (ArrayList<? extends Parcelable>) rList);
but on onther side you are looking not for list but for single Recipe item under same key
Recipe r = b.getParcelable("recipe");
you should use getParcelableArrayList or if you have only one Recipe for passing to another Activity just use putParcelable (not list)
Alternatively you can use serializable, that will be less complex.
For reference : https://stackoverflow.com/a/2736612/9502601
Eventhough parcellables are more faster but if you want a less complex solution then you can go for it.
For Comparison between Serializable and Parcelable.
https://stackoverflow.com/a/23647471/9502601
You can use this gson Lib for this
implementation 'com.google.code.gson:gson:2.8.9'
Send Data with Intent
Recipe r = new Recipe(...);
String recipeString = new Gson().toJson(r);
intent.putExtra("recipe",recipeString);
// For ArrayList
ArrayList<Recipe> recipeList = new ArrayList<>();
String recipeString = new Gson().toJson(recipeList);
intent.putExtra("recipeList",recipeString);
Receive Data From Intent
Recipe r = new Gson().fromJson(intent.getStringExtra("recipe"), Recipe.class);
// For Array List
Type listType = new TypeToken<ArrayList<Recipe>>(){}.getType();
ArrayList<Recipe> recipeList = new Gson().fromJson(intent.getStringExtra("recipeList"),listType);
I'm using ParseSDK for android project. But I have a problem to access List of ParseObjects from another ParseObject class. I tried a lot of things, but anything didn't help me. Below I put my code.
Team team;
List<User> members = team.getMembers();
for(User user : members) {
user.getName();
}
#ParseClassName("Team")
public class Team extends ParseObject {
public static class Constant {
private static final String CREATED_BY = "createdBy";
private static final String NAME = "name";
public static final String CODE = "code";
private static final String PARTICIPANTS = "participants";
public static final String IS_ACTIVE = "isActive";
}
private String name;
private String code;
private User createdBy;
private List<User> members;
private int isActive;
public String getName() {
return getString(Constant.NAME);
}
public void setName(String name) {
this.name = name;
put(Constant.NAME, name);
}
public String getCode() {
return getString(Constant.CODE);
}
public void setCode(String code) {
this.code = code;
put(Constant.CODE, code);
}
public User getCreatedBy() {
return (User) getParseUser(Constant.CREATED_BY);
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
put(Constant.CREATED_BY, createdBy);
}
public List<User> getMembers() {
return getList(Constant.PARTICIPANTS);
}
public void setMembers(List<User> members) {
this.members = members;
put(Constant.PARTICIPANTS, members);
}
public int getIsActive() {
return getInt(Constant.IS_ACTIVE);
}
public void setIsActive(int isActive) {
this.isActive = isActive;
put(Constant.IS_ACTIVE, isActive);
}
#ParseClassName("_User")
public class User extends ParseUser {
private static class Constant {
private static final String NAME = "name";
private static final String GENDER = "gender";
private static final String BIRTHDATE = "birthdate";
private static final String FACEBOOK_ID = "facebookId";
private static final String AVATAR = "avatar";
private static final String WEIGHT = "weight";
private static final String WEIGHT_UNIT = "weightUnit";
private static final String EXPERIENCE_LEVEL = "experienceLevel";
private static final String GOALS = "goals";
private static final String SCORE = "score";
private static final String IS_PREMIUM = "isPremium";
private static final String IS_TRIAL_PERIOD = "isTrialPeriod";
private static final String TOTAL_WORKOUT_BUILDS = "totalWorkoutBuilds";
}
private String name;
private String gender;
private String facebookId;
private Date birthday;
private ParseFile avatar;
private int weight;
private String weighUnit;
private String experienceLevel;
private List<Goal> goals;
private int score;
private int isPremium;
private int isTrialPeriod;
private int totalWorkoutBuilds;
private String emailAddress;
public User() {
super();
}
public String getName() {
return validateStringResult(Constant.NAME);
}
public void setName(String name) {
put(Constant.NAME, name);
}
public String getGender() {
return validateStringResult(Constant.GENDER);
}
public void setGender(String gender) {
put(Constant.GENDER, gender);
}
public Date getBirthday() {
return getDate(Constant.BIRTHDATE);
}
public void setBirthday(Date birthday) {
put(Constant.BIRTHDATE, birthday);
}
public String getFacebookId() {
return validateStringResult(Constant.FACEBOOK_ID);
}
public void setFacebookId(String facebookId) {
put(Constant.FACEBOOK_ID, facebookId);
}
public ParseFile getAvatar() {
return getParseFile(Constant.AVATAR);
}
public void setAvatar(ParseFile avatar) {
put(Constant.AVATAR, avatar);
}
public int getWeight() {
return getInt(Constant.WEIGHT);
}
public void setWeight(int weight) {
put(Constant.WEIGHT, weight);
}
public String getWeightUnit() {
return validateStringResult(Constant.WEIGHT_UNIT);
}
public void setWeightUnit(String weightUnit) {
put(Constant.WEIGHT_UNIT, weightUnit);
}
public ExperienceLevel getExperienceLevel() {
final String result = validateStringResult(Constant.EXPERIENCE_LEVEL);
if (result.equalsIgnoreCase("intermediate")) {
return ExperienceLevel.INTERMEDIATE;
} else if (result.equalsIgnoreCase("advanced")) {
return ExperienceLevel.ADVANCED;
} else {
return ExperienceLevel.BEGINNER;
}
}
public void setExperienceLevel(String experienceLevel) {
put(Constant.EXPERIENCE_LEVEL, experienceLevel);
}
public List<Goal> getGoals() {
return getList(Constant.GOALS);
}
public void setGoals(List<Goal> goals) {
put(Constant.GOALS, goals);
}
public int getScore() {
return getInt(Constant.SCORE);
}
public void setScore(int score) {
put(Constant.SCORE, score);
}
public boolean isPremium() {
return getBoolean(Constant.IS_PREMIUM);
}
public void setPremium(boolean premium) {
put(Constant.IS_PREMIUM, premium);
}
public boolean isTrialPeriod() {
return getBoolean(Constant.IS_TRIAL_PERIOD);
}
public void setTrialPeriod(boolean trialPeriod) {
put(Constant.IS_TRIAL_PERIOD, trialPeriod);
}
public int getTotalWorkoutBuilds() {
return getInt(Constant.TOTAL_WORKOUT_BUILDS);
}
public void setTotalWorkoutBuilds(int totalWorkoutBuilds) {
put(Constant.TOTAL_WORKOUT_BUILDS, totalWorkoutBuilds);
}
private String validateStringResult(String key) {
final String result = getString(key);
return result == null ? "" : result;
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.kineticoach.traveltrainer, PID: 22022
java.lang.IllegalStateException: ParseObject has no data for 'name'. Call fetchIfNeeded() to get the data.
at com.parse.ParseObject.checkGetAccess(ParseObject.java:3607)
at com.parse.ParseObject.getString(ParseObject.java:3186)
at com.kineticoach.traveltrainer.models.objects.User.getName(User.java:25)
at com.kineticoach.traveltrainer.fragments.ProfileFragment.lambda$loadUserData$1$ProfileFragment(ProfileFragment.java:153)
at com.kineticoach.traveltrainer.fragments.-$$Lambda$ProfileFragment$Sdpefi97hyh_jTMOE2pWx3FVbo8.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Follow this reference
we do not send the nested ParseObject's full data to cloud code. In order to get the data of the nested ParseObject, you have to do a query or fetch. The result you get from cloud code is pretty similar to the result you get from ParseQuery. We represent nested ParseObject as pointer and you have to fetch or query it in order to use it.
I'm creating the grid view with array list of category and un categorized product model class. Now I want to sort the list by date or name. See below my code.
Here this is my adapter.
public class CommonAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater inflator = null;
private List<Object> list;
public CommonAdapter(Context mContext, List<Object> list) {
super();
this.mContext = mContext;
this.list = list;
inflator = LayoutInflater.from(mContext);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflator.inflate(R.layout.row_categories, null);
holder = new ViewHolder();
holder.layout_bg = (RelativeLayout) convertView.findViewById(R.id.grid_bg);
holder.titleTextView = (TextView) convertView.findViewById(R.id.grid_item_title);
holder.txt_price = (TextView) convertView.findViewById(R.id.txt_price);
holder.img_notifier = (ImageView) convertView.findViewById(R.id.img_notifier);
holder.titleTextView.setTextColor(Color.WHITE);
holder.titleTextView.setTextSize(27);
holder.titleTextView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
holder.titleTextView.setLayoutParams(new RelativeLayout.LayoutParams(200, 200));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (list.get(position) instanceof Product) {
holder.titleTextView.setText(((Product) list.get(position)).getShortCode());
holder.img_notifier.setVisibility(ImageView.GONE);
holder.txt_price.setVisibility(TextView.VISIBLE);
NumberFormat format = NumberFormat.getCurrencyInstance();
double amount = Double.parseDouble(((Product) list.get(position)).getPrice()toString());
String formatAmount = NumberFormat.getCurrencyInstance().format(amount / 100);
holder.txt_price.setText(formatAmount);
}
if (list.get(position) instanceof Category) {
holder.titleTextView.setText(((CategoryWithProduct) list.get(position)).getShortCode());
holder.img_notifier.setVisibility(ImageView.VISIBLE);
holder.txt_price.setVisibility(TextView.GONE);
if (((Category) list.get(position)).getColor() != null) {
holder.layout_bg.setBackgroundColor(Color.parseColor(((Category) list.get(position)).getColor()));
} else {
}
}
return convertView;
}
static class ViewHolder {
RelativeLayout layout_bg;
TextView titleTextView, txt_price;
ImageView img_notifier;
}
This is product model classes
public class Product {
String id;
String name;
String price;
String createAt;
public Product(String id, String name, String price, String createAt) {
this.id = id;
this.name = name;
this.price = price;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
This is Category Model
public class Category {
String id;
String name;
String createAt;
public Category(String id, String name, String createAt) {
this.id = id;
this.name = name;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
In MainActivity.java
CommonAdapter commonAdapter = new CommonAdapter(getActivity(), commonArrayList);
grid_common.setAdapter(commonAdapter);
Here I tried with comparator, it's comes with object only!
Collections.sort(commonArrayList, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
return 0;
}
});
See here both models have createAt and name fields, So I want to sort by createAt or by name in this ArrayList.
Create another object model class and add all method and variable there is in two separate class...
and set data manually then... using for loop and any other ..that suitable for you...
and you this third created object model for sorting your data...
Edited
Eg:
first class
class first{
String f_name,l_name;
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
}
Second class
public class second {
String f_name,l_name,m_name;
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
}
third class
public class third{
String f_name,l_name,m_name;
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
}
set all value of first and second into third...
and use third class for setup data and sorting data
Here is my advice:
public class Category {
String id;
String name;
String createAt;
...
}
public class Product extends Category{
String price;
....
}
Collections.sort(commonArrayList, new Comparator<Category>() {
#Override
public int compare(Category o1, Category o2) {
if(o1.getCreateAt()>o2.getCreateAt()){
return 1;
}else{
...
}
return 0;
}
});
Create an abstract class, put fields common in Product and Category and compare that class.
public abstract class BaseClass {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Your Public class:
public class Product extends BaseClass {
...
public Product(String id, String name, String price, String createAt) {
setId(id);
setName(name);
this.price = price;
this.createAt = createAt;
}
}
Category class:
public class Category extends BaseClass {
...
public Category(String id, String name, String createAt) {
setId(id);
setName(name);
this.createAt = createAt;
}
}
And compare like this:
Collections.sort("ArrayList<BaseClass>()", new Comparator<BaseClass>() {
#Override
public int compare(BaseClass baseClass, BaseClass t1) {
return baseClass.getName().compareTo(t1.getName());
}
});
If you wanna sort by date put date field to BaseClass.
Thanks for your advice. I found the answer. I just make class casting on the object inside the comparator.
See the code below,
Collections.sort(commonArrayList, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
int res = 0;
if (o1 instanceof Category && o2 instanceof Category) {
res = (((Category) o1).getName().compareTo(((Category) o2).getName()));
} else if (o1 instanceof Product && o2 instanceof Product) {
res = (((Product) o1).getName().compareTo(((Product) o2).getName()));
} else if (o1 instanceof Category && o2 instanceof Product) {
res = (((Category) o1).getName().compareTo(((Product) o2).getName()));
} else if (o1 instanceof Product && o2 instanceof Category) {
res = (((Product) o1).getName().compareTo(((Category) o2).getName()));
}
return res;
}
});
If you have any simplified ideas, kindly post here..
Hope this sample solution in java may help :
Create an interface let say Data as follows
public interface Data {
}
Create the model classes as follows :
Product
public class Product implements Data{
String id;
String name;
String price;
String createAt;
public Product(String id, String name, String price, String createAt) {
this.id = id;
this.name = name;
this.price = price;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
Category
public class Category implements Data{
String id;
String name;
String createAt;
public Category(String id, String name, String createAt) {
this.id = id;
this.name = name;
this.createAt = createAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreateAt() {
return createAt;
}
public void setCreateAt(String createAt) {
this.createAt = createAt;
}
}
Now in main class of the project
public class TestSorting {
public static void main(String args[]) {
ArrayList<Data> categories = new ArrayList<>();
ArrayList<Data> products = new ArrayList<Data>();
// For Product
for (int i = 0; i < 10; i++) {
Product product = new Product("Prod" + i, "Product " + i, "" + i, System.currentTimeMillis() + "");
products.add(product);
}
// For category
for (int i = 10; i >=0; i--) {
Category category = new Category("Cat" + i, "Category " + i, System.currentTimeMillis() + "");
categories.add(category);
}
Collections.sort(categories, new Comparator<Data>() {
#Override
public int compare(Data data, Data data2) {
if(data instanceof Category)
{
int result=(((Category) data).getId().compareTo((((Category) data2).getId())));
return result;
}else if(data instanceof Product)
{
int result= (((Product) data).getId().compareTo(((Product) data2).getId()));
return result;
}else {
return 0;
}
}
});
System.out.println("******PRODUCT****************");
// For Product
for (int i = 0; i < products.size(); i++) {
Product product=((Product)products.get(i));
System.out.println(product.id+ " "+product.name);
}
System.out.println("\n\n"+"******Caterogy****************");
// For category
for (int i = 0; i < categories.size(); i++) {
Category category=((Category)categories.get(i));
System.out.println(category.id+ " "+category.name);
}
}
}
I am trying to get some the array of actors from Jira. The code for the wrapper is used in a Gson.fromJson call. I had used something similar with a json string that did not have an array in it that had the information I needed and it worked fine, so the issue seems to do with the array, but I am not 100% sure:
import com.google.gson.annotations.SerializedName;
public class JiraRoleJsonWrapper {
#SerializedName("self")
private String self;
#SerializedName("name")
private String name;
#SerializedName("id")
private int id;
#SerializedName("description")
private String description;
#SerializedName("actors")
private JiraActors[] actors;
public JiraActors[] getActors() {
return actors;
}
public void setActors(JiraActors[] actors) {
this.actors = actors;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String key) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
public String[] getAvatarUrls() {
return avatarUrls;
}
public void setAvatarUrls(String[] avatarUrls) {
this.avatarUrls = avatarUrls;
}
*/
}
class JiraActors {
#SerializedName("id")
private int id;
#SerializedName("displayNme")
private String displayName;
#SerializedName("type")
private String type;
#SerializedName("name")
private String name;
//#SerializedName("avatarUrl")
//private String avatarUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The json it would receive:
{
"self":"http://someserver.com:8080/apps/jira/rest/api/2/project/10741/role/10002",
"name":"Administrators",
"id":10002,
"description":"A project role",
"actors":[
{
"id":12432,
"displayName":"Joe Smith",
"type":"atlassian-user-role-actor",
"name":"joesmi",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=dawsmi&avatarId=12245"
},
{
"id":12612,
"displayName":"Smurfette Desdemona",
"type":"atlassian-user-role-actor",
"name":"smudes",
"avatarUrl":"/apps/jira/secure/useravatar?size=xsmall&ownerId=lamade&avatarId=10100"
},
This shows two actors and the format of the json. Please note I did not put a complete json response. It just shows two actors.
In my code, I tried the following to retrieve the actors:
InputStream is = response.getEntityInputStream();
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
JiraRoleJsonWrapper[] jiraRoleJsonWrapper = gson.fromJson(reader, JiraRoleJsonWrapper[].class);
for (JiraRoleJsonWrapper w : jiraRoleJsonWrapper) {
JiraActors[] a = w.getActors();
String name = a.getName();
It does not find getName for some reason. I am not sure why.
I figured it out.
I change the setActors to
public void setActors(ArrayList<JiraActors> actors) {
this.actors = actors;
}
Then I was able to get the array list and get access to the getName() method of JiraActors.
I have make a class which has a custom class object/variable and i want to make this class parcelable for passing it in to the intend so that i receive the reponse in next activity
MORE DETAILED
I Have class first ie
public class Data implements Parcelable{
#SerializedName("barlist")
Bar bar_list[];
public Bar[] getBarLst() {
return bar_list;
}
public void setBarLst(Bar lst[]) {
this.bar_list = lst;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeParcelableArray(bar_list, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
}
public static final Parcelable.Creator<Data> CREATOR = new Creator<Data>() {
public Data createFromParcel(Parcel source) {
Data data = new Data();
data.bar_list = (Bar[]) source.readParcelableArray(this.getClass().getClassLoader());
return data;
}
#Override
public Data[] newArray(int size) {
// TODO Auto-generated method stub
return new Data[size];
}
};
}
In the above class i have a custom type object/variable ie of type Bar
and my next class is ::
public class Bar implements Parcelable{
#SerializedName("name")
String Name;
#SerializedName("sex")
String sex;
#SerializedName("type")
String type;
#SerializedName("userid")
String userId;
#SerializedName("contactno")
String ContactNo;
#SerializedName("zipcode")
String zipCode;
#SerializedName("address")
String Address;
#SerializedName("email")
String Email;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getContactNo() {
return ContactNo;
}
public void setContactNo(String contactNo) {
ContactNo = contactNo;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(Name);
parcel.writeString(sex);
parcel.writeString(type);
parcel.writeString(userId);
parcel.writeString(ContactNo);
parcel.writeString(zipCode);
parcel.writeString(Address);
parcel.writeString(Email);
}
public static final Parcelable.Creator<Bar> CREATOR = new Creator<Bar>() {
public Bar createFromParcel(Parcel source) {
Bar barlst = new Bar();
barlst.Name = source.readString();
barlst.sex = source.readString();
barlst.ContactNo = source.readString();
barlst.type = source.readString();
barlst.userId = source.readString();
barlst.zipCode = source.readString();
barlst.Address = source.readString();
barlst.Email = source.readString();
return barlst;
}
#Override
public Bar[] newArray(int size) {
// TODO Auto-generated method stub
return new Bar[size];
}
};
}
I want to make a data class (first class) object be parcelable so in my first activity i did some this like this
EmptyRequest empt = new EmptyRequest();
Data responsestr = userManager.getMainMenuItems(empt,"url","Post","getBarList");
Intent myintent = new Intent(MainMenuPageActivity.this, BarListPageActivity.class);
Bundle mbundle = new Bundle();
mbundle.putParcelable("BARLIST", responsestr);
myintent.putExtras(mbundle);
startActivity(myintent);
till here my code worked fine and i kept the responsestr of type data into the parcelable
and in my next acitivity i tried to fetch data object like this
Data responseStr = (Response)getIntent().getParcelableExtra("BARLIST");
to fetch the object of type data but this didnt work and give exception the second activity class not found but my debugger reaches in the second activity.
Thanks in advance....
use
getIntent().getExtras().getParcelableExtra("BARLIST");