1

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
GCM 4IB
  • 21
  • 1
  • 1
  • 4
  • What exactly is this object? What is its Java class? – CommonsWare Jun 29 '17 at 13:49
  • 1
    It' a MongoDBAndroidDriver class – GCM 4IB Jun 29 '17 at 13:50
  • 3
    My guess is that it should be a singleton, either directly or through some sort of wrapper. So, you are not passing it around, but everything can refer to it. Regardless, you have no means of passing it between activities, so it is either going to be a singleton or you are going to have to stick to a single activity (e.g., using multiple fragments). – CommonsWare Jun 29 '17 at 13:51
  • @GCM4IB You must not pass this kind of classes through Intent it will error prone. – Krish Jun 29 '17 at 13:53
  • What can I do? I've thought that I can rewrite my app using fragment, but it'll take too much time – GCM 4IB Jun 29 '17 at 13:54
  • @GCM4IB Just write singleton class as per Commonsware . – Krish Jun 29 '17 at 13:57
  • Can I use Gson to encode my class to a String, pass it through intents and then decode it? – GCM 4IB Jun 29 '17 at 13:57
  • What's a singleton class? – GCM 4IB Jun 29 '17 at 13:58
  • @GCM4IB Share your code for initializing MongoDBAndroidDriver. – Krish Jun 29 '17 at 14:00
  • https://stackoverflow.com/a/37385493/908821 @GCM4IB, here's an example of the singleton solution – Angel Koh Jun 29 '17 at 14:02
  • This has been asked time and again: https://stackoverflow.com/search?q=pass+object+between+activities. Please do a search before creating new questions. Also, as mentioned by others, what you are trying to accomplish here is not a good idea. You should only pass simple data -- if anything -- between intents. – Eduardo Naveda Mar 07 '18 at 10:13

7 Answers7

10

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 
        }
Kailas Bhakade
  • 1,902
  • 22
  • 27
2

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

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

Naveen Tamrakar
  • 3,349
  • 1
  • 19
  • 28
1

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());
Prashant Sharma
  • 1,357
  • 1
  • 21
  • 31
0

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");
  • I can't modify the source code of my class, so I can't implement Parcelable – GCM 4IB Jun 29 '17 at 13:45
  • If you can't do that, then it's not possible. If you want you can make a new parcelable object, like a clone of your existing one by setting the values from the old object to the new one, or you can pass only the important parts like id, name, description etc.. – Stilianos Tzouvaras Jun 29 '17 at 13:49
0

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

ram
  • 483
  • 1
  • 4
  • 11
0

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