creating parcelable in android from some of the fields of a class - android

i have the following class which i intent to pass from one activity to another:
public class Ad extends ListItem implements parcelable{
private String _type;
private String _recordID;
private String _line1;
private String _line2;
private String _line3;
private String _line4;
private String _url;
private IOnUiNeedToUpdateListener _listener;
private boolean _notActive = false;
private String _alertText;
private Double _longitude;
private Double _latitude;
}
i want to pass an array of such objects from one activity to another. however, i do not need to pass all fields.
is it possible to create a parcel only from the desired fields and send it?

It's your code that writes to Parcel and your code that reads from Parcel. So basically yes. You can write whatever you want. Content of all members, content of some, no members, but other values you use to restore state of the object etc, etc.

Try design your class like this..
public class Form implements Parcelable {
private String formdata1;
private String formdata2;
private String formdata3;
private String formdata4;
public Form() {
}
public Form(Parcel in) {
setFormdata1(in.readString());
setFormdata2(in.readString());
setFormdata3(in.readString());
setFormdata4(in.readString());
}
public String getFormdata1() {
return formdata1;
}
public void setFormdata1(String formdata1) {
this.formdata1 = formdata1;
}
public String getFormdata2() {
return formdata2;
}
public void setFormdata2(String formdata2) {
this.formdata2 = formdata2;
}
public String getFormdata3() {
return formdata3;
}
public void setFormdata3(String formdata3) {
this.formdata3 = formdata3;
}
public String getFormdata4() {
return formdata4;
}
public void setFormdata4(String formdata4) {
this.formdata4 = formdata4;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel in, int arg1) {
in.writeString(getFormdata1());
in.writeString(getFormdata2());
in.writeString(getFormdata3());
in.writeString(getFormdata4());
}
public static final Parcelable.Creator<Form> CREATOR = new Parcelable.Creator<Form>() {
#Override
public Form createFromParcel(Parcel in) {
return new Form(in);
}
#Override
public Form[] newArray(int size) {
return new Form[size];
}
};
}

Related

Firebase real database values differ from the retrieved ones

So, in realtime database I have:
When I retrieve data from database I get:
Model class looks like:
public class User implements Parcelable {
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
#Override
public User createFromParcel(Parcel source) {
return new User(source);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
...
private String hasToPayFromPastRides;
private String didNotPayCount;
...;
public User() {
}
public User(..., String didNotPayCount, String hasToPayFromPastRides) {
...
this.didNotPayCount = didNotPayCount;
this.hasToPayFromPastRides = hasToPayFromPastRides;
}
protected User(Parcel in) {
...
this.didNotPayCount = in.readString();
this.hasToPayFromPastRides = in.readString();
}
...
public String getDidNotPayCount() {
return didNotPayCount;
}
public void setDidNotPayCount(String didNotPayCount) {
this.didNotPayCount = didNotPayCount;
}
public String hasToPayFromPastRides() {
return hasToPayFromPastRides;
}
public void setHasToPayFromPastRides(String hasToPayFromPastRides) {
this.hasToPayFromPastRides = hasToPayFromPastRides;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.userId);
dest.writeString(this.userFullName);
dest.writeString(this.userEmail);
dest.writeString(this.userPhoneNumber);
dest.writeString(this.userAvatarUrl);
dest.writeString(this.userLocalAvatar);
dest.writeString(this.userAddress);
dest.writeString(this.userCity);
dest.writeString(this.userArea);
dest.writeString(this.userPostalCode);
dest.writeString(this.userRating);
dest.writeString(this.userTotalRating);
dest.writeString(this.totalTrips);
dest.writeString(this.riskCount);
dest.writeString(this.isBlocked);
dest.writeString(this.isDefaulter);
dest.writeString(this.pendingRating);
dest.writeParcelable(this.pendingRateObj, flags);
dest.writeString(this.didNotPayCount);
dest.writeString(this.hasToPayFromPastRides);
}
}
What surprises me is that one value gets read correctly "didNotPayCount" when "hasToPayFromPastRides" is null. Any ideas?
Your getter isn't named correctly:
public String hasToPayFromPastRides()
It should be:
public String getHasToPayFromPastRides()

How to send ArrayList<Object> to other Fragment/Activity without init (start) the next Activity?

