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);
}
}
Related
I have a model class which implement Parcelable and 2 string and one arraylist of another model class
i can retrive title1 and title2 but i am not able to retrive option4 arraylist its get null
`public class TopListSubListModel implements Parcelable {
String title1,title2;
ArrayList option4;
public TopListSubListModel(String title1, String title2, ArrayList<Option4Model> option4) {
this.title1 = title1;
this.title2 = title2;
this.option4 = option4;
}
protected TopListSubListModel(Parcel in) {
title1 = in.readString();
title2 = in.readString();
}
public static final Creator<TopListSubListModel> CREATOR = new Creator<TopListSubListModel>() {
#Override
public TopListSubListModel createFromParcel(Parcel in) {
return new TopListSubListModel(in);
}
#Override
public TopListSubListModel[] newArray(int size) {
return new TopListSubListModel[size];
}
};
public String getTitle1() {
return title1;
}
public void setTitle1(String title1) {
this.title1 = title1;
}
public String getTitle2() {
return title2;
}
public void setTitle2(String title2) {
this.title2 = title2;
}
public ArrayList<Option4Model> getOption4() {
return option4;
}
public void setOption4(ArrayList<Option4Model> option4) {
this.option4 = option4;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title1);
parcel.writeString(title2);
}
}`
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);
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);
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);
I am using Parcelable for a custom Song object I have in my class. However, when ever I am trying to get an arraylist extra of type Song I always get a null pointer exception. I have no problem getting string extras from the intent but when I try to get this ArrayList I need I always get null. I am also getting a null when I just try to pass a Song object, so I am assuming there is some issue with it but I cannot figure it out for the life of me.
This is my song class
import android.os.Parcel;
import android.os.Parcelable;
public class Song implements Parcelable {
private String uri;
private String title;
private String artist;
private String album;
private String length;
private int count;
private int source;
public Song () {
}
public Song (String title, String artist, String album, String uri, String length, int count,
int source) {
this.uri = uri;
this.title = title;
this.artist = artist;
this.album = album;
this.length = length;
this.count = count;
this.source = source;
}
public String getUri() {
return uri;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String getLength() {
return length;
}
public int getCount() {return count;}
#Override
public String toString() {
return title + " - " +artist;
}
#Override
public boolean equals(Object o){
if (o instanceof Song) {
Song song = (Song) o;
if (title.equals(song.title) && length.equals(song.length)) {
return true;
}
}
return false;
}
public int compareTo(Song s) {
if (this.count < s.getCount()) {
return -1;
}
else if(this.count > s.getCount()){
return 1;
}
return 0;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public int getSource() {
return source;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.uri);
dest.writeString(this.title);
dest.writeString(this.artist);
dest.writeString(this.album);
dest.writeString(this.length);
dest.writeInt(this.count);
dest.writeInt(this.source);
}
protected Song(Parcel in) {
this.uri = in.readString();
this.title = in.readString();
this.artist = in.readString();
this.album = in.readString();
this.length = in.readString();
this.count = in.readInt();
this.source = in.readInt();
}
public static final Creator<Song> CREATOR = new Creator<Song>() {
#Override
public Song createFromParcel(Parcel source) {
return new Song(source);
}
#Override
public Song[] newArray(int size) {
return new Song[size];
}
};
}
This is the line I use to package the arraylist
Intent intent = new Intent();
Log.d("UTILS ", " size: " +queue.size()); // Making sure it is not null before passing
intent.setClass(context, PlayerService.class);
intent.putParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST, queue);
context.startService(intent);
This is retrieving the arraylist in PlayerService class
public static final String EXTRA_TRACK_LIST = "EXTRA_TRACK_LIST";
private ArrayList<Song> trackList;
.
.
.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null || intent.getAction() == null) {
Log.d(TAG, "unspecified command");
return START_STICKY;
}
trackList=intent.getParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST);
if (trackList == null) {
Log.d("TRACKLIST", "IS NULL");
} else {
Log.d(TAG, "size: "+trackList.size());
}
.
.
.
// more irrelevant code
your parameter is wrong
public static final String EXTRA_TRACK_LIST = "EXTRA_TRACK_LIST";
so change like this
trackList = intent.getParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST);
Is queue a Queue/List or similar? Or is it an array? If array, should be queue.length, right? From List to array try this. This should work.
intent.putParcelableArrayListExtra(PlayerService.EXTRA_TRACK_LIST, queue);
If not, let me know to keep trying. Also, you could also pass it as String. You could use GSON to convert it to JSON string. After converted to String, pass it as a single String.
Intent intent = new Intent(ActivityA.this, Service.class);
intent.putExtra(new Gson().toJson(queue), PlayerService.EXTRA_TRACK_LIST);
context.startService(intent);
And to retrieve that object again:
Song song = new Gson().fromJson(intent.getStringExtra(PlayerService.EXTRA_TRACK_LIST), Song.class);
Or, if list (I believe you case):
Type listType = new TypeToken<ArrayList<Song.class>>(){}.getType();
List<Song> songList = new Gson().fromJson(intent.getStringExtra(PlayerService.EXTRA_TRACK_LIST), listType);