how to pass Array list <Object> to another activity - android

I pass Array list to intent but give an error . so please tell me what is wrong.
This is my code
For Sending
addToCartList=new ArrayList<>();
Intent intent=new Intent(ShopingCart.this,SelectedProductFromShopingCartShow.class);
intent.putExtra("selectedList", (Serializable) addToCartList);
startActivity(intent);
And its my Receiver code
public class SelectedProductFromShopingCartShow extends AppCompatActivity{
ArrayList<ShowProducts> arrayList=new ArrayList<>();
String condition="SelectedItemsFromShoppingCart";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_product_from_shoping_cart_show);
arrayList= (ArrayList<ShowProducts>) getIntent().getSerializableExtra("selectedList");
}
}
Here's my error
07-25 20:15:54.280 16503-16503/com.sizdom.sizdomstockmanager E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Parcel: unable to marshal value ShowProducts{product_name='Almost new', product_photo='http://192.168.1.39:81/sizdom/sizdomstock/product_images/1-Almost-new-17-07-11-10-27-21.jpg', product_sizes=0, product_created_date='null'}
at android.os.Parcel.writeValue(Parcel.java:1235)
at android.os.Parcel.writeList(Parcel.java:622)
at android.os.Parcel.writeValue(Parcel.java:1195)
at android.os.Parcel.writeMapInternal(Parcel.java:591)
at android.os.Bundle.writeToParcel(Bundle.java:1627)
at android.os.Parcel.writeBundle(Parcel.java:605)
at android.content.Intent.writeToParcel(Intent.java:6660)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1865)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
at android.app.Activity.startActivityForResult(Activity.java:3370)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:3331)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:3566)
at android.app.Activity.startActivity(Activity.java:3534)
at com.sizdom.sizdomstockmanager.ShopingCart$1.onClick(ShopingCart.java:66)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5069)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
07-25 20:20:54.325 700-910/system_process E/InputDispatcher: channel '536cf278 com.sizdom.sizdomstockmanager/com.sizdom.sizdomstockmanager.SplashScrean (server)' ~ Channel is unrecoverably broken and will be disposed!
07-25 20:20:54.325 700-910/system_process E/InputDispatcher: channel '535f9848 com.sizdom.sizdomstockmanager/com.sizdom.sizdomstockmanager.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
07-25 20:20:54.381 21855-21855/? E/Trace: error opening trace file: No such file or directory (2)
07-25 20:20:54.557 21855-21855/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
ShowProducts class
public class ShowProducts {
String product_name;
String product_photo;
int product_sizes;
String product_created_date;
int size_id;
String size_name;
int size_price;
int size_cost;
int size_quantity;
int product_id;
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_photo() {
return product_photo;
}
public void setProduct_photo(String product_photo) {
this.product_photo = product_photo;
}
public int getProduct_sizes() {
return product_sizes;
}
public void setProduct_sizes(int product_sizes) {
this.product_sizes = product_sizes;
}
public String getProduct_created_date() {
return product_created_date;
}
public void setProduct_created_date(String product_created_date) {
this.product_created_date = product_created_date;
}
public int getSize_id() {
return size_id;
}
public void setSize_id(int size_id) {
this.size_id = size_id;
}
public String getSize_name() {
return size_name;
}
public void setSize_name(String size_name) {
this.size_name = size_name;
}
public int getSize_price() {
return size_price;
}
public void setSize_price(int size_price) {
this.size_price = size_price;
}
public int getSize_cost() {
return size_cost;
}
public void setSize_cost(int size_cost) {
this.size_cost = size_cost;
}
public int getSize_quantity() {
return size_quantity;
}
public void setSize_quantity(int size_quantity) {
this.size_quantity = size_quantity;
}
}

Please write ShowProducts implements Serializable in your model class.
This will resolve the issue.

There is no built in method to pass array list of objects from one activity to another activity via intents. You need to implement Parcelable interface.
Checkout developer console for the documentation.
https://developer.android.com/reference/android/os/Parcelable.html

The following code works for me:
Intent intent = new Intent(this, editList.class);
intent.putStringArrayListExtra("list", list);
startActivity(intent);
You can get the result using:
ArrayList<String>() array_list = new ArrayList<String>();
array_list = getIntent().getStringArrayListExtra("list");

