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);
}
}`
Related
I have tough problem with my project. Its hard to explain. I have two different model but, I should compare these two model. Should I make a new model for this two models?
Here is Cart.java. There is Voyage.java as a Model. This class differentiate if type_voyage not equals each other. I have another model named Bus.java. I should compare if it equals together with model.
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
ArrayList<Voyage> list = Lists.newArrayList(Collections2.filter(voyages, new Predicate<Voyage>() {
#Override
public boolean apply(Voyage voyage) {
return !voyage.getType_voyage().equals(type_voyage);
}
}));
return list.size() > 0 ? true : false;
}
Bus.java
public class Bus {
private static Bus instance;
private String BROADCAST_TAG = "com.bss.hepsi.bus";
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<BusPassenger> busPasengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_bus;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
boolean isExpanded;
boolean isShowProgress;
public Bus() {
}
public static synchronized Bus getInstance() {
if (instance == null) {
instance = new Bus();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public boolean isExpanded() {
return this.isExpanded;
}
public void setExpanded(boolean expanded) {
this.isExpanded = expanded;
}
public boolean isShowProgress() {
return this.isShowProgress;
}
public void setShowProgress(boolean showProgress) {
this.isShowProgress = showProgress;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_bus() {
return type_bus;
}
public void setType_voyage(String type_bus) {
this.type_bus = type_bus;
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
if (resultReturn.length()<1){
busReturnIsEmpty();}
else{
busReturnIsNotEmpty();
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(600 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
private void sendVoyagesArrayBroadcast(String target, JSONArray resultArray) {
Intent intent = new Intent();
intent.setAction(BROADCAST_TAG + target);
intent.putExtra("data", resultArray.toString());
context.sendBroadcast(intent);
}
public static Bus setJsonToClass(JSONObject jsonObject, int direction, String owner) {
Bus bus = new Gson().fromJson(String.valueOf(jsonObject), Bus.class);
bus.setDirection(direction);
bus.setType_voyage(owner);
bus.setDepartureTime(bus.departure_time);
bus.setArrivalTime(bus.arrival_time);
for (Leg leg :
bus.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
bus.type = owner;
return bus;
}
Voyage.java
public class Voyage {
private static Voyage instance;
//private static String url="http://78.186.57.167:3000/";
//private static String url="http://10.0.0.27:1337/";
/////public static final String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///bunu kaldırdım static oldugu için
private String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///onun yerine bunu koydum
//private static String url="http://185.122.203.104:3002/";
// private static String url="http://10.0.0.25:1337/";
public int checkCart; // Result activity'de veri gelip gelmediğini kontrol edip kullanıcıyı uyarmak için
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<FlightPassenger> flightPassengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_voyage;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
public Voyage() {
}
public static synchronized Voyage getInstance() {
if (instance == null) {
instance = new Voyage();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
/*public static String getUrl() {
return url;
}*/
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_voyage() {
return type_voyage;
}
public void setType_voyage(String type_voyage) {
this.type_voyage = type_voyage;
}
public void searchFlightVoyages(Context context) {
this.context = context;
cancelRequest("flight/search", context);
Map<String, String> header = prepareVoyageSearchHeaderForFlight();
sendRequest("flight/search", header);
}
public void searchTrainVoyages(Context context) {
this.context = context;
cancelRequest("train/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("train/search", header);
}
public void searchBoatVoyages(Context context) {
this.context = context;
cancelRequest("seaway/boat/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/boat/search", header);
}
public void searchFerryVoyages(Context context) {
this.context = context;
cancelRequest("seaway/ferry/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/ferry/search", header);
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
// servisten gelen cevap not_available ise
//// owner
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
// servisten gösterilebilecek bir sonuç geldiyse
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
// checkCart=0;
// sendCheckCart();
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setTag(owner);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public static Voyage setJsonToClass(JSONObject jsonObject, int direction, String owner) {
//Log.e("jsonobj", String.valueOf(jsonObject));
Voyage voyage = new Gson().fromJson(String.valueOf(jsonObject), Voyage.class);
voyage.setDirection(direction);
voyage.setType_voyage(owner);
voyage.setDepartureTime(voyage.departure_time);
voyage.setArrivalTime(voyage.arrival_time);
for (Leg leg :
voyage.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
voyage.type = owner;
return voyage;
}
When you remove all the code from your question that is superfluous, it makes the problem more obvious.
First I simplified your comparison method:
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
for(Voyage voyage : voyages) {
if(!type_voyage.equals(voyage.getType_voyage()) {
return true;
}
}
}
Then created an interface
interface Voyage {
String getType_voyage();
}
Bus.java
public class Bus implements Voyage {
...
private String type_voyage;
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
And changed Voyage.java to Ferry.java
public class Ferry implements Voyage {
...
private String type_voyage;
...
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
You may want to look at creating some more classes so that your 'model' classes are not doing to much / have so many responsibilities.
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);
}
}
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 trying to pass Parcelable object from the A activity to B activity via intent:
Intent intent = new Intent (A.this, B.class);
intent.putExtra ("post", mypost); // where post implements Parcelable`
In B Activity I got the post object in this way:
Post myPost = getIntent().getParcelableExtra("post");
In B activity myPost object fields are mixed, e.g. I have postText and postDate fields in Post model, the values of this fields in B activity are mixed.
Why this can happen? My model class look likes the following:
public class Post implements Parcelable, Serializable {
private static final long serialVersionUID = 2L;
#SerializedName("author")
private User author;
#SerializedName("comments_count")
private String commentsCount;
#SerializedName("image")
private String imageToPost;
#SerializedName("parent_key")
private String parentKey;
#SerializedName("created_date")
private String postDate;
#SerializedName("id")
private String postId;
#SerializedName("text")
private String postText;
#SerializedName("title")
private String postTitle;
#SerializedName("shared_post_id")
private String sharedPostId;
#SerializedName("url")
private String urlToPost;
#SerializedName("video")
private String videoToPost;
public Post() {
}
public Post(Parcel in) {
author = (User) in.readValue(getClass().getClassLoader());
commentsCount = in.readString();
imageToPost = in.readString();
parentKey = in.readString();
postDate = in.readString();
postId = in.readString();
postText = in.readString();
postTitle = in.readString();
sharedPostId = in.readString();
urlToPost = in.readString();
videoToPost = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostText() {
return postText;
}
public void setPostText(String postText) {
this.postText = postText;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getUrlToPost() {
return urlToPost;
}
public void setUrlToPost(String urlToPost) {
this.urlToPost = urlToPost;
}
public String getImageToPost() {
return imageToPost;
}
public void setImageToPost(String imageToPost) {
this.imageToPost = imageToPost;
}
public String getVideoToPost() {
return videoToPost;
}
public void setVideoToPost(String videoToPost) {
this.videoToPost = videoToPost;
}
public String getParentKey() {
return parentKey;
}
public void setParentKey(String parentKey) {
this.parentKey = parentKey;
}
public String getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(String commentsCount) {
this.commentsCount = commentsCount;
}
public String getSharedPostId() {
return sharedPostId;
}
public void setSharedPostId(String sharedPostId) {
this.sharedPostId = sharedPostId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(author);
dest.writeString(commentsCount);
dest.writeString(imageToPost);
dest.writeString(parentKey);
dest.writeString(postDate);
dest.writeString(postId);
dest.writeString(postText);
dest.writeString(postTitle);
dest.writeString(sharedPostId);
dest.writeString(urlToPost);
dest.writeString(videoToPost);
}
}
Add describeContents and writeToParcel.
Examples:
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(email);
dest.writeString(pass);
dest.writeFloat(amountPaid);
dest.writeString(url);
dest.writeInt(age);
}
Now, I have three class, the base class is BaseWidget which implements Parcelable, two subclasses are SelectWidget and TextWidget. Then, I use a class named WidgetInfo (also implements Parcelable) to keep a list of BaseWidget or SelectWidget or TextWidget objects.
While I put WidgetInfo object into an Intent to start TestActivity, and I received WidgetInfo in TestActivity ,but all the elements of list (which in WidgetInfo) convert to BaseWidget object. And subclass object member variable is lost. What is problem???
BaseWidget.java:
public class BaseWidget implements Parcelable{
private String name;
public BaseWidget() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected BaseWidget(Parcel in) {
this.name = in.readString();
}
public static final Creator<BaseWidget> CREATOR = new Creator<BaseWidget>() {
#Override
public BaseWidget createFromParcel(Parcel in) {
return new BaseWidget(in);
}
#Override
public BaseWidget[] newArray(int size) {
return new BaseWidget[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
}
}
TextWidget.java:
public class TextWidget extends BaseWidget{
private String width = "100";
public TextWidget() {
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
protected TextWidget(Parcel in) {
super(in);
width = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(width);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<TextWidget> CREATOR = new Creator<TextWidget>() {
#Override
public TextWidget createFromParcel(Parcel in) {
return new TextWidget(in);
}
#Override
public TextWidget[] newArray(int size) {
return new TextWidget[size];
}
};
}
SelectWidget.java:
public class SelectWidget extends BaseWidget{
private int height = 200;
public SelectWidget() {
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
protected SelectWidget(Parcel in) {
super(in);
height = in.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(height);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<SelectWidget> CREATOR = new Creator<SelectWidget>() {
#Override
public SelectWidget createFromParcel(Parcel in) {
return new SelectWidget(in);
}
#Override
public SelectWidget[] newArray(int size) {
return new SelectWidget[size];
}
};
}
WidgetInfo.java:
public class WidgetInfo implements Parcelable{
private List<BaseWidget> widgetList;
public WidgetInfo() {
}
public List<BaseWidget> getWidgetList() {
return widgetList;
}
public void setWidgetList(List<BaseWidget> widgetList) {
this.widgetList = widgetList;
}
protected WidgetInfo(Parcel in) {
widgetList = in.createTypedArrayList(BaseWidget.CREATOR);
}
public static final Creator<WidgetInfo> CREATOR = new Creator<WidgetInfo>() {
#Override
public WidgetInfo createFromParcel(Parcel in) {
return new WidgetInfo(in);
}
#Override
public WidgetInfo[] newArray(int size) {
return new WidgetInfo[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(widgetList);
}
}
start Intent:
WidgetInfo info = new WidgetInfo();
BaseWidget widget1 = new BaseWidget();
BaseWidget widget2 = new TextWidget();
BaseWidget widget3 = new SelectWidget();
List<BaseWidget> list = new ArrayList<>();
list.add(widget1);
list.add(widget2);
list.add(widget3);
info.setWidgetList(list);
Intent intent = new Intent(this, TestActivity.class);
intent.putExtra("widgetInfo", info);
startActivity(intent);