I have an ArrayList and I need to send it to another fragment. I tried to use Parcelable, but to send the data I need the "startIntent" method which starts the fragment. I don't want the fragment to be started.
I need send data array list object to another fragment without going to this other fragment. I only need to send the data. The user is free to chose when to change between activities/fragments. And the data sent earlier should already be there.
Example using Parcelable:
Class that must be to sent:
import android.os.Parcel;
import android.os.Parcelable;
public class Doenca implements Parcelable {
private String nome;
private String causa;
private String efeito;
private String cuidados;
private String prevencao;
private String categoria;
public Doenca(String nome, String causa, String efeito, String cuidados, String prevencao, String categoria) {
this.nome = nome;
this.causa = causa;
this.efeito = efeito;
this.cuidados = cuidados;
this.prevencao = prevencao;
this.categoria = categoria;
}
protected Doenca(Parcel in) {
nome = in.readString();
causa = in.readString();
efeito = in.readString();
cuidados = in.readString();
prevencao = in.readString();
categoria = in.readString();
}
public static final Creator<Doenca> CREATOR = new Creator<Doenca>() {
#Override
public Doenca createFromParcel(Parcel in) {
return new Doenca(in);
}
#Override
public Doenca[] newArray(int size) {
return new Doenca[size];
}
};
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCausa() {
return causa;
}
public void setCausa(String causa) {
this.causa = causa;
}
public String getEfeito() {
return efeito;
}
public void setEfeito(String efeito) {
this.efeito = efeito;
}
public String getCuidados() {
return cuidados;
}
public void setCuidados(String cuidados) {
this.cuidados = cuidados;
}
public String getPrevencao() {
return prevencao;
}
public void setPrevencao(String prevencao) {
this.prevencao = prevencao;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(nome);
dest.writeString(causa);
dest.writeString(efeito);
dest.writeString(cuidados);
dest.writeString(prevencao);
dest.writeString(categoria);
}
}
import android.os.Parcel;
import android.os.Parcelable;
public class Doenca implements Parcelable {
private String nome;
private String causa;
private String efeito;
private String cuidados;
private String prevencao;
private String categoria;
public Doenca(String nome, String causa, String efeito, String cuidados, String prevencao, String categoria) {
this.nome = nome;
this.causa = causa;
this.efeito = efeito;
this.cuidados = cuidados;
this.prevencao = prevencao;
this.categoria = categoria;
}
protected Doenca(Parcel in) {
nome = in.readString();
causa = in.readString();
efeito = in.readString();
cuidados = in.readString();
prevencao = in.readString();
categoria = in.readString();
}
public static final Creator<Doenca> CREATOR = new Creator<Doenca>() {
#Override
public Doenca createFromParcel(Parcel in) {
return new Doenca(in);
}
#Override
public Doenca[] newArray(int size) {
return new Doenca[size];
}
};
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCausa() {
return causa;
}
public void setCausa(String causa) {
this.causa = causa;
}
public String getEfeito() {
return efeito;
}
public void setEfeito(String efeito) {
this.efeito = efeito;
}
public String getCuidados() {
return cuidados;
}
public void setCuidados(String cuidados) {
this.cuidados = cuidados;
}
public String getPrevencao() {
return prevencao;
}
public void setPrevencao(String prevencao) {
this.prevencao = prevencao;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(nome);
dest.writeString(causa);
dest.writeString(efeito);
dest.writeString(cuidados);
dest.writeString(prevencao);
dest.writeString(categoria);
}
}
There are multiple ways with different complexity for the implementation.
Use a database to store what you need there
Store the data in the host activity containing the tabs. As soon as you switch the fragment, all you need to do is read the data from the place where you have stored it.
Use LiveData. LiveData would be my personal preference. There you can easily store any data you need and the second fragment simply observes the livedata and can easily react to changes. So you could even switch in both directions as often as you want to.
Try Using EventBus.
To use EventBus, you need to first add it to in the app module build.gradle file
implementation 'org.greenrobot:eventbus:3.1.1'
and then sync your project.
An Event Subscriber
A subscriber simply subscribes to an event by registering in the event bus and can also unregister that event. To be a subscriber, you have to do three main things:
Register the subscriber in the event bus with register(). This informs the event bus that you want to begin receiving events. In an activity, this is in the onStart() method, while in a fragment put this in the onAttact(Activity activity) method.
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
Unregister the subscriber, which means tell the event bus to stop sending me events. In an activity, this is in the onStop() method, while in a fragment put this in the onDetach() method.
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Implement the onEvent() to indicate the type of event you want to receive and action to take when you receive the event. Notice the #Subscribe annotation at the top of this method.
#Subscribe
public void onEvent(MessageEvent event) {
Toast.makeText(this, "Hey, my message" + event.getMessage(),
Toast.LENGTH_SHORT).show();.
}
Defining Event Messages
The events in greenrobot EventBus are just objects that you define. You can have different event classes if you want. They do not inherit any base class or interface—they're just POJO (Plain Old Java Objects).
public class MessageEvent {
public final List<SomeItem> items;
public MessageEvent(List<SomeItem> items) {
this.items= items;
}
}
Post Event
EventBus.getDefault().post(new MessageEvent("Hey event subscriber!"));