First of all, serializing the items and passing it as the serializable list in Android is not recomended.
Android provides a secure and fast way to do this. We can use "Parcelable" interface. Use something like the below "Parcelable pojo" to move your list items from one activity to another.
public class ShowProducts implements Parcelable {
// THis class implents pracellable but does not create a CREATOR field
String product_name;
String product_photo;
int product_sizes;
String product_created_date;
int size_id;
String size_name;
int size_price;
int size_cost;
int size_quantity;
int product_id;
protected ShowProducts(Parcel in) {
product_name = in.readString();
product_photo = in.readString();
product_sizes = in.readInt();
product_created_date = in.readString();
size_id = in.readInt();
size_name = in.readString();
size_price = in.readInt();
size_cost = in.readInt();
size_quantity = in.readInt();
product_id = in.readInt();
}
public static final Creator<ShowProducts> CREATOR = new Creator<ShowProducts>() {
#Override
public ShowProducts createFromParcel(Parcel in) {
return new ShowProducts(in);
}
#Override
public ShowProducts[] newArray(int size) {
return new ShowProducts[size];
}
};
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_photo() {
return product_photo;
}
public void setProduct_photo(String product_photo) {
this.product_photo = product_photo;
}
public int getProduct_sizes() {
return product_sizes;
}
public void setProduct_sizes(int product_sizes) {
this.product_sizes = product_sizes;
}
public String getProduct_created_date() {
return product_created_date;
}
public void setProduct_created_date(String product_created_date) {
this.product_created_date = product_created_date;
}
public int getSize_id() {
return size_id;
}
public void setSize_id(int size_id) {
this.size_id = size_id;
}
public String getSize_name() {
return size_name;
}
public void setSize_name(String size_name) {
this.size_name = size_name;
}
public int getSize_price() {
return size_price;
}
public void setSize_price(int size_price) {
this.size_price = size_price;
}
public int getSize_cost() {
return size_cost;
}
public void setSize_cost(int size_cost) {
this.size_cost = size_cost;
}
public int getSize_quantity() {
return size_quantity;
}
public void setSize_quantity(int size_quantity) {
this.size_quantity = size_quantity;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(product_name);
parcel.writeString(product_photo);
parcel.writeInt(product_sizes);
parcel.writeString(product_created_date);
parcel.writeInt(size_id);
parcel.writeString(size_name);
parcel.writeInt(size_price);
parcel.writeInt(size_cost);
parcel.writeInt(size_quantity);
parcel.writeInt(product_id);
}
}
You can use below code to move your array list to another activity.
addToCartList=new ArrayList<>();
Intent intent=new Intent(ShopingCart.this,SelectedProductFromShopingCartShow.class);
intent.putParcelableArrayListExtra("selectedList",addToArrayList);
startActivity(intent);
Use below code to receive it in another activity.
getIntent().getParcelableArrayListExtra("selectedList");
For Android Studio the shortcut for implementing Parcelable interface is ALT+ENTER.
Just implement the Parcelable interface with implementing the Java class.
Android studio will intimate you with red error to implement and create the CREATOR. Android Studio will generate the beautiful code for you.
That's it. Enjoy.

Your ShowProducts object must implements Parcelable.
You can easily make your Object parcelable with an online tool like : http://www.parcelabler.com/
This post can help you : How can I make my custom objects Parcelable?

Please try this ...
addToCartList=new ArrayList<>();
Intent intent=new
Intent(ShopingCart.this,SelectedProductFromShopingCartShow.class);
intent.putStringArrayListExtra("selectedList", addToCartList);
startActivity(intent);
In Your receiving Activity...
public class SelectedProductFromShopingCartShow extends AppCompatActivity{
ArrayList<ShowProducts> arrayList=new ArrayList<>();
String condition="SelectedItemsFromShoppingCart";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_product_from_shoping_cart_show);
arrayList= (ArrayList<ShowProducts>)
getIntent().getStringArrayListExtra("selectedList");
}}

Related

Firebase real database values differ from the retrieved ones

