This question already has answers here:
Android:Passing a hash map between Activities
(5 answers)
Closed 3 years ago.
EDIT: I've updated my question considerably and am now going with Parcelable as my method.
I'm attempting to a pass an ArrayList from one activity to another. I've been reading around and can't seem to find any answers to my problem.
I've got an ArrayList<SearchList> which implements Parcelable SearchList has the following code...
public class SearchList implements Parcelable {
private String title;
private String description;
private String link;
public SearchList(String name, String phone, String mail) {
super();
this.title = name;
this.description = phone;
this.link = mail;
}
public SearchList(Parcel source){
/*
* Reconstruct from the Parcel
*/
title = source.readString();
description = source.readString();
link = source.readString();
}
public String gettitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(description);
dest.writeString(link);
}
public static final Creator<SearchList> CREATOR = new Creator<SearchList>() {
public SearchList createFromParcel(Parcel source) {
return new SearchList(source);
}
public SearchList[] newArray(int size) {
return new SearchList[size];
}
};
}
However, when I try and do...
List<SearchList> listOfResults = new ArrayList<SearchList>();
intent.putParcelableArrayListExtra("results", listOfResults);
I get not applicable for type (String, List<SearchList> why?
Could you use all String values, and change from bundle.putSerializable() to bundle.putStringArrayList("key", ArrayList<String>_object)
You can use SQLite as alternative. To pass data from one Activity to another. Here the link.
Related
Creating a linked list that has a class, Notes, that's basically an object that contains NotePages, another class, that contains Strings that are "title" and description. The class Notes extends another class which is the LinkedList class mentioned earlier. The problem is that when I try printing out the Notes with a note page in it, the display comes out like this:
Note one
[]
Assigning what to display in the object looks like:
NotePages page = new NotePages("title one", "Description");
Notes note = new Notes("Note one", page);
note.printNote();
I've tried creating other methods such as a String method to try and return the page properly to no avail.
Here's my code for the Notes object.
public class Notes extends LinkedList{
private String title;
private LinkedList<NotePages> pages;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public LinkedList<NotePages> getPages() {
return pages;
}
public void setPages(LinkedList<NotePages> pages) {
this.pages= pages;
}
public Notes(String title, LinkedList<NotePages> pages) {
this.title = title;
this.pages= pages;
}
void printNote(){
System.out.println(getTitle()+"\n"+getPages());
}
}
I need the display to output something closer to this:
Note one
title one
description
Here is the NotePages Class:
import java.awt.*;
public class NotePages {
private String title;
private String description;
private Color label;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Color getLabel() {
return label;
}
public void setLabel(Color label) {
this.label = label;
}
NotePages(String title, String description, Color label){
this.title = title;
this.description = description;
this.label = label;
}
NotePages(String title,String description){
this.title = title;
this.description = description;
}
void printPage(){
System.out.println(getTitle() + "\n "+ getDescription());
}
}
The change will need to be made in printNote function.
When the constructor for Notes is initialized pages variable gets initialised with a NotePage LinkedList.
pages does not contain the values directly. It contains objects of NotePage. So you need to use a loop for traversing through all the linkedList objects and then print the title and description for every object.
void printNote(){
System.out.println(getTitle());
//no need to use getPages function, pages already has your list
for(int i=0; i<pages.size();i++)
System.out.println(pages.get(i).getTitle()+"\n"+pages.get(i).getDescription());
}
get function will help you get the object at every ith index and then simply use the get functions of your NotePage class to print title and description.
Also the in main function add a linkedList object to the constructor of Note instead of a NotePage.
LinkedList<NotePages> notelist = new LinkedList<>();
notelist.add(page);
//adding LinkedList object to Notes constructor
Notes note = new Notes("Note one", notelist);
This question already has answers here:
Managing constructors with many parameters in Java
(8 answers)
Closed 4 years ago.
Hi I am a quite beginner in java.
Is it a good way to create construcors with many parameters like in my BookLibrary program?
public class Book implements Serializable {
private String title;
private String directorName;
private String directorSurname;
private String type;
private int issueYear;
private List<String> actorNames;
private List<String> actorSurnames;
private Tuple<String, String> directorFullName;
public Book(String title, String directorName, String directorSurname, String type, int issueYear,
List<String> actorNames, List<String> actorSurnames, Tuple<String, String> directorFullName){
this.title = title;
this.directorName = directorName;
this.directorSurname = directorSurname;
this.type = type;
this.issueYear = issueYear;
this.actorNames = actorNames;
this.actorSurnames = actorSurnames;
this.directorFullName = directorFullName;
}
Or is there any better idea to create such a constructor?
As others already said in comments, using the Builder Pattern would be an option. But if not done properly, that introduces the risk of creating incomplete objects.
But there are more ways to improve your design. E.g. you pass names and surnames (and a full name in case of the director - why only there?) as separate Strings. I'd create a PersonName class that encapsulates these different naming elements, so your constructor becomes:
public Book(String title,
PersonName directorName,
String type,
int issueYear,
List<PersonName> actors) {
...
}
Looks better and makes naming issues more consistent.
And of course, rename that class to be Movie instead of Book.
Creating a constructor with more than 3 parameters it is not a best practice. Because you need to know the order of each parameter. I can recommend you to use getters and setters in this way(for title field of class):
public String getTitle() {
return title;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
By this structure you can create a very pretty constructions while creating a new instance:
Book book = new Book()
.setTitle("Book")
.setType("Comedy")
.setActorNames(Arrays.asList("Abzal"));
The full refactored version of your class:
public class Book implements Serializable {
private String title;
private String directorName;
private String directorSurname;
private String type;
private int issueYear;
private List<String> actorNames;
private List<String> actorSurnames;
private Tuple<String, String> directorFullName;
public Book() {
}
public String getTitle() {
return title;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
public String getDirectorName() {
return directorName;
}
public Book setDirectorName(String directorName) {
this.directorName = directorName;
return this;
}
public String getDirectorSurname() {
return directorSurname;
}
public Book setDirectorSurname(String directorSurname) {
this.directorSurname = directorSurname;
return this;
}
public String getType() {
return type;
}
public Book setType(String type) {
this.type = type;
return this;
}
public int getIssueYear() {
return issueYear;
}
public Book setIssueYear(int issueYear) {
this.issueYear = issueYear;
return this;
}
public List<String> getActorNames() {
return actorNames;
}
public Book setActorNames(List<String> actorNames) {
this.actorNames = actorNames;
return this;
}
public List<String> getActorSurnames() {
return actorSurnames;
}
public Book setActorSurnames(List<String> actorSurnames) {
this.actorSurnames = actorSurnames;
return this;
}
public Tuple<String, String> getDirectorFullName() {
return directorFullName;
}
public Book setDirectorFullName(Tuple<String, String> directorFullName) {
this.directorFullName = directorFullName;
return this;
}
}
Have a good coding!
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");
Here is the problem, when I send my object to server using retrofit I got it null. I'm doing this to create the json object:
HashMap<String, UserModel> map = new HashMap<>();
map.put("user", user);
But, when the json arrives in the server I got something like this:
{"user":null}
Then I printed ny json file with this line:
Log.d("TAG", new JSONObject(map).toString());
And I saw the same null object.
So, here is my question, Why is this happening? And how can I fix that?
Here goes some information about my project:
Retrofit version: 2.0.0
Retrofit serializer: jackson version 2.0.0
using also jackson to convert JodaTime version 2.4.0
here goes how I get retrofit instance:
public T buildServiceInstance(Class<T> clazz){
return new Retrofit.Builder().baseUrl(BuildConfig.API_HOST)
.addConverterFactory(JacksonConverterFactory.create())
.build().create(clazz);
}
I call that method here:
public static final IUserApi serviceInstance = new ApiBuildRequester<IUserApi>()
.buildServiceInstance(IUserApi.class);
Method declaration on interface IUserApi:
#POST("User.svc/Save")
Call<ResponseSaveUserApiModel> save(#Body HashMap<String, UserModel> map);
And at last, but I guess, not less important:
public class UserModel implements Parcelable {
private String idUser;
private String name;
private String email;
#JsonProperty("password")
private String safePassword;
private String salt;
private String phoneNumber;
private String facebookProfilePictureUrl;
private String facebookUserId;
public UserModel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSafePassword() {
return safePassword;
}
public void setSafePassword(String safePassword) {
this.safePassword = safePassword;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getFacebookProfilePictureUrl() {
return facebookProfilePictureUrl;
}
public void setFacebookProfilePictureUrl(String facebookProfilePictureUrl) {
this.facebookProfilePictureUrl = facebookProfilePictureUrl;
}
public String getFacebookUserId() {
return facebookUserId;
}
public void setFacebookUserId(String facebookUserId) {
this.facebookUserId = facebookUserId;
}
#Override
public int describeContents() {
return 0;
}
public UserModel(Parcel in) { // Deve estar na mesma ordem do "writeToParcel"
setIdUser(in.readString());
setName(in.readString());
setEmail(in.readString());
setSafePassword(in.readString());
setPhoneNumber(in.readString());
setFacebookProfilePictureUrl(in.readString());
setFacebookUserId(in.readString());
}
#Override
public void writeToParcel(Parcel dest, int flags) { //Deve estar na mesma ordem do construtor que recebe parcel
dest.writeString(idUser);
dest.writeString(name);
dest.writeString(email);
dest.writeString(safePassword);
dest.writeString(phoneNumber);
dest.writeString(facebookProfilePictureUrl);
dest.writeString(facebookUserId);
}
public static final Parcelable.Creator<UserModel> CREATOR = new Parcelable.Creator<UserModel>(){
#Override
public UserModel createFromParcel(Parcel source) {
return new UserModel(source);
}
#Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
Debug screen:
#Selvin and #cricket_007 You are the best!
I got this using your hint that my printing was wrong, and I found the solution.
I have two types of users in my app, facebook users or native users, two forms, but just one object, and here was the problem, when I sent facebook objects (complete) it worked fine, but when I tried to send native users, with some null properties, it crashed my serialization.
So I had to check every property before send it, it's just a workaround, but for now it's enough, thank you a lot folks!
I'm currently facing a problem with Adobe Flash Builder, I work on a project with a Java core and services to communicate with a Flex client. (BlazeDS channel)
I decided to remove an array list in an object because it was no longer useful, so I commented the following lines in my object value to remove the ArrayList named "unitFactors"
public class UnitValue extends PhysicalQuantityObjectValue{
String symbol;
String name;
String description;
String physicalQuantityName;
//UnitFactorValue[] unitFactors;
UnitConstraintValue unitConstraint;
public UnitValue(AdnUnit unit) {
super(unit.getId());
//Constructor code ...
}
public UnitValue() {}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPhysicalQuantityName() {
return physicalQuantityName;
}
public UnitValue(String symbol, String name, String description,
String physicalQuantityName,
UnitConstraintValue unitConstraint) {
super();
this.symbol = symbol;
this.name = name;
this.description = description;
this.physicalQuantityName = physicalQuantityName;
//this.unitFactors = unitFactors;
this.unitConstraint = unitConstraint;
}
public void setPhysicalQuantityName(String physicalQuantityName) {
this.physicalQuantityName = physicalQuantityName;
}
//public UnitFactorValue[] getUnitFactors() {
//return unitFactors;
//}
//public void setUnitFactors(UnitFactorValue[] unitFactors) {
//this.unitFactors = unitFactors;
//}
public UnitConstraintValue getUnitConstraint() {
return unitConstraint;
}
public void setUnitConstraint(UnitConstraintValue unitConstraint) {
this.unitConstraint = unitConstraint;
}
Well, no problem with the Java part. I tested it with SoapUI, everything's fine.
But when I switch on my Flex client code to refresh the valueObjects, it appears impossible to refresh UnitValue, unitFactors is still there, and it's obviously impossible to make my application work without errors on that specific point ... Can't find getUnitFactors().
Is someone facing the same problem with AdobeFlashBuilder?