Android Extend double class

I have my Class Adapter , and I need to have the access of two class ! Then I can put public class JSONAdapter extends ArrayAdapter<Voiture> { for have access in my class " Voiture " but I need to have the acceesss in my class "Moniteur" too , and I can"t put that :
public class JSONAdapter extends ArrayAdapter<Voiture>,ArrayAdapter<Moniteur> {
I need to view attributes of my class " Voiture " and " Moniteur " ...
Do you have the solution for me please ? Thanks
EDIT : Ok thanks you , this is the code of my class VOITURE :
public class Voiture {
private int idV = -1; // permet de voir si le parent est enregistré dans la BDD
private String marqueV;
private String dateAchatV;
private String PlaqueImmatriculationV;
public Voiture(String marqueV, String plaqueImmatriculationV) {
this.marqueV = marqueV;
PlaqueImmatriculationV = plaqueImmatriculationV;
}
public Voiture(JSONAdapter jsonAdapter) {
this.marqueV = marqueV;
this.PlaqueImmatriculationV = PlaqueImmatriculationV;
}
public int getIdV() {
return idV;
}
public void setIdV(int idV) {
this.idV = idV;
}
public String getMarqueV() {
return marqueV;
}
public void setMarqueV(String marqueV) {
this.marqueV = marqueV;
}
public String getDateAchatV() {
return dateAchatV;
}
public void setDateAchatV(String dateAchatV) {
this.dateAchatV = dateAchatV;
}
public String getPlaqueImmatriculationV() {
return PlaqueImmatriculationV;
}
public void setPlaqueImmatriculationV(String plaqueImmatriculationV) {
PlaqueImmatriculationV = plaqueImmatriculationV;
}
}
This is the code of my class Moniteur :
public class Moniteur {
private int idM;
private String nomM;
private String prenomM;
private String adresseM;
private String telephoneM;
public Moniteur(String nomM, String prenomM,String adresseM,String telephoneM) {
this.nomM = nomM;
this.prenomM = prenomM;
this.adresseM = adresseM;
this.telephoneM = telephoneM;
}
public int getIdM() { return idM; }
public void setIdM(int idM) { this.idM = idM; }
public String getNomM() {
return nomM;
}
public void setNomM(String nomM) {
this.nomM = nomM;
}
public String getPrenomM() {
return prenomM;
}
public void setPrenomM(String prenomM) {
this.prenomM = prenomM;
}
public String getAdresseM() {
return adresseM;
}
public void setAdresseM(String adresseM) {
this.adresseM = adresseM;
}
public String getTelephoneM() {
return telephoneM;
}
public void setTelephoneM(String telephoneM) {
this.telephoneM = telephoneM;
}
}
The purpose of these two classes and how they relate is not clear, but if you want to store both of them in a single container (which is what you are trying to do) you will need to define a common interface between them (or an abstract class). I don't speak French so you will have a easier time creating a good name.
I suggest creating an interface:
public interface AbstractItem
{
//TODO define common functions in this class
}
then implement this interface in your classes:
public class Voiture implements AbstractItem
{ ... }
public class Moniteur implements AbstractItem
{ ... }
Then, you can create an array adapter that will hold both of these items:
public class JSONAdapter extends ArrayAdapter<AbstractItem>
{ ... }
If I understand correctly, "Voiture" means "car" and "Moniteur" means "instructor" or "teacher".
So, it sounds like you are implementing a type of "driving school" where there are teachers with cars that they use/drive.
If that is the case, you really only need an ArrayAdapter<Monituer> and you could implement your Moniteur class like so.
public class Moniteur {
private List<Voiture> voitures;
public Monituer() {
voitures = new ArrayList<Voiture>();
}
public void ajouterVoiture(Voiture v) {
voitures.add(v);
}
public List<Voiture> obtientVoitures() {
return voitures;
}
}
Or maybe I don't understand what is trying to be displayed in the adapters. In that case, feel free to comment below.

How to make nested ArrayLists parcelable

To pass an arrayList of objects to a fragment, I have to make the list objects parcelable.
public mObjectClass implements Parcelable {
// Some code
}
The problem is that one of the attributes in my list objects is another object-based arrayList.
public mObjectClass implements Parcelable {
// Some code
private ArrayList<someOtherObject> anotherArrayList;
}
How can I make mObjectClass parcelable?
someOtherObject has to implement Parcelable (not extend has in your question) too. Then you can call parcel.writeTypedList(anotherArrayList); to write it and parcel.readTypedList(yourList, someOtherObject.CREATOR) to read it back. You can read more here
This solution is heavily influenced by some Stackoverflow posts, including
this.
Essentially make both Classes parcelable and make use of someOtherClasses Parcelable.Creator.
mObjectClass:
public class mObjectClass implements Parcelable {
private ArrayList<someOtherObject> anotherArrayList;
//add getter + setter...
public mObjectClass() {
anotherArrayList = new ArrayList<someOtherObject>();
}
public mObjectClass(Parcel in) {
anotherArrayList = new ArrayList<someOtherObject>();
in.readTypedList(anotherArrayList, someOtherObject.CREATOR);
}
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel outParcel, int flags) {
outParcel.writeTypedList(anotherArrayList);
}
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
#Override
public mObjectClass createFromParcel(Parcel in) {
return new mObjectClass(in);
}
#Override
public mObjectClass[] newArray(int size) {
return new mObjectClass[size];
}
};
}
someOtherObject:
public class someOtherObject implements Parcelable {
String someString;
//add getter + setter...
public void writeToParcel(Parcel out, int flags) {
out.writeString(someString);
}
public static final Parcelable.Creator<someOtherObject> CREATOR = new Parcelable.Creator<someOtherObject>() {
public someOtherObject createFromParcel(Parcel in) {
return new someOtherObject(in);
}
public someOtherObject[] newArray(int size) {
return new someOtherObject[size];
}
};
public int describeContents() {
return 0;
}
public someOtherObject(Parcel in) {
someString = in.readString();
}
public someOtherObject() {
}
public someOtherObject(String someString) {
this.someString = someString;
}
}
Tada, you are now able to add mObjectClass as extra to your intents after initialising it and using a setter to set the Arraylist with other someOtherObjects.