So, in realtime database I have:
When I retrieve data from database I get:
Model class looks like:
public class User implements Parcelable {
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
#Override
public User createFromParcel(Parcel source) {
return new User(source);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
...
private String hasToPayFromPastRides;
private String didNotPayCount;
...;
public User() {
}
public User(..., String didNotPayCount, String hasToPayFromPastRides) {
...
this.didNotPayCount = didNotPayCount;
this.hasToPayFromPastRides = hasToPayFromPastRides;
}
protected User(Parcel in) {
...
this.didNotPayCount = in.readString();
this.hasToPayFromPastRides = in.readString();
}
...
public String getDidNotPayCount() {
return didNotPayCount;
}
public void setDidNotPayCount(String didNotPayCount) {
this.didNotPayCount = didNotPayCount;
}
public String hasToPayFromPastRides() {
return hasToPayFromPastRides;
}
public void setHasToPayFromPastRides(String hasToPayFromPastRides) {
this.hasToPayFromPastRides = hasToPayFromPastRides;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.userId);
dest.writeString(this.userFullName);
dest.writeString(this.userEmail);
dest.writeString(this.userPhoneNumber);
dest.writeString(this.userAvatarUrl);
dest.writeString(this.userLocalAvatar);
dest.writeString(this.userAddress);
dest.writeString(this.userCity);
dest.writeString(this.userArea);
dest.writeString(this.userPostalCode);
dest.writeString(this.userRating);
dest.writeString(this.userTotalRating);
dest.writeString(this.totalTrips);
dest.writeString(this.riskCount);
dest.writeString(this.isBlocked);
dest.writeString(this.isDefaulter);
dest.writeString(this.pendingRating);
dest.writeParcelable(this.pendingRateObj, flags);
dest.writeString(this.didNotPayCount);
dest.writeString(this.hasToPayFromPastRides);
}
}
What surprises me is that one value gets read correctly "didNotPayCount" when "hasToPayFromPastRides" is null. Any ideas?
Your getter isn't named correctly:
public String hasToPayFromPastRides()
It should be:
public String getHasToPayFromPastRides()

How to populate values to variables of a parcelable class whose object we are sending from one activity to the other

