Passing object to other activity - android

I have question about sending object to other activity. Im not sure about this what im doing. So i have object Player in MainActivity
final Player player = new Player("Player", 150);
I have separate class for Player with simple constructor
public class Player {
private String playerName;
private double playerCash;
Player(String playerName, double playerCash)
{
this.playerName = playerName;
this.playerCash = playerCash;
}
And i have second Activity , where i want use Player object. I made a button in MainActivity with this code
mButton = (Button) findViewById(R.id.mButton);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("player", player);
startActivity(intent);
}
});
And now i got problem "Cannot resolve method putExtra". What am i doing wrong? I want only one Player object and want to use it in multiple activities but have no idea how. For any help, big thanks ;)

Everything that mentioned in the answers above, describe the solution very clearly.
Here is the code :
public class Player implements Parcelable{
private String playerName;
private double playerCash;
// Constructor
public Player(String playerName, double playerCash){
this.playerName = playerName;
this.playerCash = playerCash;
}
// Implement Getter and setter methods
// Parcelling part
public Player(Parcel in){
this.playerName = in.readString();
this.playerCash = in.readDouble();
}
#Оverride
public int describeContents(){
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(playerName);
dest.writeDouble(playerCash);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Player createFromParcel(Parcel in) {
return new Player(in);
}
public Player[] newArray(int size) {
return new Player[size];
}
};
}

Passing in custom objects is a little more complicated. You could just mark the class as Serializable and let Java take care of this.
However, on the android, there is a serious performance hit that comes with using Serializable. The solution is to use Parcelable. Follow this link for implementation details: http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

You can use parcelable for that, take a look at my post here:
https://stackoverflow.com/a/35252575/982161
since you need to make some changes on the player class.

Make one Serializable class
import java.io.Serializable;
#SuppressWarnings("serial")
public class MyPlayer implements Serializable {
private String playerName;
private double playerCash;
public MyPlayer(String playerName, double playerCash) {
this.playerName = playerName;
this.playerCash = playerCash;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public double getPlayerCash() {
return this.playerCash;
}
public void setPlayerCash(double playerCash) {
this.playerCash = playerCash;
}
}
then in your button click put
mButton = (Button) findViewById(R.id.mButton);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyPlayer myPlayer = new MyPlayer(playerName,playerCash);
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("key", myPlayer);
startActivity(i);
}
});
To get Passed Data use(in second activity)
Intent i = getIntent();
MyPlayer myPlayer = (MyPlayer)i.getSerializableExtra("key");

Related

Pass Objects between Activities