How to Pass Custom Arraylist content from one Activity to another Activity in android

i have an objects in an custom arraylist as "finaljsoncontent", and now i am trying to pass this "finaljsoncontent" array to another Activity, and i have also tried getters and setters, and also bundle, but i cant, help me how to do this.
Thanks in advance.
Check this out: How do I pass an object from one activity to another on Android?
Your class "JSonKey" should implement parcealable or serializable so that Android can "send" it from an activity to the other activity.
You could try implementing Parcelable, then you can pass it in a bundle. You will need to reduce your object to mostly primitive types to do this. Otherwise you can extend the Application class and store it there. You would retrieve that using the call to getApplicationContext(). Or, of course, you could always create some sort of static globals class that all of your classes can reference.
Here is one of my implementations of parcelable..
package warrior.mail.namespace;
import android.os.Parcel;
import android.os.Parcelable;
public class JView implements Parcelable {
public String subject;
public String from;
public boolean unread;
public String body;
public int inboxIndex;
private long id;
public static final Parcelable.Creator<JView> CREATOR = new Parcelable.Creator<JView>() {
public JView createFromParcel(Parcel in) {
return new JView(in);
}
public JView[] newArray(int size) {
return new JView[size];
}
};
public JView(){
body = "";
}
public JView(String subject,String from,boolean unread){
body = "";
this.subject = subject;
this.from = from;
this.unread = unread;
}
public JView(Parcel parcel){
subject = parcel.readString();
from = parcel.readString();
body = parcel.readString();
unread = parcel.createBooleanArray()[0];
inboxIndex = parcel.readInt();
}
#Override
public int describeContents() {
return inboxIndex;
}
#Override
public void writeToParcel(Parcel out, int arg1) {
out.writeString(subject);
out.writeString(from);
out.writeString(body);
boolean[] array = new boolean[] {unread};
out.writeBooleanArray(array);
out.writeInt(inboxIndex);
}
public void setIndex(int index){
inboxIndex = index;
}
public void setUnread(boolean arg){
unread = arg;
}
public void setContent(String content){
body = content;
}
public void setSubject(String subject){
this.subject = subject;
}
public void setFrom(String f){
from = f;
}
public void setId(long arg){
id = arg;
}
public long getId(){
return id;
}
public void updateIndex(){
}
}
You can either make your class Parcelable(android specific) or make it serializable like in java(just write implements Serializable with your class)

Categories

Resources