I am using parcelable to pass class to new activity. However, at receiving side, I get empty values. It is strange that I get empty values and not null values. However, I do expect some values in each attribute. I have checked that the attributes are not empty at the caller part. Why is this so?
Here is my implementation:
Call new activity
Intent intent = new Intent(ProductDetailsActivity.this, ShopActivity.class);
intent.putExtra(ShopActivity.KEY_COMPANY, products.get(currentTypePosition).companyDetails);
startActivity(intent);
Receive
Company company = getIntent().getParcelableExtra(KEY_COMPANY);
Parcelable
public class Company implements Parcelable {
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Company createFromParcel(Parcel in) {
return new Company(in);
}
public Company[] newArray(int size) {
return new Company[size];
}
};
// TODO: Remove default values once backend is completed
public ArrayList<CompanyProduct> companyProducts = getDefaultCompanyProducts();
public String name = "hello";
public int icon = 0;
public int productCount = 100;
public int followerCount = 9000;
public String location = "hello";
public String contact = "400-23729";
public String description = "hello";
public int storeCount = 100;
public Company() {
super();
}
public Company(Parcel in) {
in.readTypedList(companyProducts, Status.CREATOR);
name = in.readString();
icon= in.readInt();
productCount = in.readInt();
followerCount = in.readInt();
location = in.readString();
contact = in.readString();
description = in.readString();
storeCount = in.readInt();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(companyProducts);
dest.writeString(name);
dest.writeInt(icon);
dest.writeInt(productCount);
dest.writeInt(followerCount);
dest.writeString(location);
dest.writeString(contact);
dest.writeString(description);
dest.writeInt(storeCount);
}
}
Related
I have objects in a firebase database which represent characters in a video game and contain all their stats (attack, defense, health etc). I use a firebaseListAdapter to fill a gridview with custom views showing the characters and some of their stats.
When using Android API 25 or below, this works as expected, but with API 26 and above, all data EXCEPT the health value come through fine, and the health value is always set to 0.
The health variable is simply an int, and is never treated any differently than the other integer values (strength, defense etc) anywhere in the code.
I'll note that adding a listener to the health value alone of any of the characters retrieves the value just fine.
Does anyone have any ideas what may be causing this?
FirebaseListOptions<PlayerMonster> options = new FirebaseListOptions.Builder<PlayerMonster>()
.setQuery(mDatabase.child("playerMonsters").child(firebaseId).orderByChild("size"), PlayerMonster.class)
.setLayout(R.layout.monster_grid_single)
.build();
monsterFirebaseAdapter = new FirebaseListAdapter<PlayerMonster>(options) {
#Override
protected void populateView(View view, PlayerMonster monsterInstance, int position) {
// Not getting value for health ONLY, max health and everything else works. Querying health by itself also works.
Timber.d("monster health is " + monsterInstance.getHealth() + ", max hp: " + monsterInstance.getMax_health());
// Code here populates the view
}
};
grid.setAdapter(monsterFirebaseAdapter);
package odyssey.game.balfur.odyssey.firebase_objects;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.firebase.database.Exclude;
import java.util.HashMap;
import java.util.Map;
public class PlayerMonster extends Monster implements Parcelable {
private String user_given_nick_name;
private int experience;
private int drawableRes;
private int itemHeldId;
protected PlayerMonster(Parcel in) {
user_given_nick_name = in.readString();
monster_name = in.readString();
itemHeldId = in.readInt();
type = in.readInt();
level = in.readInt();
health = in.readInt();
max_health = in.readInt();
experience = in.readInt();
size = in.readInt();
skill1 = in.readInt();
skill2 = in.readInt();
skill3 = in.readInt();
skill4 = in.readInt();
strength = in.readInt();
defense = in.readInt();
magicStrength = in.readInt();
magicDefense = in.readInt();
speed = in.readInt();
skinId = in.readInt();
}
public static final Creator<PlayerMonster> CREATOR = new Creator<PlayerMonster>() {
#Override
public PlayerMonster createFromParcel(Parcel in) {
return new PlayerMonster(in);
}
#Override
public PlayerMonster[] newArray(int size) {
return new PlayerMonster[size];
}
};
public int getDrawableRes() {return drawableRes;}
public void setDrawableRes(int drawableRes) {this.drawableRes = drawableRes;}
public int getExperience() {return experience;}
public void setExperience(int experience) {this.experience = experience; }
// public void addExperience(int experience) {this.experience += experience; }
public String getUser_given_nick_name() {
return user_given_nick_name;
}
public void setUser_given_nick_name(String user_given_nick_name) {this.user_given_nick_name = user_given_nick_name;}
public int getItemHeldId() {return itemHeldId;}
public void setItemHeldId(int itemHeldId) {this.itemHeldId = itemHeldId;}
public String getMonsterStringName(){ return user_given_nick_name; }
public PlayerMonster(){}
public PlayerMonster(String userGivenNickName, String monsterName, int itemHeldId, int type, int level, int health,
int max_health, int experience, int size, int skill1, int skill2, int skill3, int skill4,
int strength, int defense, int magicStrength, int magicDefense, int speed, int skinId){
this.user_given_nick_name = userGivenNickName;
this.monster_name = monsterName;
this.itemHeldId = itemHeldId;
this.type = type;
this.level = level;
this.health = health;
this.max_health = max_health;
this.experience = experience;
this.size = size;
this.skill1 = skill1;
this.skill2 = skill2;
this.skill3 = skill3;
this.skill4 = skill4;
this.strength = strength;
this.defense = defense;
this.magicStrength = magicStrength;
this.magicDefense = magicDefense;
this.speed = speed;
this.skinId = skinId;
}
// constructor for monsters w/ image resource. for use in the monsterBattleGridAdapter
public PlayerMonster(String userGivenNickName, String monsterName, int itemHeldId, int type, int level, int health,
int max_health, int experience, int size, int drawableRes, int skill1, int skill2, int skill3, int skill4,
int strength, int defense, int magicStrength, int magicDefense, int speed, int skinId){
this.user_given_nick_name = userGivenNickName;
this.monster_name = monsterName;
this.itemHeldId = itemHeldId;
this.type = type;
this.level = level;
this.health = health;
this.max_health = max_health;
this.experience = experience;
this.size = size;
this.drawableRes = drawableRes;
this.skill1 = skill1;
this.skill2 = skill2;
this.skill3 = skill3;
this.skill4 = skill4;
this.strength = strength;
this.defense = defense;
this.magicStrength = magicStrength;
this.magicDefense = magicDefense;
this.speed = speed;
this.skinId = skinId;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("user_given_nick_name", user_given_nick_name);
result.put("monster_name", monster_name);
result.put("itemHeldId", itemHeldId);
result.put("type", type);
result.put("level", level);
result.put("health", health);
result.put("max_health", max_health);
result.put("experience", experience);
result.put("size", size);
result.put("skill1", skill1);
result.put("skill2", skill2);
result.put("skill3", skill3);
result.put("skill4", skill4);
result.put("strength", strength);
result.put("defense", defense);
result.put("magicStrength", magicStrength);
result.put("magicDefense", magicDefense);
result.put("speed", speed);
result.put("skinId", skinId);
return result;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(user_given_nick_name);
parcel.writeString(monster_name);
parcel.writeInt(itemHeldId);
parcel.writeInt(type);
parcel.writeInt(level);
parcel.writeInt(health);
parcel.writeInt(max_health);
parcel.writeInt(experience);
parcel.writeInt(size);
parcel.writeInt(skill1);
parcel.writeInt(skill2);
parcel.writeInt(skill3);
parcel.writeInt(skill4);
parcel.writeInt(strength);
parcel.writeInt(defense);
parcel.writeInt(magicStrength);
parcel.writeInt(magicDefense);
parcel.writeInt(speed);
parcel.writeInt(skinId);
}
}
package odyssey.game.balfur.odyssey.firebase_objects;
import android.os.Parcel;
import android.os.Parcelable;
import odyssey.game.balfur.odyssey.helpers.Condition;
import odyssey.game.balfur.odyssey.helpers.Helpers;
import odyssey.game.balfur.odyssey.helpers.TalentShorthand;
import java.util.HashMap;
import timber.log.Timber;
public class Monster implements Parcelable {
String monster_name;
int type;
int skill1;
int skill2;
int skill3;
int skill4;
int max_health;
int health;
int shield = 0;
int strength;
int speed;
int defense;
int magicStrength;
int magicDefense;
private boolean canSwap = true;
int skinId; // Each separate skin for each monster will have an ID associated with it
String firebaseId;
// At start of battle, record monsters stats to make sure buffs stay below certain %
public int[] baseStats = new int[6];
// Used to record how many stacks of a buff a monster has. can have between -5 and 5, each
// Representing 8% change from base stats. All values initialize to 0 by default
public int[] buffStacks = new int[6];
private HashMap<Integer, Condition> currentConditions = new HashMap<>();
private HashMap<Object, TalentShorthand> talentShorthand= new HashMap<>();
int level;
int size;
protected Monster(Parcel in) {
monster_name = in.readString();
type = in.readInt();
skill1 = in.readInt();
skill2 = in.readInt();
skill3 = in.readInt();
skill4 = in.readInt();
max_health = in.readInt();
health = in.readInt();
shield = in.readInt();
strength = in.readInt();
speed = in.readInt();
defense = in.readInt();
magicStrength = in.readInt();
magicDefense = in.readInt();
canSwap = in.readByte() != 0;
skinId = in.readInt();
firebaseId = in.readString();
baseStats = in.createIntArray();
buffStacks = in.createIntArray();
level = in.readInt();
size = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(monster_name);
dest.writeInt(type);
dest.writeInt(skill1);
dest.writeInt(skill2);
dest.writeInt(skill3);
dest.writeInt(skill4);
dest.writeInt(max_health);
dest.writeInt(health);
dest.writeInt(shield);
dest.writeInt(strength);
dest.writeInt(speed);
dest.writeInt(defense);
dest.writeInt(magicStrength);
dest.writeInt(magicDefense);
dest.writeByte((byte) (canSwap ? 1 : 0));
dest.writeInt(skinId);
dest.writeString(firebaseId);
dest.writeIntArray(baseStats);
dest.writeIntArray(buffStacks);
dest.writeInt(level);
dest.writeInt(size);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<Monster> CREATOR = new Creator<Monster>() {
#Override
public Monster createFromParcel(Parcel in) {
return new Monster(in);
}
#Override
public Monster[] newArray(int size) {
return new Monster[size];
}
};
// At start of battle, need to copy an array of each monsters stats and store it in each monster object
// These values will be checked when buff skills are used to ensure monsters stats do not go over the max buff amount (currently 40% over base)
public void backupStats(){
Timber.d("Backing up stats for %s", monster_name);
baseStats[0] = strength;
baseStats[1] = defense;
baseStats[2] = magicStrength;
baseStats[3] = magicDefense;
baseStats[4] = speed;
baseStats[5] = max_health;
}
public Monster(){}
public Monster(int level, String monster_name, int skinId){
this.level = level;
this.monster_name = monster_name;
this.skinId = skinId;
}
public int[] getBaseStats() { return baseStats; }
public void setBaseStats(int[] baseStats) { this.baseStats = baseStats; }
public String getFirebaseId() {return firebaseId;}
public void setFirebaseId(String firebaseId) {this.firebaseId = firebaseId;}
public int getSpeed() {return speed;}
public void setSpeed(int speed) {this.speed = speed;}
public int getStrength() {return strength;}
public void setStrength(int strength) {this.strength = strength;}
public int getDefense() {return defense;}
public void setDefense(int defense) {this.defense = defense;}
public int getMagicStrength() {return magicStrength;}
public void setMagicStrength(int magicStrength) {this.magicStrength = magicStrength;}
public int getMagicDefense() {return magicDefense;}
public void setMagicDefense(int magicDefense) {this.magicDefense = magicDefense;}
public int getSkill2() {return skill2;}
public void setSkill2(int skill2) {this.skill2 = skill2;}
public int getSkill3() {return skill3;}
public void setSkill3(int skill3) {this.skill3 = skill3;}
public int getSkill1() {return skill1;}
public void setSkill1(int skill1) {this.skill1 = skill1;}
public int getSkill4() {return skill4;}
public void setSkill4(int skill4) {this.skill4 = skill4;}
public int getSize() {return size;}
public void setSize(int size) {this.size = size;}
public int getMax_health() {
return max_health;
}
public void setMax_health(int max_health) {
this.max_health = max_health;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
if (health > max_health) this.health = max_health;
else if (health <= 0) this.health = 0;
else this.health = health;
}
public int getShield() {return shield;}
public void setShield(int shield) {
if (shield > max_health) this.shield = max_health;
else if (shield <= 0) this.shield = 0;
else this.shield = shield;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getMonster_name() {
return monster_name;
}
public void setMonster_name(String monster_name) {
this.monster_name = monster_name;
}
public String getMonsterStringName(){ return monster_name; }
public int getSkinId() { return skinId; }
public void setSkinId(int skinId) { this.skinId = skinId; }
public boolean isCanSwap() { return canSwap; }
public void setCanSwap(boolean canSwap) { this.canSwap = canSwap; }
public HashMap<Object, TalentShorthand> getTalentShorthand(){
return talentShorthand;
}
public void setTalentShorthand(HashMap<Object, TalentShorthand> talentShorthand){this.talentShorthand = talentShorthand;}
public HashMap<Integer, Condition> getCurrentConditions(){
return currentConditions;
}
public void setCurrentConditions(HashMap<Integer, Condition> currentConditions){this.currentConditions = currentConditions;}
public void addCondition(int conditionId, int roundsRemaining, double conditionDamagePercent, int addedStacks){
Condition condition;
if (currentConditions.containsKey(conditionId)){
int conditionStacks = currentConditions.get(conditionId).getConditionStacks();
// If adding one to the current stacks would still be less than the max stacks for that condition, add 1, otherwise do nothing
if (conditionStacks + addedStacks > Helpers.getConditionMaxStacks(conditionId)){
conditionStacks = Helpers.getConditionMaxStacks(conditionId);
addedStacks = Helpers.getConditionMaxStacks(conditionId) - conditionStacks; // The difference between the max and the preexisting conditions will be the true number of stacks added
} else {
conditionStacks += addedStacks;
}
condition = new Condition(roundsRemaining, conditionDamagePercent, conditionStacks);
condition.setStacksAppliedThisRound(addedStacks);
currentConditions.put(conditionId, condition);
} else {
condition = new Condition(roundsRemaining, conditionDamagePercent, addedStacks);
condition.setStacksAppliedThisRound(addedStacks);
currentConditions.put(conditionId, condition);
}
}
public void removeCondition(int conditionId){ // Used for calling condition remove skills doi
if (currentConditions.containsKey(conditionId)){
currentConditions.remove(conditionId);
}
}
}
I ended up finding a fix, but I'm still uncertain as to why this was an issue in only certain android API levels.
public void setHealth(int health) {
if (health > max_health) this.health = max_health;
else if (health <= 0) this.health = 0;
else this.health = health;
}
The setHealth() function is called for each object when firebaseListAdapter gets these objects, and when using API 26+, these functions must be called piecemeal or something because when called, the max_health value is set to 0, so the condition
if (health > max_health)
is true, and therefore health was being erroneously set to 0. In older versions of Android, the max_health value is already set correctly by the tim the setHealth() function is called.
I added a check to ensure that max_health isn't 0 at the top of the setHealth() function, as a character can't have 0 for a max_health
I'd still be interested for curiosity's sake and to possibly help someone down the line in learning why the behavior differs in the different versions of Android, but for the time being I'll consider my original question answered.
I'm trying to trasnfer data between activities with parcelable I'm having a bit of an issue. I'm getting the error Expression expected on the putExtraData portion of the code. The debugger says error: cannot find symbol variable ListingsModel. The class containing the parcelable code is called ListingsModel as is the constructor. I can’t seem to locate my error. My intent is wrapped in an if statement that should execute if try and launch the activity ReviewActivity.class and pass all data accordingly. Any help would be greatly appreciated.
Intent to launch Review activity class and pass data on true if statement:
Intent intent = new Intent(MainActivity.this, ReviewActivity.class);
putExtraData("ListingsModel", **ListingsModel**); //error appears here
startActivity(intent);
Class containing parcelable code:
public class ListingsModel implements Parcelable {
public static final int IMAGE_TYPE = 1;
public String title, street, city, state, zip, hours, isOpen, content, image, phone, timestamp;
public int type, rating, ratingCount;
public Double lat, lng;
public ListingsModel(int mtype, String mtitle, Integer mrating, Integer mRatingCount, String mstreet, String mcity, String mstate, String mzip, String mhours, String mIsOpen, String mcontent, String mimage, String mphone, Double mlat, Double mlng, String mtimestamp) {
this.type = mtype;
this.title = mtitle;
this.rating = mrating;
this.ratingCount = mRatingCount;
this.street = mstreet;
this.city = mcity;
this.state = mstate;
this.zip = mzip;
this.hours = mhours;
this.isOpen = mIsOpen;
this.content = mcontent;
this.image = mimage;
this.phone = mphone;
this.lat = mlat;
this.lng = mlng;
this.timestamp = mtimestamp;
}
//write object values to parcel for storage
public void writeToParcel(Parcel dest, int flags){
//write all properties to the parcle
//dest.writeInt(type);
dest.writeString(title);
dest.writeInt(rating);
dest.writeInt(ratingCount);
dest.writeString(street);
dest.writeString(city);
dest.writeString(state);
dest.writeString(zip);
dest.writeString(hours);
dest.writeString(isOpen);
dest.writeString(content);
dest.writeString(image);
dest.writeString(phone);
dest.writeDouble(lat);
dest.writeDouble(lng);
}
//constructor used for parcel
public ListingsModel(Parcel parcel){
//read and set saved values from parcel
title = parcel.readString();
rating = parcel.readInt();
ratingCount = parcel.readInt();
street = parcel.readString();
city = parcel.readString();
state = parcel.readString();
zip = parcel.readString();
hours = parcel.readString();
isOpen = parcel.readString();
content = parcel.readString();
image = parcel.readString();
phone = parcel.readString();
lat = parcel.readDouble();
lng = parcel.readDouble();
}
//creator - used when un-parceling our parcle (creating the object)
public static final Parcelable.Creator<ListingsModel> CREATOR = new Parcelable.Creator<ListingsModel>(){
#Override
public ListingsModel createFromParcel(Parcel parcel) {
return new ListingsModel(parcel);
}
#Override
public ListingsModel[] newArray(int size) {
return new ListingsModel[0];
}
};
//return hashcode of object
public int describeContents() {
return hashCode();
}
}
I need the activity ReviewActivity to lauch pre-poulated with the parcelable data. I can't figure out the issue that's causing the error on the putExtraData portion of my intent call.
When passing model as parcelable use this:
Bundle b = new Bundle();
b.putParcelable("keyName", YourModel);
startActivity(new Intent(this, Activity.class).putExtra("bundleName", bundle));
Receive model as parcelable:
Bundle bundle= getIntent().getBundleExtra("bundleName");
bundle.getParcelable("keyName");
ListingModel listingModel = new ListingModel(/* put required parameters here*/);
Intent intent = new Intent(this, ReviewActivity.class);
intent.putExtra("ListingsModel", listingModel);
startActivity(intent);
I'm creating an alarm clock app and i have a problem with passing the data about repeating days in parcel. I thought that it might be something with boolean array so i switched it to String but still problem remains.
Any idea what is wrong with my Parcelable object?
public Alarm(Parcel source) {
mHour = source.readInt();
mMinutes = source.readInt();
mId = source.readInt();
// Here string is empty ""
String days = source.readString();
mDays = GeneralUtilities.daysStringToBoolean(days);
mIsEnabled = source.readInt() != 0;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mHour);
dest.writeInt(mMinutes);
dest.writeLong(mId);
// Here days is string "True,False ... "
String days = GeneralUtilities.daysBooleanToString(mDays);
dest.writeString(days);
dest.writeInt((mIsEnabled ? 1 : 0));
}
public static final Creator<Alarm> CREATOR = new Creator<Alarm>() {
#Override
public Alarm createFromParcel(Parcel source) {
return new Alarm(source);
}
#Override
public Alarm[] newArray(int size) {
return new Alarm[size];
}
};
}
I had to pass a dataobject from one activity to another. The best way to do this is uing Parcelable.
The dataobject had some fields with setter and getter methods. After setting some fields and passing the object to another activity, wha tI observed is that the field values got interchanged to other field values.
The order of fields for writing to parcel and reading from parcel is the same.
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(appNo);
out.writeString(this.policyNo);
out.writeInt((int)this.AppRcptDt.getTime());
out.writeString(this.currentStatus);
out.writeString(this.productCd);
out.writeDouble(this.sumAssured);
out.writeDouble(this.modalPremium);
out.writeDouble(this.annualPremium);
out.writeString(this.paymentMode);
out.writeString(this.branchCd);
out.writeString(this.branchName);
out.writeString(this.insuredName);
out.writeString(this.auraStatus);
out.writeString(this.ownerName);
out.writeString(this.agentCd);
out.writeString(this.billingMode);
}
private ApplicationTrackerDO(Parcel in) {
id=in.readInt();
this.appNo = in.readString();
this.policyNo = in.readString();
this.AppRcptDt = new Date(in.readLong());
this.currentStatus = in.readString();
this.productCd = in.readString();
this.sumAssured = in.readDouble();
this.modalPremium = in.readDouble();
this.annualPremium = in.readDouble();
this.paymentMode = in.readString();
this.branchCd = in.readString();
this.branchName = in.readString();
this.insuredName = in.readString();
this.auraStatus = in.readString();
this.ownerName = in.readString();
this.agentCd = in.readString();
this.billingMode = in.readString();
}
It is not the order but the data type that is not the same, from the first 4 lines you write int, string, string, int then you read int, string, string, long. I didn't check any further, you must match both order and datatype of read and write operations.
You are writing int
out.writeInt((int)this.AppRcptDt.getTime());
But reading long
this.AppRcptDt = new Date(in.readLong());
my solution to provide an date object with null
#Override
public void writeToParcel ( Parcel dest, int flags ) {
dest.writeInt((birthday != null) ? 1 : 0); // is birthday set?
dest.writeLong((birthday != null) ? birthday.getTime() : 0);
}
public void readFromParcel ( Parcel in ) {
if(in.readInt() == 1) {
birthday = new Date(in.readLong());
} else {
in.readLong(); // ignore stored value
birthday = null;
}
}
java.util.Date implements Serializable:
public class Date implements Serializable, Cloneable, Comparable<Date> {
private static final long serialVersionUID = 7523967970034938905L;
// Used by parse()
private static final int CREATION_YEAR = new Date().getYear();
private transient long milliseconds;
Use:
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(myDateField);
}
private MyClass(Parcel in) {
myDateField = (Date)in.readSerializable();
}
I have Product class.I want to pass product object one activity to another.
I have implemented like this :
public class Product implements Parcelable{
private double availableQuantity;
private double price;
private String productCode;
private String description;
private String nonStockItemFlag;
private String activeFlag;
private String kitProductFlag;
private double value;
private ArrayList<Product> product;
private double qty;
public Product() {
}
/**
* #param availableQuantity
* #param price
* #param productCode
* #param description
* #param nonStockItemFlag
* #param kitProductFlag
* #param qty
* #param grossValue
* #param value
*/
public Product(double availableQuantity, double price, String productCode,
String description, String nonStockItemFlag, String kitProductFlag,
double qty, double value) {
super();
this.availableQuantity = availableQuantity;
this.price = price;
this.productCode = productCode;
this.description = description;
this.nonStockItemFlag = nonStockItemFlag;
this.kitProductFlag = kitProductFlag;
this.qty = qty;
this.value = value;
}
// setter & getter
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
Bundle b = new Bundle();
b.putParcelableArrayList("enteredProduct", product);
dest.writeBundle(b);
}
public static final Parcelable.Creator<Product> CREATOR = new Parcelable.Creator<Product>() {
public Product createFromParcel(Parcel in) {
Product prod = new Product();
Bundle b = in.readBundle(Product.class.getClassLoader());
prod.product = b.getParcelableArrayList("enteredProduct");
System.out.println("***product***" + prod.product.get(0).getPrice());
return prod;
}
public Product[] newArray(int size) {
return new Product[size];
}
};
This is caller part :
if(productMap.size() >0){
ArrayList<Product> enteredProductList = new ArrayList<Product>(productMap.values());
System.out.println("-enteredProductList --" + enteredProductList.size());
System.out.println("--- " +enteredProductList.get(0).getPrice() );
Bundle b = new Bundle();
b.putParcelableArrayList("enteredProduct", enteredProductList);
Intent showContent = new Intent(getApplicationContext(),RetailerOrderIActivity.class);
showContent.putExtras(b); //Insert the Bundle object in the Intent' Extras
startActivity(showContent);
}else{
Toast.makeText(RetailerOrderActivity.this," You don't have invoice records" ,Toast.LENGTH_SHORT).show();
}
This is receive part :
Bundle b = this.getIntent().getExtras();
ArrayList<Product> p = b.getParcelableArrayList("enteredProduct");
System.out.println("-- RetailerOrderIActivity --" + p.size() );
for(Product s : p){
System.out.println(" --Qty-" + s.getQty());
System.out.println(" --price -" + s.getPrice());
System.out.println(" --code -" + s.getProductCode());
}
The receiving part return null value.But in the sending Activity part contain value.Please correct my code?
what is wrong in my code?
I have lot of property for product entity calss.But i want to set some of entity.
Thanks in advance.
I guess you misunderstood the Parcelable examples.
You have to put all needed elements into the parcel, and get it from it later:
To write your object to the parcel, this is needed:
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(productCodce);
dest.writeString(description);
// and all other elements
}
Plus, you need a constructor receiving a parcel:
public Product(Parcel in)
{
this.productCode=in.readString();
this.description=in.readString();
// and all other elements
}
Your Creator should be something like:
public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
{
public Product createFromParcel(Parcel in) { return new Product(in); }
public Product[] newArray(int size) { return new Product[size]; }
};
Now, at your activity level (NOT in your Product class!):
Push it into extras, use:
bundle.putParcelableArrayList("whatevername",products);
To get it from the extras, use a simple:
ArrayList<Product> products=bundle.getParcelableArrayList("whatevername");