I'm devlopping an Android app made of multiple Activities and I have to pass ab Object between them, but I can't pass it by using intents because the class of the object doesn't implement serializable, how can I do it?
I CAN'T MODIFY THE SOURCE CODE OF MY CLASS
Thanks :)
public class MyClass { //stuff }
//I can't modify this source code
MyClass m = new MyClass(); //object I have to pass
Suppose there is a data object class named StudentDataObject having some data types.
StudentDataObject studentDataObject = new StudentDataObject();
Gson gson = new Gson();
String studentDataObjectAsAString = gson.toJson(studentDataObject);
Now we are passing it from one activity to another activity using intent.
Intent intent = new Intent(FromActivity.this, ToActivity.class);
intent.putExtra("MyStudentObjectAsString", studentDataObjectAsAString);
startActivity(intent);
Now we are in new activity, we get that object here using following line.
Gson gson = new Gson();
String studentDataObjectAsAString = getIntent().getStringExtra("MyStudentObjectAsString");
StudentDataObject studentDataObject = gson.fromJson(studentDataObjectAsAString, StudentDataObject.class);
Activity itself know where from I am called, so we can directly write getIntent() method.
Here we only need to add one dependency of GSON we can add it using following line in build.gradle file.
compile 'com.google.code.gson:gson:2.6.2'
And one thing is that implement StudentDataObject as a Parcelable and if showing error then just press alt+Enter and implement methods.
Try this once, Hope it will work.
Sample Example for StudentDataObject should be like :-
public class StudentDataObject implements Parcelable {
// fields
//empty constructor
//parameterised constructor
//getters and setters
//toString method
//last implement some Parcelable methods
}
First of all create Parcelable data model.
public class DataModel implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<DataModel> CREATOR
= new Parcelable.Creator<DataModel>() {
public DataModel createFromParcel(Parcel in) {
return new DataModel(in);
}
public DataModel[] newArray(int size) {
return new DataModel[size];
}
};
private DataModel(Parcel in) {
mData = in.readInt();
}
}
put object into intent
intent.putExtra("KEY", object);
get object from intent
object = getIntent().getExtras().getParcelable("KEY");
This code may help you:
public class EN implements Serializable {
//... you don't need implement any methods when you implements Serializable
}
FirstActivity
EN enumb = new EN();
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("en", enumb); //second param is Serializable
startActivity(intent);
SecandActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
en = (EN)getIntent().getSerializableExtra("en"); //Obtaining data
}
Passing data through intent using Serializable
Here is my object class Book.java
import android.os.Parcel;
import android.os.Parcelable;
public class Book implements Parcelable {
// book basics
private String title;
private String author;
// main constructor
public Book(String title, String author) {
this.title = title;
this.author = author;
}
// getters
public String getTitle() { return title; }
public String getAuthor() { return author; }
// write object values to parcel for storage
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(author);
}
public Book(Parcel parcel) {
title = parcel.readString();
author = parcel.readString();
}
public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {
#Override
public Book createFromParcel(Parcel parcel) {
return new Book(parcel);
}
#Override
public Book[] newArray(int size) {
return new Book[0];
}
};
public int describeContents() {
return hashCode();
}
}
Now you can pass object like this
Button button = (Button) findViewById(R.id.submit_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Book book = new Book(mBkTitle.getText().toString(),
mBkAuthor.getText().toString());
Intent intent = new Intent(MainActivity.this, BookActivity.class);
intent.putExtra("Book", book);
startActivity(intent);
}
});
Now object will be received like this in receiving ReceivingActivity.java
Intent intent = getIntent();
Book book = intent.getParcelableExtra("Book");
mBkTitle.setText("Title:" + book.getTitle());
mBkAuthor.setText("Author:" + book.getAuthor());
You need to implement parcelable and then pass it via intent. Dont use Serializable cause is way slower than parcelable.
Read here how to make your object parcelable: https://developer.android.com/reference/android/os/Parcelable.html
after you dont it, pass your object like this:
intent.putExtra("KEY", your_object);
to read it:
getIntent().getExtras().getParcelable("KEY");
Extend the class and implement serializable or parcelable in the inherited class and use its objects as in other answers.
Class NewClass extends MyClass implements serializable {
//Create a constructor matching super
}
Use objects of this class instead of my class
You can pass a custom object from one activity to another through intent in 2 ways.
By implements Serializable
By implements Parcelable
(1) By implements Serializable no need to do anything just implement Serializable
into your class like
public class Note implements Serializable {
private int id;
private String title;
}
(2) By implementing Parcelable (you have to follow the Parcel write and read with same order)
public class Note implements Parcelable {
private int id;
private String title;
public Note() {
}
Note(Parcel in){
this.id = in.readInt();
this.title = in.readString();
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(title);
}
public static final Parcelable.Creator<Note> CREATOR = new Parcelable.Creator<Note>(){
#Override
public Note createFromParcel(Parcel source) {
return new Note(source);
}
#Override
public Note[] newArray(int size) {
return new Note[size];
}
};
}
and then in your activity
Activity A
intent.putExtra("NOTE", note);
Activity B
Note note = (Note) getIntent().getExtras().get("NOTE");
Imp: Parcelable is 10 times faster than Serializable

Passing and ArrayList<Service> through intent

I have a class called Service, which is used to create Service objects using this constructor
public Service(int id, String service_name, String service_code) {
this.id = id;
this.service_name = service_name;
this.service_code = service_code;
}
then I create a list call service list as with the following signature
List<Service> serviceList = new ArrayList<Service>
I have try to pass this ArrayList through Intent Object like this
Intent i = new Intent(Classname.this, anotherClass.class);
i.putExtras("serviceList",serviceList);
startActivity(i);
But it fails. What is the way I pass through intent with ArrayList object.
Your custom class has to implement Parcelable or Serializable in order to serialize/de-serialize within an Intent.
Your class Service has to look like this for example (used a generator http://www.parcelabler.com/)
public class Service implements Parcelable {
private int id;
private String service_name;
private String service_code;
public Service(int id, String service_name, String service_code) {
this.id = id;
this.service_name = service_name;
this.service_code = service_code;
}
protected Service(Parcel in) {
id = in.readInt();
service_name = in.readString();
service_code = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(service_name);
dest.writeString(service_code);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Service> CREATOR = new Parcelable.Creator<Service>() {
#Override
public Service createFromParcel(Parcel in) {
return new Service(in);
}
#Override
public Service[] newArray(int size) {
return new Service[size];
}
};
}
Then you can use getIntent().getParcelableArrayListExtra() with casting
ArrayList<Service> serviceList= intent.<Service>getParcelableArrayList("list"));
For sending you use it like this
intent.putParcelableArrayListExtra("list", yourServiceArrayList);
Note that the yourServiceArrayList should be an ArrayList
if it is List the you can pass through
intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) yourServiceArrayList);
You can use parcelable interface for 'Service' class, and send object through
intent using 'putParcelableArrayListExtra' method and to retrive data you can use
'getParcelableArrayListExtra'.
For your reference
refer this link
Implement object class with Serializable .
eg.
class abc implements Serializable{
//your code
}
then try this code
ArrayList<abc> fileList = new ArrayList<abc>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putSerializable("arraylisty",filelist);
startActivity(intent);
and on other side receive intent like
your arraylist objact=intent.getSerializableExtra(String name)

