Search code examples
androidandroid-activity

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

Solution

  • 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 
            }