3

I have a main_activity that starts a child Activity via Intent.

I know about methods getStringExtra(string), or getBooleanExtra(string) etc. that we call in onActivityResult; But they all return a primitive data... How can I get an object from a user-defined class from the child activity?

Thanks, and this is my first question here! :) kinda too late...

N J
  • 27,217
  • 13
  • 76
  • 96
sorry_I_wont
  • 639
  • 1
  • 9
  • 16

3 Answers3

1

You're looking for Parcelable.

A simpler, though non optimal solution is Serializable.

Snippet:

 public class MyParcelable 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<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

Usage:

// Sender class
MyParcelable mp = new MyParcelable();
intent.putExtra("KEY_PARCEL", mp);

// Receiver class
Bundle data = getIntent().getExtras();
MyParcelable student = (Myparcelable)data.getParcelable("KEY_PARCEL");

Here's a working example.

EDIT: Here's how to do it with fragments.

// Receiver class
Bundle data = getIntent().getExtras();

public class MyFragment extends Fragment {

    public static MyFragment newInstance(int index, Bundle data) {
        MyFragment f = new MyFragment();
        data.putInt("index", index);
        f.setArguments(data);
        return f;
    }

}

// In the fragment
Bundle data = getArguments();
xyz
  • 3,349
  • 1
  • 23
  • 29
1

You can create Parcelable custom object.

like this

public class Student implements Parcelable{

add to intent like this

intent.putExtra("student", obj);

Then get That object like

Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
N J
  • 27,217
  • 13
  • 76
  • 96
0

There is this website that makes Parselabel classes out of your custom class....swweeeeeet! http://www.parcelabler.com/

sorry_I_wont
  • 639
  • 1
  • 9
  • 16