Returning object from child activity in android

I have a main_activity that launches a child Activity

via Intent

.

I am aware of the methods getStringExtra(string)

or getBooleanExtra(string)

etc that we call in onActivityResult

; But they are all return

primitive data ... How can I get an object from a custom class from a child activity?

Thanks, and this is my first question! :) seems to be too late ...

+3


source to share


3 answers


You can create a custom object Parcelable

.

like this

public class Student implements Parcelable{

      

add to this intention



intent.putExtra("student", obj);

      

Then we get this object as

Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");

      

+1


source


You are looking for Parcelable

.

A simpler, though not optimal solution Serializable

.

Excerpt:

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

      

Using:



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

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

      

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

      

+1


source


There is this site that makes Parselabel classes from your custom class .... swweeeeeet! http://www.parcelabler.com/

0


source







All Articles