Stack trace:
11-16 20:39:42.374 30640-30703/? E/LocalFingerprints: cannot compute fingerprint for: content://media/external/images/media/41373
java.io.FileNotFoundException: No such file or directory
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:682)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1063)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:904)
at android.content.ContentResolver.openInputStream(ContentResolver.java:629)
at cak.a(PG:159)
at bzj.a(PG:123)
at com.google.android.apps.plus.service.FingerprintScannerIntentService.onHandleIntent(PG:79)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
This is the FirstActivity:
void handleBlogEditClick(){
if (BlogDetailActivity.this!= null) {
BlogDetailVO blogDetailVO=new BlogDetailVO(getArgs().getmId(),getArgs().getmName().toString(),getArgs().getmDescription().toString());
blogDetailVO.mCoverPic.setmImageUrl(getArgs().getmImageUrl());
Intent intent = new Intent(BlogDetailActivity.this, EditBlogActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("blogDetailVO",blogDetailVO);
startActivity(intent);
}
}
Second activity:
mState = new EditBlogState();
Intent intent = getIntent();
BlogDetailVO blogDetailVO =(BlogDetailVO) intent.getParcelableExtra("blogDetailVO");
mState.mCoverPhotoStory.setmName(blogDetailVO.getmName());
mView.updateBlogTitle(mState.mCoverPhotoStory.getmName());
Other things in the first and second activity code is irrelevant to this so i shared this much
public class BlogDetailVO extends BlogFeedVO implements Parcelable{
PhotoStoryVO mCoverPic;
List<PhotoStoryVO> mPhotoStories;
LocationVO mLocationVO;
public BlogDetailVO(String mId, String mName, String mDescription) {
super(mId, mName, mDescription);
}
protected BlogDetailVO(Parcel in) {
super(in);
mCoverPic = in.readParcelable(PhotoStoryVO.class.getClassLoader());
mPhotoStories = in.createTypedArrayList(PhotoStoryVO.CREATOR);
mLocationVO = in.readParcelable(LocationVO.class.getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeParcelable(mCoverPic, flags);
dest.writeTypedList(mPhotoStories);
dest.writeParcelable(mLocationVO, flags);
}
#Override
public int describeContents() {
return hashCode();
}
public static final Creator<BlogDetailVO> CREATOR = new Creator<BlogDetailVO>() {
#Override
public BlogDetailVO createFromParcel(Parcel in) {
return new BlogDetailVO(in);
}
#Override
public BlogDetailVO[] newArray(int size) {
return new BlogDetailVO[size];
}
};
public PhotoStoryVO getmCoverPic() {
return mCoverPic;
}
public void setmCoverPic(PhotoStoryVO mCoverPic) {
this.mCoverPic = mCoverPic;
}
public List<PhotoStoryVO> getmPhotoStories() {
return mPhotoStories;
}
public void setmPhotoStories(List<PhotoStoryVO> mPhotoStories) {
this.mPhotoStories = mPhotoStories;
}
public LocationVO getmLocationVO() {
return mLocationVO;
}
public void setmLocationVO(LocationVO mLocationVO) {
this.mLocationVO = mLocationVO;
}
}
I am new to android. so sorry if the question is silly. But i am really stuck and need help. i am sending BlogDetailVO class object to another activity. The second line is showing null. so can't i populate value in this way? Eventually it crashes.
BlogDetailVO blogDetailVO=new BlogDetailVO(getArgs().getmId(),getArgs().getmName().toString(),getArgs().getmDescription().toString());
blogDetailVO.mCoverPic.setmImageUrl(getArgs().getmImageUrl()); //this gives the error!!
Intent intent = new Intent(BlogDetailActivity.this, EditBlogActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("blogDetailVO",blogDetailVO); startActivity(intent);
So how to populate values to BlogDtailVO class so to send it to the other activity?
In the receiving activity I am receiving it this way:
Intent intent = getIntent();
BlogDetailVO blogDetailVO =(BlogDetailVO) intent.getParcelableExtra("blogDetailVO");

Firebase onClick list in android

My goal is to create an app that in basics have two different activities, one in which the user creates a "protocol" (EditorActivity) and on in which the user can view them in a listview(CatalogActivity). If there is something wrong with a protocol, the user must be able to press one of the list view items in the listview, and from there go back in to the EditorActivity and edit the specific item.
My problem is that I have not figured out how to get the old data from the CatalogActivity in to the EditorActivity.
From firebase console:
[Firebase structure][1]
CustomProtocol:
public class CustomProtocol {
public String dateDrill;
public String pileID;
public boolean cleaned;
public CustomProtocol() {
}
public CustomProtocol(String pileID,
String dateDrill,
boolean cleaned) {
this.pileID = pileID;
this.dateDrill = dateDrill;
this.cleaned = cleaned;
}
public void setPileID(String pileID) {
this.pileID = pileID;
}
public String getPileID() {
return pileID;
}
public void setDateDrill(String dateDrill) {
this.dateDrill = dateDrill;
}
public String getDateDrill() {
return dateDrill;
}
}
Snippet from CatalogActivity:
final String projectNumber = projectPrefs.getString(getString(R.string.settings_project_number_key), getString(R.string.settings_project_number_by_default));
mFirebaseDatabase = FirebaseDatabase.getInstance();
mProtocolDatabaseReference = mFirebaseDatabase.getReference().child(projectNumber);
List<CustomProtocol> protocols = new ArrayList<>();
mProtocolAdapter = new ProtocolAdapter(this, R.layout.item_protocol, protocols);
mProtocolListView.setAdapter(mProtocolAdapter);
attachDatabaseReadListener();
mProtocolListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
intent.putExtra("Exiting protocol", EXISTING_PROTOCOL);
}
});
}
EditorActivty:
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
EXISTING_PROTOCOL = intent.getBooleanExtra("Exiting protocol", false);
mEditorFirebaseDatabase = FirebaseDatabase.getInstance();
mEditorProtocolDatabaseReference =
mEditorFirebaseDatabase.getReference().child(projectNumber);
if (EXISTING_PROTOCOL)
mProtocolDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//WHAT GOES HERE SO THAT I CAN POPULATE THE TEXTVIEWS IN THE ACTIVITY_EDITOR WITH THE EXISTING VALUES?
}}
And after this I'm stuck. I guess that I must add something more to the databasereference in the EditorActivity, but I cannot figure out what? Since I don't know the pileID until after the listitem has been clicked? Is there an easier way to do this?
Thank you in advance!
1]: https://i.stack.imgur.com/Bt1mZ.png
You can pass List<CustomProtocol> through intent.
Your CustomProtocol must be implement Parcelable.
Same question is here
1.Make CustomProtocol Parcelable, IDE can do it automatically
public class CustomProtocol implements Parcelable {
public String dateDrill;
public String pileID;
public boolean cleaned;
public CustomProtocol() {
}
public CustomProtocol(String pileID,
String dateDrill,
boolean cleaned) {
this.pileID = pileID;
this.dateDrill = dateDrill;
this.cleaned = cleaned;
}
protected CustomProtocol(Parcel in) {
dateDrill = in.readString();
pileID = in.readString();
cleaned = in.readByte() != 0;
}
public static final Creator<CustomProtocol> CREATOR = new Creator<CustomProtocol>() {
#Override
public CustomProtocol createFromParcel(Parcel in) {
return new CustomProtocol(in);
}
#Override
public CustomProtocol[] newArray(int size) {
return new CustomProtocol[size];
}
};
public void setPileID(String pileID) {
this.pileID = pileID;
}
public String getPileID() {
return pileID;
}
public void setDateDrill(String dateDrill) {
this.dateDrill = dateDrill;
}
public String getDateDrill() {
return dateDrill;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(dateDrill);
parcel.writeString(pileID);
parcel.writeByte((byte) (cleaned ? 1 : 0));
}
}
2.Pass clicked protocol from CatalogActivity to EditorActivity using intent,
mProtocolListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
intent.putExtra("Exiting protocol", EXISTING_PROTOCOL);
intent.putExtra("Clicked protocol object", protocols.get(position));
}
});
3.In editor activity read the clicked protocol though intent.
EXISTING_PROTOCOL = intent.getBooleanExtra("Exiting protocol", false);
protocol = intent.getParcelableExtra("Clicked protocol object");
4.
public void onDataChange(DataSnapshot dataSnapshot) {
//WHAT GOES HERE SO THAT I CAN POPULATE THE TEXTVIEWS IN THE ACTIVITY_EDITOR WITH THE EXISTING VALUES?
// Ans: Find text views by id and set corresponding text from protocol read above.
}}

