Java android ava.lang.RuntimeException: Parcelable encountered IOException writing serializable object - java

I want to in finish Activity with result put a List of objets I created a class which look like this :
public class Vals implements Serializable {
public ArrayList<RowBean> data;
public Vals(ArrayList<RowBean> data) {
this.data = data;
}
}
Next in activity (fragment) I did this when I finish my activity with result :
private void finishWithResult() {
Bundle conData = new Bundle();
conData.putString("param_result", counter + "");
Intent intent = new Intent();
intent.putExtras(conData);
ArrayList<RowBean> rows = new ArrayList<>();
for(RowBean row : rowBeen){
if(row.isSelected())
rows.add(row);
}
intent.putExtra(ROW_BEAN_DATA, new Vals(rows));
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
And in console I have :
FATAL EXCEPTION: main
Process: com.maps, PID: 10222 java.lang.RuntimeException:
Parcelable encountered IOException writing serializable object (name = com.maps.Utils.Vals) at
android.os.Parcel.writeSerializable(Parcel.java:1316) at android.os.Parcel.writeValue(Parcel.java:1264) at android.os.Parcel.writeArrayMapInternal(Parcel.java:618) at android.os.Bundle.writeToParcel(Bundle.java:1692) at android.os.Parcel.writeBundle(Parcel.java:636) at android.content.Intent.writeToParcel(Intent.java:7582) at android.app.ActivityManagerProxy.finishActivity(ActivityManagerNative.java:2517)at android.app.Activity.finish(Activity.java:4324) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.finishWithResult(FragmentListOfAllObjetsToReportActivity.java:156) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.confirmChoose(FragmentListOfAllObjetsToReportActivity.java:160) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity.access$200(FragmentListOfAllObjetsToReportActivity.java:34) at com.maps.Fragment.FragmentListOfAllObjetsToReportActivity$3.onClick(FragmentListOfAllObjetsToReportActivity.java:102) at android.view.View.performClick(View.java:4640)
This is onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 90:
if (resultCode == RESULT_OK) {
Bundle res = data.getExtras();
String result = res.getString("param_result");
int count = Integer.parseInt(result);
if (count != 1)
tvChooseObjects.setText("Wybrano " + count + " obiekty");
else
tvChooseObjects.setText("Wybrano " + count + " obiekt");
rowBeen = ((Vals) getIntent().getSerializableExtra(FragmentListOfAllObjetsToReportActivity.ROW_BEAN_DATA)).data;
Toast.makeText(getApplicationContext(), rowBeen.size() + " " , Toast.LENGTH_LONG).show();
}
break;
}

