I am trying to pass an array list of an object called popular people through the extras.
I have implemented parcelable interface in the object
public class PopularPeople implements Parcelable {
#SerializedName("popularity")
private double popularity;
#SerializedName("name")
private String name;
#SerializedName("profile_path")
private String profilePath;
#SerializedName("id")
private int id;
#SerializedName("adult")
private boolean adult;
public void setPopularity(double popularity){
this.popularity = popularity;
}
public double getPopularity(){
return popularity;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setProfilePath(String profilePath){
this.profilePath = profilePath;
}
public String getProfilePath(){
return profilePath;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setAdult(boolean adult){
this.adult = adult;
}
public boolean isAdult(){
return adult;
}
#Override
public String toString(){
return
"PopularPeople{" +
"popularity = '" + popularity + '\'' +
",name = '" + name + '\'' +
",profile_path = '" + profilePath + '\'' +
",id = '" + id + '\'' +
",adult = '" + adult + '\'' +
"}";
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeDouble(this.popularity);
dest.writeString(this.name);
dest.writeString(this.profilePath);
dest.writeInt(this.id);
dest.writeByte(this.adult ? (byte) 1 : (byte) 0);
}
public PopularPeople() {
}
protected PopularPeople(Parcel in) {
this.popularity = in.readDouble();
this.name = in.readString();
this.profilePath = in.readString();
this.id = in.readInt();
this.adult = in.readByte() != 0;
}
public static final Parcelable.Creator<PopularPeople> CREATOR = new Parcelable.Creator<PopularPeople>() {
#Override
public PopularPeople createFromParcel(Parcel source) {
return new PopularPeople(source);
}
#Override
public PopularPeople[] newArray(int size) {
return new PopularPeople[size];
}
};
}
Now in an activity, I am creating a new popular people object and creating a list of PopularPeople from another object Cast
detailCastSeeAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// we need to convert CAST to POPULARPEOPLE. We only need name, profile path and ID.
ArrayList<PopularPeople> popularPeople = new ArrayList<>();
Bundle b = new Bundle();
for(Cast c : cast){
PopularPeople p = new PopularPeople();
p.setName(c.getName());
p.setId(c.getId());
p.setProfilePath(c.getProfilePath());
popularPeople.add(p);
Timber.e("Added %s",c.getName());
}
Timber.e("Length before sendin list %d",popularPeople.size());
Intent i = new Intent(MovieDetailActivity.this, PopularPeopleActivity.class);
b.putParcelableArrayList(AppConstants.CAST_LIST,popularPeople);
i.putExtras(b);
i.putExtra(AppConstants.TAG,AppConstants.MOVIE_CAST);
startActivity(i);
}
});
Now when I recieve this in the other class, the recieved array list is still empty and not populated with the list of data I sent in from the other activity.
b = getIntent().getExtras();
if (b != null){
ArrayList<PopularPeople> peopleList =
b.getParcelableArrayList(AppConstants.CAST_LIST);
tag = b != null ? b.getString(AppConstants.TAG) : null;
}else{
Toast.makeText(this, "Error loading. Please try again..", Toast.LENGTH_SHORT).show();
finish();
// return is required as we dont want to execute the code below and just want the activity to close.
return;
}
In the second activity where I recieve the intent, if I log out the size of popular people it gives out 0. How do I fix this?
You might want to consider saving the Arraylist to SharedPreferences and pass the key to it through an intent extra.
I experienced it to be the easiest to use Gson and json to write an Arraylist of Custom Objects to SharedPreferences.
Here is a good tutorial on how to do that: https://youtu.be/jcliHGR3CHo
But if you want to use parcelable I would recommend you to watch this tutorial: https://youtu.be/WBbsvqSu0is
I hope this could help you!
Instead of going with "parceable", you can go with "serializable".
try this way may this help you
First you want to make
Class Venue implements Serializable
public class Venue implements Serializable { /** * */
private static final long serialVersionUID = 1L; }
In your FirstActivity do this way
ArrayList<Venue> VenueArrayList = new ArrayList<Venue>();
Intent intent = new Intent(this,secondActivity.class);
intent.putExtra("VenueArrayList", VenueArrayList);
In your SecondActivity do this way
ArrayList<Venue> VenueArrayList; VenueArrayList = (ArrayList<Venue>)
getIntent().getSerializableExtra( "VenueArrayList");
Related
I want to check duplicate IDs from a list with the data I inputted, then increment the qty variable in the list. If it's new data, it will add a new list.
This is my code
public void addBarang(Barang barang){
int id_barang = barang.getId();
if(this.list.isEmpty())
{
list.add(barang);
}
else
{
for(int i=0;i<list.size();i++)
{
if(list.get(i).getId() != id_barang)
{
list.add(barang);
System.out.println("Added");
break;
}
if(list.get(i).getId() == id_barang)
{
int new_qty = list.get(i).getQty()+barang.getQty();
list.get(i).setQty(new_qty);
}
}
}
}
Even if I input new data it always increments the qty of old data and the new data is not added (basically always end in the "else" section).
Code for inputing data
Gudang gudang1 = new Gudang(1,1);
System.out.println("ID: ");
int id = input.nextInt();
System.out.println("Jumlah: ");
int qty = input.nextInt();
System.out.println("Nama: ");
String name = input.next();
Barang barang = new Barang(id,name,qty);
gudang1.addBarang(barang);
Barang Class
public class Barang {
public static int id;
private String name;
private int qty;
public Barang(int id, String name, int qty) {
this.id = id;
this.name = name;
this.qty = qty;
}
public Barang(){
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getQty() {
return qty;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setQty(int qty) {
this.qty = qty;
}
#Override
public String toString() {
return "Barang{" + "id=" + id + ", name=" + name + ", qty=" + qty + '}';
}
Gudang Class
public class Gudang {
public static int id;
private int location;
public List<Barang> list = new ArrayList<Barang>();
public Gudang(int id, int location) {
Gudang.id = id;
this.location = location;
}
public int getId() {
return id;
}
public int getLocation() {
return location;
}
public List<Barang> getList() {
return list;
}
public void setId(int id) {
this.id = id;
}
public void setLocation(int location) {
this.location = location;
}
public void setList(List<Barang> list) {
this.list = list;
}
public void addBarang(Barang barang){
int id_barang = barang.getId();
if(this.list.isEmpty())
{
list.add(barang);
}
else
{
for(int i=0;i<list.size();i++)
{
if(list.get(i).getId() != id_barang)
{
list.add(barang);
System.out.println("Added");
break;
}
if(list.get(i).getId() == id_barang)
{
int new_qty = list.get(i).getQty()+barang.getQty();
list.get(i).setQty(new_qty);
}
}
}
System.out.println("Size List = "+list.size());
}
public void duplicate(List<Barang> list2)
{
this.list.addAll(list2);
}
public void clearBarang(){
this.list.clear();
}
public void display(){
for(Barang barang: this.list){
System.out.println(barang);
}
}
IE : If I have id=1 and qty=1, then input a new data with id=2 and qty=2, the final result will end up with id=2 and qty=3. No new data int he list were added.
try using .equals to compare if the data exist in your list
Please check if ids are duplicate between your old and new data.
If you ids are unique then you can take advantage of Map and put id as key and barang object as value. Whenever you successfully lookup map increment quantity field of object.
At first guess i would change:
if(list.get(i).getId() != id_barang)
to:
if(list.get(i).getId() != barang.getId())
maybe id_barang is not the same as the id stored in the barang object.
The String variable finalMapSearchUrl gets concatenated with another String (mapUrlParam) in the constructor and the Log shows the expected value : Final map URL : https://www.google.com/maps/search/?api=1&query=Spilia%20Beach (here the mapUrlParam = Spilia Beach). However, when i call the getMapSearchUrl() method from outside the class and monitor the Log, the finalMapSearchUrl's value is now back to the default https://www.google.com/maps/search/?api=1&query=. Log in getMapSearchUrl() : finalMapSearchUrl = https://www.google.com/maps/search/?api=1&query=. Any ideas on when,why and how it's value is not preserved outside of the constructor?
PlaceObject.java class:
public class PlaceObject implements Parcelable { // Implementing the Parcelable interface to allow for cleaner and faster code
private static final String TAG = PlaceObject.class.getSimpleName();
private static final String baseMapSearchUrl = "https://www.google.com/maps/search/?api=1&query="; // Base url for launching a Map activity with a Search Intent
// Using int so that the values can be accessed via R.string etc.
private int name;
private int description;
private int category;
private String locationDistance;
private String finalMapSearchUrl = baseMapSearchUrl;
PlaceObject(int name, int description, int category , String locationDistance, String mapUrlParam) {
this.name = name;
this.description = description;
this.locationDistance = locationDistance;
this.category = category;
finalMapSearchUrl += Uri.encode(mapUrlParam);
Log.d(TAG,"Final map URL : " + finalMapSearchUrl);
}
private PlaceObject(Parcel in) {
name = in.readInt();
description = in.readInt();
locationDistance = in.readString();
category = in.readInt();
}
public static final Creator<PlaceObject> CREATOR = new Creator<PlaceObject>() {
#Override
public PlaceObject createFromParcel(Parcel in) {
return new PlaceObject(in);
}
#Override
public PlaceObject[] newArray(int size) {
return new PlaceObject[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(name);
parcel.writeInt(description);
parcel.writeString(locationDistance);
parcel.writeInt(category);
}
public int getName() {
return name;
}
public int getDescription() {
return description;
}
public String getLocationDistance() {
return locationDistance;
}
public int getCategory() {
return category;
}
public String getMapSearchUrl() {
Log.d(TAG,"finalMapSearchUrl = " + finalMapSearchUrl);
return finalMapSearchUrl; //TODO:sp figure out why the variable's value gets lost after the constructor is done
}
}
Because you're simply getting the base url and not the one Parceled.
Solution:
Add it to parcel and pay attention to the order of writing,
Like this:
private PlaceObject(Parcel in) {
name = in.readInt();
description = in.readInt();
category = in.readInt();
locationDistance = in.readString();
finalMapSearchUrl = in.readString();
}
and don't forget to fix this as well:
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(name);
parcel.writeInt(description);
parcel.writeInt(category);
parcel.writeString(locationDistance);
parcel.writeString(finalMapSearchUrl);
}
I've tried pass object between activities exactly like in How to pass an object from one activity to another on Android
and SerializableTask is creating correctly but when I want to read this in next activity it is null.
Task task = listOfTask.get(position);
Log.i(TAG, "recyclerViewEditTask: edit clicked for title: " +
task.getTitle());
SerializabledTask sTask = new SerializabledTask(task.getTitle(),
task.getDetails(), task.getTimeToDo(), task.getTag(),
task.getId(), task.isDone());
if(sTask == null)
Log.e(TAG, "recyclerViewEditTask: sTask IS NULL");
else {
Log.i(TAG, "recyclerViewEditTask: sTaskInfo: " + sTask.toString());
Intent editIntent = new Intent(ListOfTasksActivity.this, EditTaskActivity.class);
editIntent.putExtra("task", sTask);
startActivity(editIntent);
then it goes to another activity
activity that try to get Serializable object:
Intent i = getIntent();
SerializabledTask sTask = (SerializabledTask) i.getSerializableExtra("task");
if(sTask == null)
Log.e(TAG, "onCreate: sTASK IS NULL" );
and "onCreate: sTASK IS NULL" is calling
when I tried to pass single String it works properly
Serializables class:
public class SerializabledTask implements Serializable {
String title, details, timeToDo, tag;
int id;
boolean done;
Task task;
public SerializabledTask(String title, String details, String timeToDo, String tag, int id, boolean done) {
this.title = title;
this.details = details;
this.timeToDo = timeToDo;
this.tag = tag;
this.id = id;
this.done = done;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getTimeToDo() {
return timeToDo;
}
public void setTimeToDo(String timeToDo) {
this.timeToDo = timeToDo;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
#Override
public String toString() {
return "SerializabledTask{" +
"title='" + title + '\'' +
", details='" + details + '\'' +
", timeToDo='" + timeToDo + '\'' +
", tag='" + tag + '\'' +
", id=" + id +
", done=" + done +
", task=" + task +
'}';
}
Your model class SerializableTask must implement Serializable for your code to work.
public class SerializableTask implements Serializable {
...
}
Also it's highly recommended to use Parcelable instead of Serializable, because it's a lot faster.
Source : http://www.developerphil.com/parcelable-vs-serializable/
I am trying to pass array of objects from one activity to another activity using parcelable. Here i faced this problem Class not found when unmarshalling:
First Activity code
intent.setExtrasClassLoader(MenueItemDetails.class.getClassLoader());
intent.putExtra("menue",myArray);
Second Activity code
myArray = (MenueItemDetails[])getIntent().getParcelableArrayExtra("menue");
it's my class which is parceable
public class MenueItemDetails implements Parcelable {
private int id = 0, menueId = 0, type = 0, typeId = 0, styleId = 0, lineBefore = 0;
private String webSite = "", title = "", icon = "";
#Override
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeInt(menueId);
out.writeInt(type);
out.writeInt(typeId);
out.writeInt(styleId);
out.writeInt(lineBefore);
out.writeString(webSite);
out.writeString(title);
out.writeString(icon);
}
private MenueItemDetails(Parcel in) {
id = in.readInt();
menueId = in.readInt();
type = in.readInt();
typeId = in.readInt();
styleId= in.readInt();
lineBefore= in.readInt();
webSite=in.readString();
title= in.readString();
icon=in.readString();
}
public MenueItemDetails() {
id = 0;
menueId = 0;
type = 0;
styleId= 0;
lineBefore= 0;
webSite="";
title= "";
icon="";
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public MenueItemDetails createFromParcel(Parcel in) {
return new MenueItemDetails(in);
}
public MenueItemDetails[] newArray(int size) {
return new MenueItemDetails[size];
}
};
public int getLineBefore() {
return lineBefore;
}
public void setLineBefore(int lineBefore) {
this.lineBefore = lineBefore;
}
public void setId(int id) {
this.id = id;
}
public void setMenueId(int menueId) {
this.menueId = menueId;
}
public void setTitle(String title) {
this.title = title;
}
public void setIcon(String icon) {
this.icon = icon;
}
public void setType(int type) {
this.type = type;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public void setStyleId(int styleId) {
this.styleId = styleId;
}
public int getId() {
return id;
}
public String getWebSite() {
return webSite;
}
public void setWebSite(String webSite) {
this.webSite = webSite;
}
public int getMenueId() {
return menueId;
}
public String getTitle() {
return title;
}
public String getIcon() {
return icon;
}
public int getType() {
return type;
}
public int getTypeId() {
return typeId;
}
public int getStyleId() {
return styleId;
}
}
Your Second Activity must be like this:
Intent intent = getIntent();
intent.setExtrasClassLoader(MenueItemDetails.class.getClassLoader());
myArray = (MenueItemDetails[]) intent.getParcelableArrayExtra("menue");
Your code to pass the arraylist in first activity code is not correct.Send the arraylist in your activities as below:
First Activity Code
intent.setExtrasClassLoader(MenueItemDetails.class.getClassLoader());
intent.putParcelableArrayListExtra("menue",myArray);
And receive the arraylist as below in Second activity.
Second Activity Code
ArrayList<MenueItemDetails> myarray=getIntent().getParcelableArrayListExtra("menue");
The problem with your code is that it is used to send and receive single Object,not the arraylist.If you still have problems in using Parceable object,make sure to use Android Parceable Code generator plugin for Android Studio.
If your task is Pass data from activity to activity or Fragment
Than instead of Using Parcelable you can use Serializable object and pass it to intent it take very less time to implement and code than Parcelable
https://stackoverflow.com/a/39631604/4741746
implement serializable in your class
public class Place implements Serializable{
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then you can pass this object in intent
Intent intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity();
int the second activity you can get data like this
Place place= (Place) getIntent().getSerializableExtra("PLACE");
I have a class called "Sprache" and need a attribute "getSprache", who is a get methode. I want to display all "getSprache" to a Jcombobox. I actually have a DefaultComboboxModel.
How can I do it?
Do I need a list?
How looks a loop for the model?
public class Sprache {
private int id;
private String sprache;
private String kuerzel;
public int getId() {
return id;
}
public String getSprache() {
return sprache;
}
public String getKuerzel() {
return kuerzel;
}
private void setId(int id) {
this.id = id;
}
private void setSprache(String sprache) {
this.sprache = sprache;
}
private void setKuerzel(String kuerzel) {
this.kuerzel = kuerzel;
}
#Override
public String toString() {
return "Sprache [id=" + id + ", sprache=" + sprache + ", kuerzel=" + kuerzel + "]";
}
}
If your class Sprache contains one "Sprache" (language), then you can iterate through all of them and call #getSprache() on each and store the return value in an String array:
// Instantiate Classes
Sprache sprache1 = new Sprache();
sprache1.setId(0);
sprache1.setKuerzel("EN");
sprache1.setSprache("English");
Sprache sprache2 = new Sprache();
sprache2.setId(1);
sprache2.setKuerzel("DE");
sprache2.setSprache("Deutsch");
List<Sprache> sprachen = new ArrayList<>(2);
sprachen.add(sprache1);
sprachen.add(sprache2);
// Create an array from the langues
String sprachenStringArray[] = {sprache1.getSprache(), sprache2.getSprache()};
// Alternative way
String sprachenStringArray[] = new String[sprachen.size()];
for (int i = 0; i < sprachen.size(); i++)
{
sprachenStringArray[i] = sprachen.get(i).getSprache();
}
// Create combo box model
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(sprachenStringArray);