How use object in multiple classes?

Im fighting with this some time and still don't know how to make it work. So i have class Player with constructor
Player(String playerName, double playerCash)
{
this.playerName = playerName;
this.playerCash = playerCash;
}
In MainActivity i make a player object
Player player = new Player("player", 100);
And now in TextView in SecondActivity i would like to use
playerCash = (TextView) findViewById(R.id.playerCash);
playerCash.setText(player.getPlayerCash());
Can someone explain me how i can make it works? I get cannot resolve symbol player. Thanks in advance
You can implement Parcelable interface for Player class and then pass instance of it from the MainActivity through Intent to the SecondActivity.
I am unsure if what you have posted is your entire class, or if you obviated a part of it. I will write this answer, assuming that is your entire class.
So, here is the deal: you need to create methods in your class for you to get and set data to/from it.
public class Player() implements Parcelable {
private String playerName;
private String playerCash;
public Player(String playerName, String playerCash) {
this.playerName = playerName;
this.playerCash = playerCash;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerCash() {
return playerCash;
}
public void setPlayerCash(String playerCash) {
this.playerCash = playerCash;
}
public Player(Parcel in) {
String[] data = new String[2];
in.readStringArray(data);
this.playerData = data[0];
this.playerCash = data[1];
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.playerName,
this.playerCash});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Player createFromParcel(Parcel in) {
return new Player(in);
}
public Player[] newArray(int size) {
return new Player[size];
}
};
}
edit
I didn't read the part where you say you want to share it between Activities. I only noticed it because someone mentioned implementing Parcelable, which does help your problem.
Anyway, I edited my code to implement it.
To share data between Activities you will also need an intent, and there you can share the data stored on your Player class:
Intent i = new Intent();
i.putExtra("player", new Player("Jhon", "Over 9000!");
And in your 2nd Activity, to get it you would do:
Bundle b = getIntent().getExtras();
Player player = b.getParcelable("player");
Hope that helps.

Parcelable transfer fails

I'm trying my first Parcelable transfer and it doesn't go fine. This is my Parcelable class :
public class Element implements Parcelable, Serializable {
private static final long serialVersionUID = 1L;
String name;
String id;
byte[] password;
public static final Parcelable.Creator<Element> CREATOR = new Parcelable.Creator<Element>() {
public Element createFromParcel(Parcel source) {
return new Element(source);
}
public Element[] newArray(int size) {
return new Element[size];
}
};
private Element(Parcel in){
name = in.readString();
id = in.readString();
password = new byte[in.readInt()];
in.readByteArray(password);
}
public Element(String name,String id,byte[] password){
this.name=name;
this.id=id;
this.password=password;
}
#Override
public String toString() {
return name;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(id);
dest.writeInt(password.length);
dest.writeByteArray(password);
}
}
As you see, it's a simple Parcelable with 2 String fields and 1 byteArray.
Now I send it to the second activity via my main one :
//Inside the main activity
Intent i = new Intent(MainActivity.this, DisplayActivity.class);
i.putExtra("element", (Parcelable)adapter.getItem(pos));
startActivity(i);
And then, I receive the Parcelable in the second activity :
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.display);
Element e = getIntent().getExtras().getParcelable("element");
//this line makes my app crash. No idea why.
Try it this way:
Element obj = new Element();
//set your data here before send
Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.Element", obj);
startActivity(i);
Then to retrieve it:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
Element obj = b.getParcelable("com.package.Element");
}
}
I was also struggling with the same issue. In your manifest in the MyActivity activity add:
android:launchMode="singleTop"
It solved the issue for me.
<activity android:name="com.example.myapp.MyActivity"
android:label="#string/title_myactivity"
android:launchMode="singleTop">
</activity>
Why would you implement both Parcelable and Serializable?

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