Try replacing Serializable implementation with Parcelable in Vals & RawBean classes
Replace getSerializableExtra with getParcelableExtra in *onActivityResult**
Vals.java
public class Vals implements Serializable, Parcelable {
public ArrayList<RowBean> data;
public Vals(ArrayList<RowBean> data) {
this.data = data;
}
protected Vals(Parcel in) {
if (in.readByte() == 0x01) {
data = new ArrayList<RowBean>();
in.readList(data, RowBean.class.getClassLoader());
} else {
data = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (data == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(data);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Vals> CREATOR = new Parcelable.Creator<Vals>() {
#Override
public Vals createFromParcel(Parcel in) {
return new Vals(in);
}
#Override
public Vals[] newArray(int size) {
return new Vals[size];
}
};
}
RawBean.java
public class RowBean implements Serializable, Parcelable {
public String title;
public boolean selected;
public RowBean(){
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public RowBean(boolean selected, String title) {
this.selected = selected;
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
protected RowBean(Parcel in) {
title = in.readString();
selected = in.readByte() != 0x00;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeByte((byte) (selected ? 0x01 : 0x00));
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<RowBean> CREATOR = new Parcelable.Creator<RowBean>() {
#Override
public RowBean createFromParcel(Parcel in) {
return new RowBean(in);
}
#Override
public RowBean[] newArray(int size) {
return new RowBean[size];
}
};
}

Check out This example
public class Vals implements Serializable {
int id;
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Vals(int id, String name) {
this.id = id;
this.name = name;
}
}
Add DataWraperClass
public class DataWrapper implements Serializable {
private ArrayList<Vals > mServicesList;
public DataWrapper(ArrayList<Vals > data) {
this.mServicesList = data;
}
public ArrayList<Vals > getServicesList() {
return this.mServicesList;
}
}
Create Intent Like This
DataWrapper mServiceListData = new DataWrapper(yourarraylist);
mIntent = new Intent(KitVerfiyActivity.this, BeneficiaryDetailsActivity.class);
mIntent.putExtra("arr_list", mServiceListData);
startActivity(mIntent);
get arraylist from Intent like this
DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("arr_list");
mArrayCaseFullList = dw.getServicesList();
Hope this will help you

Use Below method :
private void finishWithResult() {
Bundle conData = new Bundle();
conData.putString("param_result", counter + "");
Intent intent = new Intent();
ArrayList<RowBean> rows = new ArrayList<>();
for(RowBean row : rowBeen){
if(row.isSelected())
rows.add(row);
}
conData.putSerializable(ROW_BEAN_DATA, new Vals(rows));
intent.putExtras(conData);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
Retrieve your data like below code :
Bundle bundle = getIntent().getExtras();
rowBeen = ((Vals) bundle.getSerializable(ROW_BEAN_DATA);

Related

How do I implement polymorphism properly with Interface?

I have 2 model classes(Data,Title) which contain the same field:
String dataID. I want to get both of this IDs with interface implementation.
I am passing Title model through Bundle to another Activity, passing Data model through Bundle in that same activity(just creating new instance of the activity and resetting information).
I want both of my model classes to implement SharedID interface, with method String getSharedId();
How can I get different ids but from different models? I need to put only one parameter and it should be String in my ViewModelFactory constructor.
public class Data implements SharedId,Parcelable {
private String text;
private String textHeader;
private int viewType;
private String mainId;
private String dataID;
public Data() { }
public String getDataID() {
return dataID;
}
public void setDataID(String dataID) {
this.dataID = dataID;
}
public String getText() {return (String) trimTrailingWhitespace(text); }
public void setText(String text) {
this.text = (String) trimTrailingWhitespace(text);
}
public String getTextHeader() {
return (String) trimTrailingWhitespace(textHeader);
}
public void setTextHeader(String textHeader) {
this.textHeader = textHeader;
}
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
public String getMainId() {
return mainId;
}
public void setMainId(String mainId) {
this.mainId = mainId;
}
protected Data(Parcel in) {
text = in.readString();
textHeader = in.readString();
viewType = in.readInt();
mainId = in.readString();
dataID = in.readString();
}
#Override
public String toString() {
return "Data{" +
"order=" +
", text='" + text + '\'' +
", textHeader='" + textHeader + '\'' +
", viewType=" + viewType +
'}';
}
#SuppressWarnings("StatementWithEmptyBody")
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null) {
return "";
}
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
public static final Creator<Data> CREATOR = new Creator<Data>() {
#Override
public Data createFromParcel(Parcel in) {
return new Data(in);
}
#Override
public Data[] newArray(int size) {
return new Data[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(text);
dest.writeString(textHeader);
dest.writeInt(viewType);
dest.writeString(mainId);
dest.writeString(dataID);
}
#Override
public String getSharedDataId() {
return getDataID();
}
}
public class Title implements SharedId,Parcelable {
private String dataID;
private String title;
public Title() { }
protected Title(Parcel in) {
dataID = in.readString();
title = in.readString();
}
public String getDataID() {
return dataID;
}
public void setDataID(String dataID) {
this.dataID = dataID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public static final Creator<Title> CREATOR = new Creator<Title>() {
#Override
public Title createFromParcel(Parcel in) {
return new Title(in);
}
#Override
public Title[] newArray(int size) {
return new Title[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dataID);
dest.writeString(title);
}
#NonNull
#Override
public String toString() {
return "Title{" +
"dataID='" + dataID + '\'' +
", titleOrder=" +
", title='" + title + '\'' +
'}';
}
#Override
public String getSharedDataId() {
return getDataID();
}
}
And My DetailActivity code, I already succeeded with the mission of passing id, but i need to do this trough interfaces :( So help me out friends, would really appreciate it!
public class DetailActivity extends AppCompatActivity implements
DetailAdapter.OnDialogClickListener,
DetailAdapter.OnDetailClickListener {
private static String id;
private String parentId;
private Data data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView tvToolbarTitle = findViewById(R.id.title_toolbar_detail);
tvToolbarTitle.setSelected(true);
findViewById(R.id.btn_back).setOnClickListener(v -> finish());
ArrayList<SharedId> sharedIds = new ArrayList<>();
sharedIds.add(new Title());
sharedIds.add(new Data());
for (SharedId sharedId : sharedIds){
System.out.println(sharedId.getSharedDataId());
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
}
if (bundle != null) {
Title model = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
Data childModel = bundle.containsKey("idDetail") ? bundle.getParcelable("idDetail") : null;
String parentId = bundle.getString("mainScreenId");
if (parentId != null) {
this.parentId = parentId;
}
if (model != null) {
this.id = model.getDataID();
tvToolbarTitle.setText(model.getTitle());
}
if (childModel != null) {
this.id = childModel.getDataID();
tvToolbarTitle.setText(childModel.getTextHeader());
}
}
RecyclerView recyclerView = findViewById(R.id.rv_detail);
DetailAdapter adapter = new DetailAdapter(this, this);
recyclerView.setAdapter(adapter);
// TODO: 3/1/19 change it to single ID // DetailViewModelFactory(); // id != null ? id : parentId
DetailViewModelFactory detailViewModelFactory = new DetailViewModelFactory(id != null ? id : parentId);
DetailActivityViewModel viewModel = ViewModelProviders.of(this, detailViewModelFactory).get(DetailActivityViewModel.class);
FirebaseListLiveData<Data> liveData = viewModel.getLiveDataQuery();
liveData.observe(this, adapter::setNewData);
}
#Override
public void onDialogClicked(#NonNull String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(HtmlCompat.fromHtml(text, 0, null, new HandlerHtml()));
builder.setPositiveButton("Ok", null);
builder.show();
}
#Override
public void onDetailClicked(Data data) {
Intent intent = new Intent();
DetailActivity.open(DetailActivity.this);
intent.putExtra("idDetail", data);
intent.putExtra("mainScreenId", id);
startActivity(intent);
}
public static void open(#NonNull Context context) {
context.startActivity(new Intent(context, InfoActivity.class));
}
}
I found a bit different, but working solution!
I create an interface
public interface SharedId {
String getSharedDataId();
String getHeader();
}
Both of my model classes Data + Title implemented Interface and methods from it.
In DetailActivity i created 2 Strings.
private String mainId;
private String detailId;
And then passed ids with my model classes with bundle
`SharedId mainId = new Title();
SharedId detailId = new Data();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mainId = bundle.containsKey("ID") ? bundle.getParcelable("ID") : null;
detailId = bundle.containsKey("idDetail") ?
bundle.getParcelable("idDetail") : null;
}
if (mainId != null) {
this.detailId = mainId.getSharedDataId();
tvToolbarTitle.setText(mainId.getHeader());
}
if (detailId != null) {
this.mainId = detailId.getSharedDataId();
tvToolbarTitle.setText(detailId.getHeader());
}
And passed in my ViewmodelFactory
DetailViewModelFactory detailViewModelFactory =
new DetailViewModelFactory(this.detailId != null ?
this.detailId : this.mainId);

How to share an Arraylist through Intent.ACTION_SEND

i'm developing an App which has an Arraylist with the name of the product and its quantity. Now i want to make an Intent to share this information like a list through the WhatsApp, email or whatever he is able.
Example:
List<Compartilhar> listaCompras2 = new ArrayList<>( );
//listaCompras2 has a for loop to to get a new content every time the client input a product and quantity.
listaCompras2.add(new Compartilhar(doc.getString("inputNome"), doc.getString("inputQtd")));
fabShare = view.findViewById(R.id.fabShare);
fabShare.setOnClickListener(new View.OnClickListener( ) {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
for (int i=0 ; i < listaCompras2.size(); i++)
{
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Produto: " + listaCompras2.get(0).getProduto() + " Qtd: " + listaCompras2.get(0).);
i++;
}
startActivity(Intent.createChooser(shareIntent, "share Via"));
}
});
import java.util.ArrayList;
import java.util.List;
public class Compartilhar implements Parcelable {
private List<String> produto;
private List<String> qtd;
public Compartilhar(List<String> produto, List<String> qtd) {
this.produto = produto;
this.qtd = qtd;
}
public List<String> getProduto() {
return produto;
}
public void setProduto(List<String> produto) {
this.produto = produto;
}
public List<String> getQtd() {
return qtd;
}
public void setQtd(List<String> qtd) {
this.qtd = qtd;
}
protected Compartilhar(Parcel in) {
if (in.readByte() == 0x01) {
produto = new ArrayList<String>();
in.readList(produto, String.class.getClassLoader());
} else {
produto = null;
}
if (in.readByte() == 0x01) {
qtd = new ArrayList<String>();
in.readList(qtd, String.class.getClassLoader());
} else {
qtd = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (produto == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(produto);
}
if (qtd == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(qtd);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Compartilhar> CREATOR = new Parcelable.Creator<Compartilhar>() {
#Override
public Compartilhar createFromParcel(Parcel in) {
return new Compartilhar(in);
}
#Override
public Compartilhar[] newArray(int size) {
return new Compartilhar[size];
}
};
}
To put an ArrayList into the intent you can use the
putParcelableArrayListExtra(String name, ArrayList value) method. Please pay attention that this method allows to pass a list of items what implements the Parcelable interface. So in your case, your Compartilhar class should implement the Parcelable interface.
As i understand you want share these items to other apps, it can be tricky, because every standalone app(Whatsapp, etc.) has it's own logic how they handles/parses the data from the intent.

How to implement parcelable with my custom class containing Hashmap and SparseArray?

I need to implement parcelable in my custom class "ArtistInfo"
with the following structure:
public class ArtistInfo implements Parcelable {
private String artist;
// album name to list of ids of songs
private HashMap> albumInfo;
// song id to songInfo
private SparseArray songsMap;
protected ArtistInfo(Parcel in) {
artist = in.readString();
}
public static final Creator CREATOR = new Creator() {
#Override
public ArtistInfo createFromParcel(Parcel in) {
return new ArtistInfo(in);
}
#Override
public ArtistInfo[] newArray(int size) {
return new ArtistInfo[size];
}
};
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void addSongsInfoToAlbum(List songsInfo, String album) {
if (albumInfo == null) {
albumInfo = new HashMap();
}
if (songsMap == null) {
songsMap = new SparseArray();
}
List songsIds = new ArrayList();
for (SongInfo songInfo : songsInfo) {
songsIds.add(songInfo.getId());
songsMap.put(songInfo.getId(), songInfo);
}
List songsIdsForAlbum = getSongIdsForAlbum(album);
songsIdsForAlbum.addAll(songsIds);
albumInfo.put(album, songsIdsForAlbum);
}
private List getSongIdsForAlbum(String album) {
if (albumInfo == null) {
return new ArrayList();
}
List songsIds = albumInfo.get(album);
return songsIds == null ? new ArrayList() : songsIds;
}
public HashMap> getAlbumInfo() {
return albumInfo;
}
public SparseArray getSongsMap() {
if (songsMap == null) {
songsMap = new SparseArray();
}
return songsMap;
}
#Override
public String toString() {
return "ArtistInfo{" +
"artist='" + artist + '\'' +
", albumInfo=" + albumInfo.toString() +
", songsMap=" + songsMap.toString() +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(artist);
}
}
And following is the structure of the "SongInfo" class used in the above class:
public class SongInfo implements Parcelable {
private Integer id;
private String name;
private String url;
public SongInfo(Integer id, String name, String url) {
this.id = id;
this.name = name;
this.url = url;
}
protected SongInfo(Parcel in) {
if (in.readByte() == 0) {
id = null;
} else {
id = in.readInt();
}
name = in.readString();
url = in.readString();
}
public static final Creator CREATOR = new Creator() {
#Override
public SongInfo createFromParcel(Parcel in) {
return new SongInfo(in);
}
#Override
public SongInfo[] newArray(int size) {
return new SongInfo[size];
}
};
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeInt(id);
}
dest.writeString(name);
dest.writeString(url);
}
}
Now as you can see there is no problem in implementing the Parcelable interface in the SongInfo class, but I am not able to understand how to read and write the albumInfo and songsMap variables in the Constructor and writeToParcel method respectively. Can someone please help me understand how should I go ahead with that. Thanks!
The idea is iterate through each item in albumInfo and songsMap then add it into Parcelable.
Write to parcel.
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(artist);
// Write album info
dest.writeInt(albumInfo.size());
for (Map.Entry<String, List<Integer>> item : albumInfo.entrySet()) {
dest.writeString(item.getKey());
dest.writeList(item.getValue());
}
// Write song map
dest.writeInt(songsMap.size());
for (int i = 0; i < songsMap.size(); i++) {
int key = songsMap.keyAt(i);
dest.writeInt(key);
dest.writeParcelable(songsMap.get(key), flags);
}
}
Read from parcel
protected ArtistInfo(Parcel in) {
artist = in.readString();
// Read album info
albumInfo = new HashMap<>();
int albumInfoSize = in.readInt();
for (int i = 0; i < albumInfoSize; i++) {
String key = in.readString();
List<Integer> value = new ArrayList<>();
in.readList(value, null);
albumInfo.put(key, value);
}
// Read song map
songsMap = new SparseArray<>();
int songsMapSize = in.readInt();
for (int i = 0; i < songsMapSize; i++) {
int key = in.readInt();
SongInfo value = in.readParcelable(SongInfo.class.getClassLoader());
songsMap.put(key, value);
}
}

Adding Arraylist to custom object not updating values in android

In the below android activity, trying to display data in a view pager and it is working as expected.
But in loadItemsForSuppliers method, when i am adding SupplierAndItemList object to it's arraylist, value returned from getInventoriesByItemDetails method is not updating properly rather takes last value always.
Can some body assist me what's wrong here ?
public class ScreenSlidePagerActivity extends BaseActivity {
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private Dealer dealerObject;
private ArrayList<ItemDetail> itemDetails;
private List<Dealer> supplierList;
private ArrayList<SupplierAndItemList> supplierAndItemLists = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
dealerObject = getIntent().getParcelableExtra(UiConstants.DEALER_OBJECT);
itemDetails = getIntent().getParcelableArrayListExtra("itemDetails");
supplierList = dealerObject.getParentSalesPoints(this,dealerObject.getServerId());
loadItemsForSuppliers();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(),supplierAndItemLists);
mPager.setAdapter(mPagerAdapter);
}
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id);
}
return inventories;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<SupplierAndItemList> supplierAndItemList;
public ScreenSlidePagerAdapter(FragmentManager fm, ArrayList<SupplierAndItemList> supplierAndItemList) {
super(fm);
this.supplierAndItemList = supplierAndItemList;
}
#Override
public Fragment getItem(int position) {
SupplierAndItemList supplierAndItems = supplierAndItemList.get(position);
ScreenSlidePageFragment f = new ScreenSlidePageFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("supplierAndItems",supplierAndItems.getSelectedItemList());
bundle.putString("supplierName",supplierAndItems.getDealerName());
f.setArguments(bundle);
return f;
}
#Override
public int getCount() {
return supplierAndItemList.size();
}
}
}
SupplierAndItemList class
public class SupplierAndItemList implements Parcelable {
public String dealerName;
public ArrayList<ItemDetail> selectedItemList;
public SupplierAndItemList() {
selectedItemList = new ArrayList<>();
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public ArrayList<ItemDetail> getSelectedItemList() {
return selectedItemList;
}
public void setSelectedItemList(ArrayList<ItemDetail> itemList) {
this.selectedItemList = itemList;
}
protected SupplierAndItemList(Parcel in) {
dealerName = in.readString();
selectedItemList = in.readArrayList(ItemDetail.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dealerName);
dest.writeList(selectedItemList);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SupplierAndItemList> CREATOR = new Parcelable.Creator<SupplierAndItemList>() {
#Override
public SupplierAndItemList createFromParcel(Parcel in) {
return new SupplierAndItemList(in);
}
#Override
public SupplierAndItemList[] newArray(int size) {
return new SupplierAndItemList[size];
}
};
}
ItemDetail class
public class ItemDetail implements Parcelable {
public int itemId;
public String itemName;
public String salesPointLastStock;
public String salesPointLastStockTakingDate;
public String parentSalesPointLastStock;
public String parentSalesPointLastStockTakingDate;
public IDStockInput idStockInput;
public IDReturnInput idReturnInput;
public IDOrderInput idOrderInput;
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setIsSelected(boolean isUpdated) {
this.isSelected = isUpdated;
}
public String getParentSalesPointLastStockTakingDate() {
return parentSalesPointLastStockTakingDate;
}
public void setParentSalesPointLastStockTakingDate(String parentSalesPointLastStockTakingDate) {
this.parentSalesPointLastStockTakingDate = parentSalesPointLastStockTakingDate;
}
public String getParentSalesPointLastStock() {
return parentSalesPointLastStock;
}
public void setParentSalesPointLastStock(String parentSalesPointLastStock) {
this.parentSalesPointLastStock = parentSalesPointLastStock;
}
#NonNull
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
#NonNull
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
#NonNull
public String getSalesPointLastStock() {
return salesPointLastStock;
}
public void setSalesPointLastStock(String salesPointLastStock) {
this.salesPointLastStock = salesPointLastStock;
}
#NonNull
public String getSalesPointLastStockTakingDate() {
return salesPointLastStockTakingDate;
}
public void setSalesPointLastStockTakingDate(String salesPointLastStockTakingDate) {
this.salesPointLastStockTakingDate = salesPointLastStockTakingDate;
}
public IDStockInput getIdStockInput() {
return idStockInput;
}
public void setIdStockInput(IDStockInput idStockInput) {
this.idStockInput = idStockInput;
}
public IDReturnInput getIdReturnInput() {
return idReturnInput;
}
public void setIdReturnInput(IDReturnInput idReturnInput) {
this.idReturnInput = idReturnInput;
}
public IDOrderInput getIdOrderInput() {
return idOrderInput;
}
public void setIdOrderInput(IDOrderInput idOrderInput) {
this.idOrderInput = idOrderInput;
}
public ItemDetail() {
idStockInput = new IDStockInput();
idReturnInput = new IDReturnInput();
idOrderInput = new IDOrderInput();
}
protected ItemDetail(Parcel in) {
itemId = in.readInt();
itemName = in.readString();
salesPointLastStock = in.readString();
salesPointLastStockTakingDate = in.readString();
parentSalesPointLastStock = in.readString();
parentSalesPointLastStockTakingDate = in.readString();
isSelected =in.readInt()==1;
idStockInput = (IDStockInput) in.readValue(IDStockInput.class.getClassLoader());
idReturnInput = (IDReturnInput) in.readValue(IDReturnInput.class.getClassLoader());
idOrderInput = (IDOrderInput) in.readValue(IDOrderInput.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(itemId);
dest.writeString(itemName);
dest.writeString(salesPointLastStock);
dest.writeString(salesPointLastStockTakingDate);
dest.writeString(parentSalesPointLastStock);
dest.writeString(parentSalesPointLastStockTakingDate);
dest.writeInt(isSelected ? 1 : 0);
dest.writeValue(idStockInput);
dest.writeValue(idReturnInput);
dest.writeValue(idOrderInput);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<ItemDetail> CREATOR = new Parcelable.Creator<ItemDetail>() {
#Override
public ItemDetail createFromParcel(Parcel in) {
return new ItemDetail(in);
}
#Override
public ItemDetail[] newArray(int size) {
return new ItemDetail[size];
}
};
}
I have go through your method I have found some assigning value issue
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id); // do this
}
return inventories; // you are not assigning value anywhere;
}
You are not assigning value to the inventories in getInventoriesByItemDetails. I think you should add item through inventories.add(id);
Check it , Hope this help
Set
mPager.setOffscreenPageLimit(1);

Unable to get Parcelable list in a bundle in another activity

What I want is to pass a list of list from one activity to another. Here is my approach.
Feeditem.java
public class FeedItem implements Parcelable {
private String id,status, image, timeStamp, url;
private ArrayList<CommentItem> commentItems;
public FeedItem() {
}
protected FeedItem(Parcel in) {
id = in.readString();
status = in.readString();
image = in.readString();
timeStamp = in.readString();
url = in.readString();
if(commentItems!=null) {
in.createTypedArrayList(CommentItem.CREATOR);
}
}
public static final Creator<FeedItem> CREATOR = new Creator<FeedItem>() {
#Override
public FeedItem createFromParcel(Parcel in) {
return new FeedItem(in);
}
#Override
public FeedItem[] newArray(int size) {
return new FeedItem[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public ArrayList<CommentItem> getCommentItems() {
return commentItems;
}
public void setCommentItems(ArrayList<CommentItem> commentItems)
{
this.commentItems=commentItems;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(status);
dest.writeString(image);
dest.writeString(timeStamp);
dest.writeString(url);
dest.writeTypedList(commentItems);
}}
CommentItem.java
public class CommentItem implements Parcelable{
private String id,comment, from, timeStamp;
public CommentItem() {
}
protected CommentItem(Parcel in) {
id = in.readString();
comment = in.readString();
from = in.readString();
timeStamp = in.readString();
}
public static final Creator<CommentItem> CREATOR = new Creator<CommentItem>() {
#Override
public CommentItem createFromParcel(Parcel in) {
return new CommentItem(in);
}
#Override
public CommentItem[] newArray(int size) {
return new CommentItem[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(comment);
dest.writeString(from);
dest.writeString(timeStamp);
}}
ReceivingActivity.java
ArrayList<CommentItem> commentItems;
FeedItem feedItem;
commentItems=new ArrayList<>();
Bundle bundle=getIntent().getExtras();
feedItem=bundle.getParcelable("status");
if(feedItem.getCommentItems()!=null) { //help here
commentItems = feedItem.getCommentItems();
}
SendingActivity.java
Button getComments=(Button)convertView.findViewById(R.id.commentsbutton);
getComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(activity, CommentActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("status", item); //item is feeditem
i.putExtras(bundle);
activity.startActivity(i);
}
});
I am able to get all the attributes of the feeditem except the list which is giving me null in the receiving activity. Could someone please help me out with this. Thanks in advance.
I think the problem is that you're only reading in the list if it is already non-null:
if(commentItems!=null) {
in.createTypedArrayList(CommentItem.CREATOR);
}
If it's null, which it will be at that point, it doesn't get set. Just remove the non-null check and I think it will work.
commentItems = in.createTypedArrayList(CommentItem.CREATOR);

Categories