Use Parcelables instead. Here you have an example.
Parcelable is the way Android uses to communicate between activites. In order to use it, you must create a class that implements Parcelable:
import android.
public class MyClass implements Parcelable
{
private string userName;
private int userAge;
public void SetUserName(string name) { userName = name; }
public string GetUserName() { return userName; }
public void SetUserAge(int age) { userAge = age; }
public int GetUserAge() { return age; }
// Some inner stuff
}
This class needs to implement the WriteToParcel
method, which writes into a Parcel all the needed info:
@Override
public void WriteToParcel(Parcel dest, int flags)
{
dest.writeString(userName);
dest.writeInt(userAge);
// Since here you wrote into dest Parcel your string and int
}
In order to be able to read from that Parcel, you need to do the following:
public static final Parcelable.Creator<ExtractionConfig> CREATOR = new Creator<ExtractionConfig>() {
{
@Override
public MyClass [] newArray(int size) {
return new MyClass [size];
}
@Override
public MyClass createFromParcel(Parcel source) {
MyClass toReturn = new MyClass ();
toReturn.setUserName(source.readString());
toReturn.setUserAge(source.readInt());
return toReturn;
}
};
IMPORTANT: the writeToParcel order MUST BE THE SAME than the createFromParcel order!!
How to pass Parcel between activities:
When you launch an activity from another one, you call an Intent
. You can put extra information in it by creating an object of the Parcelable class and fill it:
MyClass myclass = new MyClass();
myclass.setUserName("first user");
myclass.setUserAge(20);
And then put that extra information into your Intent:
In your main activity:
Intent intent = new Intent(this, ActivityToBeCalled.class);
intent.putExtra(myclass, "extraclass"); // look at this string, this one will be your identifier to receive the extra information
startActivity(intent);
To read information from the intent in the called class:
In your second activity:
Intent intent = getIntent();
MyClass myReceivedClass = intent.getParcelableExtra("extraclass"); // here you use your string identifier defined in putExtra(...);
And now, in myReceivedClass
you should have all your MyClass
information.