Android:Parcel: unable to marshal value

I am getting below error while passing custom Arraylist in intent.
Parcel: unable to marshal value com.kahoindia.dev.models.KaHOStudentModel#62bceea
This is how am passing
KaHOSelectedObj selObject = new KaHOSelectedObj(); /*Parcelable */
selObject.setmIntent(mContext);
selObject.setSelectedStudents(mSelectedStudents);
Intent intent = new Intent(mContext, KaHOMyInputsActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("SelectedStudents", selObject);
intent.putExtras(bundle);
startActivity(intent);
I am using Parcelable, but am getting unable to marshall.. run time error in the calling function at line start activity. Please help how to proceed with!
public class KaHOSelectedObj implements Parcelable
{
private Context mIntent;
private ArrayList<KaHOStudentModel> mSelectedStudentObj;
public Context getmIntent() {
return mIntent;
}
public void setmIntent(Context mIntent) {
this.mIntent = mIntent;
}
public ArrayList<KaHOStudentModel> getSelectedStudents() {
return mSelectedStudentObj;
}
public void setSelectedStudents(ArrayList<KaHOStudentModel> mObjects) {
this.mSelectedStudentObj = mObjects;
}
public static final Parcelable.Creator<KaHOSelectedObj> CREATOR = new Creator<KaHOSelectedObj>() {
#Override
public KaHOSelectedObj createFromParcel(Parcel source) {
KaHOSelectedObj selObj = new KaHOSelectedObj();
selObj.mSelectedStudentObj = source.readArrayList(null);
return selObj;
}
#Override
public KaHOSelectedObj[] newArray(int size) {
return new KaHOSelectedObj[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeList(mSelectedStudentObj);
}
}

Passing ArrayLists in Android

I'm trying to pass array lists between activities in Android. The lists contains strings. I've read a lot about Parcelable. Would I need to create a Parcelable to pass a String array list? As of now I am using putStringArrayListExtra() and getSringArrayListExtra() to pass the lists through intents.
Here is some of my code.
Intent load = new Intent(getApplicationContext(), HelloTabWidget.class);
load.putStringArrayListExtra("albums", albums);
load.putStringArrayListExtra("songs", songs);
load.putStringArrayListExtra("artists", artists);
load.putStringArrayListExtra("fileName", fileName);
This is my onCreate method for the acticity which obtains the array list.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songlist);
Bundle extras = getIntent().getExtras();
isArtists = extras.getBoolean("artists");
isAlbums = extras.getBoolean("albums");
isSongs = extras.getBoolean("songs");
Intent get = getIntent();
songs = get.getStringArrayListExtra("songs");
artists = get.getStringArrayListExtra("artists");
albums = get.getStringArrayListExtra("albums");
fileName = get.getStringArrayListExtra("fileName");
if(isArtists == true)
updateArtistsList();
else if(isAlbums == true)
updateAlbumsList();
else if(isSongs == true)
updateSongList();
}
The class which retrieves the list is supposed to create a listView from the data in the lists. Whenever I run the code i get nullPointerExceptions when trying to make the lists. I know that my listView code works, so I have narrowed down the problem to the intents which pass the array lists.
Thanks in advance.
EDIT:
Here are the first few lines from the logcat.
12-28 03:03:42.313: E/AndroidRuntime(873): FATAL EXCEPTION: main
12-28 03:03:42.313: E/AndroidRuntime(873): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adam.mediaplayer/com.adam.mediaplayer.HelloTabWidget}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adam.mediaplayer/com.adam.mediaplayer.MakeListActivity}: java.lang.NullPointerException
It depends on the type of arraylist
putIntegerArrayListExtra(String name, ArrayList<Integer> value)
putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
putStringArrayListExtra(String name, ArrayList<String> value)
putCharSequenceArrayListExtra(String name, ArrayList<CharSequence> value)
Then you can read from you next activity by replacing put with get with key string as argument,eg
myIntent.getStringArrayListExtra("arrayListName");
Here is how you can pass an ArrayList :
MyListClass.java - Custom class
public class MyListClass implements Parcelable{
private int test;
public MyListClass()
{}
public MyListClass(Parcel read){
test = read.readInt();
}
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
public static final Parcelable.Creator<MyListClass> CREATOR =
new Parcelable.Creator<MyListClass>() {
#Override
public MyListClass createFromParcel(Parcel source) {
return new MyListClass(source);
}
#Override
public MyListClass[] newArray(int size) {
return new MyListClass[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(test);
}
}
MyParcelable.java
public class MyParcelable implements Parcelable {
private List<MyListClass> arrList = new ArrayList<MyListClass>();
private int myInt = 0;
private String str = null;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public List<MyListClass> getArrList() {
return arrList;
}
public void setArrList(List<MyListClass> arrList) {
this.arrList = arrList;
}
public int getMyInt() {
return myInt;
}
public void setMyInt(int myInt) {
this.myInt = myInt;
}
MyParcelable() {
// initialization
arrList = new ArrayList<MyListClass>();
}
public MyParcelable(Parcel in) {
myInt = in.readInt();
str = in.readString();
in.readTypedList(arrList, MyListClass.CREATOR);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel outParcel, int flags) {
outParcel.writeInt(myInt);
outParcel.writeString(str);
outParcel.writeTypedList(arrList);
}
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
#Override
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
#Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
}
MainAcitivty.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrList.add(new MyListClass());
arrList.get(0).setTest(200);
MyParcelable object = new MyParcelable();
object.setMyInt(100);
object.setArrList(arrList);
Intent intent = new Intent(MainActivity.this,ReceiverParcel.class);
intent.putExtra("parcel", object);
startActivity(intent);
}
ReceiverParcel.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
MyParcelable object = b.getParcelable("parcel");
System.out.println(object.getArrList().get(0).getTest());
System.out.println(object.getMyInt());
}

Categories

Resources