GCM 4IB
GCM 4IB

Reputation: 21

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

Upvotes: 1

Views: 17700

Answers (7)

Manasranjan
Manasranjan

Reputation: 71

You can pass a custom object from one activity to another through intent in 2 ways.

  1. By implements Serializable
  2. 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

Upvotes: 0

Prashant Sharma
Prashant Sharma

Reputation: 1407

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());

Upvotes: 1

Kailas Bhakade
Kailas Bhakade

Reputation: 1922

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 
        }

Upvotes: 10

ram
ram

Reputation: 503

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

Upvotes: 0

Vijay Pal Vishwakarma
Vijay Pal Vishwakarma

Reputation: 731

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");

Upvotes: 2

Stilianos Tzouvaras
Stilianos Tzouvaras

Reputation: 29

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");

Upvotes: 0

Naveen Tamrakar
Naveen Tamrakar

Reputation: 3339

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

Upvotes: 1

Related Questions