I have an Parcelable object called Book and another called Author. I can't tell why the object constructor for Book is not working. The first bit of code is where i try to make it so I can send it to a parent activity. The values were checked before, and when I do the .toString() method on book, I get null Price: null
Activity Code
EditText editText = (EditText) findViewById(R.id.search_title);
String title = editText.getText().toString();
editText = (EditText) findViewById(R.id.search_author);
String author = editText.getText().toString();
editText = (EditText) findViewById(R.id.search_isbn);
int isbn = Integer.parseInt(editText.getText().toString());
...
Parcel p = Parcel.obtain();
p.writeInt(isbn);
p.writeString(title);
p.writeString(author);
p.writeString(editText.getText().toString());
p.writeString("$15.00");
Intent intent = new Intent();
Book book = new Book(p);
System.out.println(book.toString());
Book.java
public class Book implements Parcelable {
private int id;
private String title;
private ArrayList<Author> authors = new ArrayList<Author>();
//private int Aflags;
private String isbn;
private String price;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(title);
out.writeTypedList(authors);
out.writeString(isbn);
out.writeString(price);
}
public Book(Parcel in) {
id = in.readInt();
title = in.readString();
in.readTypedList(authors, Author.CREATOR);
isbn = in.readString();
price = in.readString();
}
public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {
public Book createFromParcel(Parcel in) {
return new Book(in);
}
public Book[] newArray(int size) {
return new Book[size];
}
};
#Override
public String toString()
{
return title + " Price: " + price;
}
}
Author.java
public class Author implements Parcelable {
// NOTE: middleInitial may be NULL!
public String firstName;
public String middleInitial;
public String lastName;
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeString(firstName);
if (middleInitial.length() == 0)
out.writeString(middleInitial);
out.writeString(lastName);
}
private Author(Parcel in)
{
firstName = in.readString();
if (in.dataSize() == 2)
middleInitial = in.readString();
if (in.dataSize() == 1)
lastName = in.readString();
}
public static final Parcelable.Creator<Author> CREATOR = new Parcelable.Creator<Author>() {
public Author createFromParcel(Parcel in) {
return new Author(in);
}
public Author[] newArray(int size) {
return new Author[size];
}
};
#Override
public int describeContents() {
return 0;
}
}
Parcel p = Parcel.obtain();
p.writeInt(isbn);
p.writeString(title);
p.writeString(author); // Here i think u need to write list of author and not string
p.writeString(editText.getText().toString());
p.writeString("$15.00");
Intent intent = new Intent();
Book book = new Book(p);
System.out.println(book.toString());
/*****Edited answer ******/
//HERE u go mate this should work, tested code
//You need to parse the author text then
Parcel p = Parcel.obtain();
p.writeInt(23); // isbn
p.writeString("sometitle");
// List<String> data = new List<String>();//parseAuthor(author); // function dependent on what u get
Parcel auth = Parcel.obtain();
auth.writeString("firstname"); // firstname
auth.writeString("middle"); // middle
auth.writeString("lastname"); // lastname
auth.setDataCapacity(3);
auth.setDataPosition(0);
Author a = Author.CREATOR.createFromParcel(auth);
ArrayList<Author> authors = new ArrayList<Author>();
authors.add(a);
p.writeTypedList(authors);
p.writeString("something");
p.writeString("$15.00");
p.setDataPosition(0);
Intent intent = new Intent();
Book book = Book.CREATOR.createFromParcel(p);
System.out.println(book.toString());
Hi so I just gave up and made a new constructor that doesn't use Parcels.
But what was written below p.setDataPosition(0); may work as well for future users
Related
I'm trying to put a Parcelable object as an extra in an intent and pass it to the next Activity, and it doesn't crash but the object changes dramatically. I'm sending when clicking on an item from a RecyclerView in a Fragment and opening an Activity from it.
This is how I send it:
AdminProfile adminProfile = list.get(position).admin;
Intent intent = new Intent(view.getContext(),ClosedChatActivity.class);
intent.putExtra("chat",adminProfile);
view.getContext().startActivity(intent);
This how I get it:
adminProfile = (AdminProfile) getIntent().getExtras().getParcelable("chat");
And here the class:
public class AdminProfile implements Parcelable {
public static final Creator<AdminProfile> CREATOR = new Creator<AdminProfile>() {
#Override
public AdminProfile createFromParcel(Parcel in) {
return new AdminProfile(in);
}
#Override
public AdminProfile[] newArray(int size) {
return new AdminProfile[size];
}
};
public Long idUser;
public String name;
public String professio;
public String description;
public List<WebLink> webLinks;
public Long idOficina;
protected AdminProfile(Parcel in) {
if (in.readByte() == 0) {
idUser = null;
} else {
idUser = in.readLong();
}
name = in.readString();
professio = in.readString();
description = in.readString();
webLinks = in.createTypedArrayList(WebLink.CREATOR);
if (in.readByte() == 0) {
idOficina = null;
} else {
idOficina = in.readLong();
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(idUser);
parcel.writeString(name);
parcel.writeString(professio);
parcel.writeString(description);
parcel.writeLong(idOficina);
parcel.writeList(webLinks);
}
}
I can't understand why, but when I send the object I have UserId=3, but when I get it it's userId=55834574848. Any ideas?
The Parcelable functions were filled automatically by Android Studio, and reading the first byte messed it up.
Changing
if (in.readByte() == 0) {
idUser = null;
} else {
idUser = in.readLong();
}
for
idUser = in.readLong();
fixed it.
I have a list which I am trying to broadcast with the use of intents. After following online tutorials, I was adviced to use Parcelable in order to send this data. However, I keep getting this error in logcat:
Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.os.Parcelable
from this line of code
bundle.putParcelable("data", (Parcelable)tweets);
I do not know how to correct this.
Where i am building the intent
protected void onHandleWork(#NonNull Intent intent) {
Log.d(TAG, "onHandleWork: ");
List<tweet> tweets = new ArrayList();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("HyjgZgfiqSODTdICZUXIHI8HK", "TlynMItosq99QxnLMLGxA6FElD3TAKx9UmBxva5oExg9Gz1mzV");
AccessToken accessToken = new AccessToken("2362719277-w5QlRNB2I7PXdMJuDXf5cc8FDT5H8X38ujxrtiT", "3v2Z2cqezaFrV6pFHu2yfPVFHZgMvLjMVKH4cUujI9kwI");
twitter.setOAuthAccessToken(accessToken);
Query query = new Query("Twitch");
try {
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
String createdat = status.getCreatedAt().toString();
String text = status.getText();
String retweets = String.valueOf(status.getRetweetCount());
String favs = String.valueOf(status.getFavoriteCount());
String uri = status.getUser().getProfileImageURL();
tweet onetweet = new tweet(createdat,text,retweets,favs,uri);
// Log.d(TAG, status.getText());
tweets.add(onetweet);
}
if (isStopped()) return;
} catch (TwitterException e) {
e.printStackTrace();
}
sendToUI(tweets);
}
private void sendToUI(List tweets) {
Intent intent = new Intent("tweet_result");
Bundle bundle = new Bundle();
bundle.putParcelable("data", tweets);
intent.putExtras(bundle);
sendBroadcast(intent);
}
My tweet POJO
import android.os.Parcel;
import android.os.Parcelable;
public class tweet implements Parcelable {
private String created_at;
private String text;
private String retweet_count;
private String favorite_count;
private String image_uri;
public String getImage_uri() {
return image_uri;
}
public String getCreated_at() {
return created_at;
}
public String getText() {
return text;
}
public String getRetweet_count() {
return retweet_count;
}
public String getFavorite_count() {
return favorite_count;
}
protected tweet(Parcel in) {
created_at = in.readString();
text = in.readString();
retweet_count = in.readString();
favorite_count = in.readString();
image_uri = in.readString();
}
public static final Creator<tweet> CREATOR = new Creator<tweet>() {
#Override
public tweet createFromParcel(Parcel in) {
return new tweet(in);
}
#Override
public tweet[] newArray(int size) {
return new tweet[size];
}
};
#Override
public int describeContents() {
return 0;
}
public tweet(String created_at, String text, String retweet_count, String favorite_count, String image_uri) {
this.created_at = created_at;
this.text = text;
this.retweet_count = retweet_count;
this.favorite_count = favorite_count;
this.image_uri = image_uri;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(created_at);
dest.writeString(text);
dest.writeString(retweet_count);
dest.writeString(favorite_count);
dest.writeString(image_uri);
}
}
You used wrong method, you should use intent.putParcelableArrayListExtra() but don't forget about that your array list must contains only parcelables items.
Changing my sendToUI() to this has worked:
private void sendToUI(List tweets) {
Intent intent = new Intent("tweet_result"); //tweet_result is a string to identify this intent
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) tweets);
intent.putExtras(bundle);
sendBroadcast(intent);
}
I've created a ListView (myList). By pressing on one of the items on the ListView, the app is supposed to direct the user to the PlaySongActivity page.
I used a searchById function to try to match the ID of the song and the song in my database.( get ID of the song and match the song ID in database to play the same song) However, my teacher told me I am searching by the ID of the ListView, not the song.
So is there any way I can either search by the song title or possibly add an ID to each item in the ListView?
I'm a beginner in coding and have searched for hours and found no solution on the internet :(
private SongCollection mySongCollection = new SongCollection();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(SearchSong.this, PlaySongActivity.class);
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
AppUtil.popMessage(SearchSong.this, "Streaming music: " + selectedSong.getTitle());
intent.putExtra("id", selectedSong.getId());
intent.putExtra("title", selectedSong.getTitle());
intent.putExtra("artiste", selectedSong.getArtiste());
intent.putExtra("fileLink", selectedSong.getFileLink());
intent.putExtra("coverArt", selectedSong.getCoverArt());
startActivity(intent);
}
});
SongCollection.class codes
package com.example.musix;
public class SongCollection {
private Song[] allSongs = new Song[9];
public SongCollection (){
prepareSongs();
}
private void prepareSongs(){
Song theWayYouLookTonight = new Song ("S1001", "The Way You Look Tonight", "Michael Buble", "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=2afe87a64b0042dabf51f37318616965", 4.66, "michael_buble_collection");
Song billiejean = new Song ("S1002", "Billie Jean", "Michael Jackson", "4eb779428d40d579f14d12a9daf98fc66c7d0be4?cid=2afe87a64b0042dabf51f37318616965", 4.9, "billie_jean");
Song somethingJustLikeThis = new Song("S1003", "Something Just Like This","The Chainsmokers","499eefd42a24ec562c464bd7acfad7ed41eb9179?cid=2afe87a64b0042dabf51f37318616965", 4.13, "something_just_like_this");
Song southOfTheBorder = new Song("S1004", "South of the Border","Ed Sheeran","7b43dd0c94b0af0c0401381a683d2f4833180ba3?cid=2afe87a64b0042dabf51f37318616965", 3.41, "south_of_the_border");
Song oldTownRoad = new Song("S1005", "Old Town Road","Lil Nas X","3bc62106123fcafad475271e72e74cd7f519ab83?cid=2afe87a64b0042dabf51f37318616965", 1.9, "old_town_road");
Song noGuidance = new Song("S1006", "No Guidance", "Chris Brown", "7c3bc7b4d1741a001463b570fe29f922d9c42bd6?cid=2afe87a64b0042dabf51f37318616965", 4.34, "no_guidance");
Song closer = new Song("S1007", "Closer", "The Chainsmokers", "8d3df1c64907cb183bff5a127b1525b530992afb?cid=2afe87a64b0042dabf51f37318616965", 4.08, "closer");
Song sideface = new Song("S1008", "側臉", "于果", "c8cc891a7cacb36857ea15c8fcfc4da6e4b1583d?cid=2afe87a64b0042dabf51f37318616965", 3.63, "sideface");
Song kebukeyi = new Song("S1009", "可不可以", "张紫豪", "2d790215acf7c4e6c5e093255b94a936064f75ed?cid=2afe87a64b0042dabf51f37318616965", 4.01, "kebukeyi");
allSongs[0]= theWayYouLookTonight;
allSongs[1]= billiejean;
allSongs[2]= somethingJustLikeThis;
allSongs[3]= southOfTheBorder;
allSongs[4]= oldTownRoad;
allSongs[5]= noGuidance;
allSongs[6]= closer;
allSongs[7]= sideface;
allSongs[8]= kebukeyi;
}
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
//create a method to retrieve the next song
public Song getNextSong(String currentSongId){
Song nextSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x < allSongs.length -1)){
nextSong = allSongs[x+1];
break;
}
}
return nextSong;
}
//create a method to retrieve the previous song
public Song getPrevSong(String currentSongId){
Song PrevSong = null;
for(int x = 0; x < allSongs.length; x++){
String tempSongId = allSongs[x].getId();
if(tempSongId.equals(currentSongId) && (x > 0)){
PrevSong = allSongs[x-1];
break;
}
}
return PrevSong;
}
//create a method to get random song
public Song getRandomSong(){
Song randomSong = null;
int max = 2;
int min = 0;
int randomNum = (int)(Math.random()*4);
randomSong = allSongs[randomNum];
return randomSong;
}
}
Song.class codes
package com.example.musix;
public class Song {
//private attributes are hidden from other classes/files
private String id;
private String title;
private String artiste;
private String fileLink;
private double songLength;
private String coverArt;
public Song(String _id, String _title, String _artiste, String _fileLink, double _songLength, String _coverArt){
this.id = _id;
this.title = _title;
this.artiste = _artiste;
this.fileLink = _fileLink;
this.songLength = _songLength;
this.coverArt = _coverArt;
}
//encapsulation
//SET methods for setting/changing of the values of the attributes
public void setId(String id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setArtiste(String artiste) {
this.artiste = artiste;
}
public void setFileLink(String fileLink) {
this.fileLink = fileLink;
}
public void setSongLength(double songLength) {
this.songLength = songLength;
}
public void setCoverArt(String coverArt) {
this.coverArt = coverArt;
}
//GET methods allows us to retrieve values of the attributes
public String getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
public String getArtiste() {
return this.artiste;
}
public String getFileLink() {
return this.fileLink;
}
public double getSongLength() {
return this.songLength;
}
public String getCoverArt() {
return this.coverArt;
}
}
codes for getResourceId
public final class AppUtil
{
public static void popMessage(Context context, String message)
{
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static String getResourceId(Context context, View view)
{
String id = context.getResources().getResourceEntryName(view.getId());
return id;
}
String resourceId = AppUtil.getResourceId(SearchSong.this, myList);
Song selectedSong = mySongCollection.searchById(resourceId);
resourceId is going to be the id of the element of the list view (eg. first element id = 0, 2nd id = 1 and so on).
public Song searchById (String id){
Song selectedSong = null;
for(int index=0; index<allSongs.length; index++){
selectedSong = allSongs[index];
if(selectedSong.getId().equals(id)){
return selectedSong;
}
}
return selectedSong;
}
Should be:
public Song searchById (String id){
//we are returning the song selected by the index of its Arrays
Song selectedSong = allSongs[Integer.parseInt(id)];
return selectedSong;
}
Why?:
Your returning the actual songid, but in
Song selectedSong = mySongCollection.searchById(resourceId); <-- resourceId is already the Id stored in the database and not the index of mySongCollection.
intent.putExtra("id", selectedSong.getId());
you are using already the actuals song id. This doesen't make sense as you can already identify the actual song.
So either apply these changes or change this line:
intent.putExtra("id", resourceId);
I am crafting a non profit charity app. Despite I have checked many questions in stack and google, i could not solve the problem.
I have 3 classes:
- BaseCell implements Parcelable (Base class)
- Needy extends BaseCell
- UserBasket class which hold the list of all classes extend BaseCell
Problem
I am holding Needy classes with Arraylist in UserBasket class. When i send it to another activity, if i add 1 item to the UserBasket i am getting ridiculous result(Missing or wrong characters) and if i add more than 1 item then i am getting exception.
I need to deliver UserBasket class(list of needy items) to the payment activity so i can calculate the total price for charity and perform necessary actions.
public abstract class BaseCell implements Parcelable {
String imageUrl;
int percentageOfCollectedDonation;
String needyTitle;
String needyDescription;
protected String category;
protected int amountOfCollectedDonation=0;
protected int amountOfTargetDonation=0;
protected int amountOfDonater=0;
protected int drawableID;
protected String campaignCode;
protected int maxInstallmentNumber;
int price;
public String getCellType() {
return cellType;
}
protected String cellType ;
/**
* How many of this campaign purchased by user
* */
protected int userPurchaseAmount = 1;
protected BaseCell(String cellType)
{
this.cellType = cellType;
}
protected BaseCell(Parcel in)
{
drawableID = in.readInt();
price = in.readInt();
imageUrl = in.readString();
needyTitle = in.readString();
needyDescription = in.readString();
category = in.readString();
campaignCode = in.readString();
maxInstallmentNumber = in.readInt();
userPurchaseAmount = in.readInt();
}
public static final Parcelable.Creator<BaseCell> CREATOR = new Parcelable.Creator<BaseCell>() {
#Override
public BaseCell createFromParcel(Parcel in) {
String cellType = in.readString();
BaseCell baseCell = null;
if (cellType.equals("Needy"))
{
baseCell = (Needy)new Needy(in);
}else
if (cellType.equals("Qurban"))
{
baseCell = (Qurban)new Qurban(in);
}
return baseCell;
}
#Override
public BaseCell[] newArray(int size) {
return new BaseCell[size];
}
};
public void writeToParcel(Parcel out, int flags) {
out.writeString(getCellType());
}
public BaseCell(String imageUrl, int drawableID, String needyTitle, String needyDescription, int amountOfCollectedDonation, int amountOfTargetDonation, int amountOfDonater, String category,String campaignCode, int maxInstallmentNumber, int price)
{
this.imageUrl = imageUrl;
this.drawableID = drawableID;
this.needyTitle = needyTitle;
this.needyDescription = needyDescription;
this.amountOfCollectedDonation = amountOfCollectedDonation;
this.amountOfTargetDonation = amountOfTargetDonation;
this.amountOfDonater = amountOfDonater;
this.category = category;
this.campaignCode = campaignCode;
this.maxInstallmentNumber = maxInstallmentNumber;
this.price= price;
}
}
Needy
public class Needy extends BaseCell {
protected Needy(Parcel in) {
super(in);
cellType ="Needy";
}
public static final Parcelable.Creator<Needy> CREATOR = new Parcelable.Creator<Needy>() {
#Override
public Needy createFromParcel(Parcel in) {
return new Needy(in);
}
#Override
public Needy[] newArray(int size) {
return new Needy[size];
}
};
public Needy(String imageUrl, int drawableID, String needyTitle, String needyDescription, int amountOfCollectedDonation, int amountOfTargetDonation, int amountOfDonater, String category, String campaignCode, int maxInstallmentNumber, int price) {
super(imageUrl, drawableID, needyTitle, needyDescription, amountOfCollectedDonation, amountOfTargetDonation, amountOfDonater, category, campaignCode, maxInstallmentNumber,price);
cellType = "Needy";
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getCellType());
super.writeToParcel(dest,flags);
dest.writeInt(drawableID);
dest.writeInt(price);
dest.writeString(imageUrl);
dest.writeString(needyTitle);
dest.writeString(needyDescription);
dest.writeString(category);
dest.writeString(campaignCode);
dest.writeInt(maxInstallmentNumber);
dest.writeInt(userPurchaseAmount);
}
#Override
public void setUserPurchaseAmount(int userPurchaseAmount) {
super.setUserPurchaseAmount(userPurchaseAmount);
}
}
UserBasket
public class UserBasket implements Parcelable{
List<BaseCell> userBasket;
/**
* holds all items to be purchased
* */
public UserBasket(List<BaseCell> userBasket) {
this.userBasket = userBasket;
}
public UserBasket() {
userBasket = new ArrayList<>();
}
protected UserBasket(Parcel in) {
super();
setUserBasket(new ArrayList<BaseCell>());
userBasket = in.createTypedArrayList(BaseCell.CREATOR);
//in.readTypedList(userBasket,BaseCell.CREATOR);
}
public static final Parcelable.Creator<UserBasket> CREATOR = new Parcelable.Creator<UserBasket>() {
#Override
public UserBasket createFromParcel(Parcel in) {
return new UserBasket(in);
}
#Override
public UserBasket[] newArray(int size) {
return new UserBasket[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(userBasket);
}
public List<BaseCell> getUserBasket() {
return userBasket;
}
public void setUserBasket(List<BaseCell> userBasket) {
this.userBasket = userBasket;
}
/**
* Add to the basket list
* */
public void add(Needy donation) {
if (donation != null)
userBasket.add(donation);
}
/**
* Remove from basket list
* */
public void remove(int position)
{
if (userBasket.size()>0)
userBasket.remove(position);
}
}
sending userBasket arrayList with items from MainActivity
Navigate.navigateToPaymentPayuStart
(MainActivity.this,userBasket,"basket");
// userBasket arrayList with "basket" key
Receiving UserBasket in paymentPayu activity
UserBasket userBasket = getIntent().getParcelableExtra("basket");
How am i going to get UserBasket properly in paymentPayuActivity.
I appreciate for the help
Thank you.
It does seem like you are handling the Parcelable implementation wrong. e.i. you are reading some of the variables from the Parcel twice, which isn't allowed. So to improve this, we'll try to make your code a bit simpler. As Needy doesn't actually have any variables, it seems better to let BaseCell handle all of the parcelable implementation, i've tried to create a mock for you, so depending on the rest of your code it might need a bit of tweaking.
First i've removed all of the Parcelable implementation in Needy and is just pointing it's CREATOR to BaseCell.
public class Needy extends BaseCell {
protected Needy(Parcel in) {
super(in);
cellType ="Needy";
}
// Since Needy doesn't actually store any variables, we don't need a Creator for it.
// Just point it to BaseCell.CREATOR and let it handle it
public static final Parcelable.Creator<BaseCell> CREATOR = BaseCell.CREATOR;
public Needy(String imageUrl, int drawableID, String needyTitle, String needyDescription, int amountOfCollectedDonation, int amountOfTargetDonation, int amountOfDonater, String category, String campaignCode, int maxInstallmentNumber, int price) {
super(imageUrl, drawableID, needyTitle, needyDescription, amountOfCollectedDonation, amountOfTargetDonation, amountOfDonater, category, campaignCode, maxInstallmentNumber,price);
cellType = "Needy";
}
}
And then we'll let BaseCell handle all of the Parcelable implementation, like so:
public abstract class BaseCell implements Parcelable {
/**
* ALL OF YOUR VARIABLES, GETTERS, SETTERS AND CONSTRUCTORS GOES HERE
*/
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<BaseCell> CREATOR = new Parcelable.Creator<BaseCell>() {
#Override
public BaseCell createFromParcel(Parcel in) {
String cellType = in.readString();
if (cellType.equals("Needy")) {
return (Needy)new Needy(in);
} else if (cellType.equals("Qurban")) {
return (Qurban)new Qurban(in);
}
return null;
}
#Override
public BaseCell[] newArray(int size) {
return new BaseCell[size];
}
};
protected BaseCell(Parcel in) {
drawableID = in.readInt();
price = in.readInt();
imageUrl = in.readString();
needyTitle = in.readString();
needyDescription = in.readString();
category = in.readString();
campaignCode = in.readString();
maxInstallmentNumber = in.readInt();
userPurchaseAmount = in.readInt();
}
public void writeToParcel(Parcel out, int flags) {
// cellType written first, and read by Creator
out.writeString(cellType);
// the rest is read by the BaseCell constructor
out.writeInt(drawableID);
out.writeInt(price);
out.writeString(imageUrl);
out.writeString(needyTitle);
out.writeString(needyDescription);
out.writeString(category);
out.writeString(campaignCode);
out.writeInt(maxInstallmentNumber);
out.writeInt(userPurchaseAmount);
}
}
I am having some hard time trying to figure out how to write data with a Parcel object, I am new using this class and I've been doing some research but don't understand how to, here is the parcelable class
public class Item implements Parcelable {
private String iItemName;
private String iType;
private String iSerial;
private String iRetailer;
private String iLocation;
private String iValue;
private String iDescription;
public Item() {
super();
}
public Item (Parcel in) {
super();
this.iItemName = in.readString();
this.iType = in.readString();
this.iSerial = in.readString();
this.iRetailer = in.readString();
this.iLocation = in.readString();
this.iValue = in.readString();
this.iDescription = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(getItemName());
parcel.writeString(getType());
parcel.writeString(getSerial());
parcel.writeString(getRetailer());
parcel.writeString(getLocation());
parcel.writeString(getValue());
parcel.writeString(getDescription());
}
public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>(){
#Override
public Item createFromParcel(Parcel source) {
Item item = new Item();
item.iItemName = source.readString();
return item;
}
public Item [] newArray(int size) {
return new Item[size];
}
};
public String getItemName() {
return iItemName;
}
public void setItemName(String iItemName) {
this.iItemName = iItemName;
}
my question is if I want to create a new Item object I need to send as a parameter a Parcel Object am I right? so I can do something like:
String name = getString("name");
// how to add name to the parcel object?
Parcel parcel;
Item i = new Item(parcel);
No you do not need to. Your object now has two constructors. You should create the object like normal and call its setter methods. You should avoid manually creating parcels and rather use writeValue() and readValue() methods.
// Create an item as usual
Item myItem = new Item();
myItem.setItemName("name");
// Add it to a parcel
Parcel parcel = Parcel.obtain();
parcel.writeValue(myItem);
// Read the item back from the parcel
parcel.setDataPosition(0);
Item newItem = (Item) parcel.readValue(Item.class.getClassLoader());
// When you are finished with the parcel
parcel.recycle();
Usually you would create an object from a Parcel when receiving it from an Intent. In which case you would do the following.
// Create intent
Intent intent = new Intent(this, MyActivity.class);
Bundle itemBundle = new Bundle();
itemBundle.putParcelable("item_extra", myItem);
intent.putExtras(itemBundle);
startActivity(intent);
// In the activities onCreate(Bundle savedInstanceState)
Item myItem = getIntent().getParcelableExtra("item_extra");