ericyoung
ericyoung

Reputation: 641

Android: passing object between activities and make it parcelable

New to Android programming. Having trouble to pass the object between activities and make it parcelable. Could somebody tell me what the problem could be? I want to know whether the logic is sound.

public class MainActivity extends Activity {

    private Bundle MyActivityParams;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(this, MyActivity.class);
        MyActivityParams = fillInData(MyActivityParams);
        intent.putExtras(MyActivityParams);
        startActivity(intent, savedInstanceState);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    private Bundle fillInData(Bundle bundle){

        bundle.putFloat("com.company.MyActivity.FL", 12);
        bundle.putFloat("com.company.MyActivity.VH", 100);
        bundle.putFloat("com.company.MyActivity.const", 1);
        return bundle;
    }
}

public class DisplayActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        displayData();

    }
    private void displayData(){
        //ActivityData is from MyActivity
        ActivityData data = new ActivityData(getIntent().getExtras());

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_display, menu);
        return true;
    }
}

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        displayParams();
    }
    private void displayParams(){
        ActivityData dataBundle = new ActivityData((getIntent()).getExtras());
        transfer(dataBundle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_algorithm, menu);
        return true;
    }

    public void transfer(ActivityData incomingdata){
        startActivity(incomingdata.getIntent());
    }

    protected static class ActivityData{
        private Bundle data;
        private TextView text;
        private Intent intent;
        public ActivityData(Bundle bundle){
            /*data = bundle;
            intent = new Intent(null, DisplayActivity.class);
            text = new TextView(null);*/
        }

        public void display(String key){
            this.text.setText(data.getString(key));
                    //not allowed: startActivity(intent);
        //not allowed either: setContentView(text);
        }

        public Intent getIntent() {
            return intent;
        }
        public void setIntent(Intent intent) {
            this.intent = intent;
        }
        public TextView getText() {
            return text;
        }
        public void setText(TextView text) {
            this.text = text;
        }
        public Bundle getData() {
            return data;
        }
        public void setData(Bundle data) {
            this.data = data;
        }
    }
}

Upvotes: 0

Views: 4750

Answers (3)

Zohaib
Zohaib

Reputation: 2865

try this one.

ParcelTest.java

import java.util.HashMap;

import android.os.Parcel;
import android.os.Parcelable;

public class ParcelTest implements Parcelable {
    private HashMap map;

    public ParcelTest() {
        map = new HashMap();
    }

    public ParcelTest(Parcel in) {
        map = new HashMap();
        readFromParcel(in);
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public ParcelTest createFromParcel(Parcel in) {
            return new ParcelTest(in);
        }

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

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(map.size());
        for (String s: map.keySet()) {
            dest.writeString(s);
            dest.writeString(map.get(s));
        }
    }

    public void readFromParcel(Parcel in) {
        int count = in.readInt();
        for (int i = 0; i < count; i++) {
            map.put(in.readString(), in.readString());
        }
    }

    public String get(String key) {
        return map.get(key);
    }

    public void put(String key, String value) {
        map.put(key, value);
    }
}

ExampleSupplierActivity.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class ExampleSupplierActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ParcelTest p = new ParcelTest();
        p.put("green", "go");
        p.put("yellow", "wait");
        p.put("red", "stop");

        Bundle b = new Bundle();
        b.putParcelable("com.example.trafficlight", p);

        Intent i = new Intent(this, ExampleConsumerActivity.class);
        i.putExtras(b);

        startActivity(i);
    }
}

ExampleConsumerActivity.java

import android.app.Activity;
import android.os.Bundle;

public class ExampleConsumerActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle b = getIntent().getExtras();

        ParcelTest p = b.getParcelable("com.example.trafficlight");

        String red = p.get("red");
        // ...
    }
}

Upvotes: 0

user219882
user219882

Reputation: 15844

Let's have a Person class

public class Person {
    private String name;
    private String email;
    private int age;

    public Person(int age, String name, String email) {
        this.age = age;
        this.name = name;
        this.email = email;
    }
}

A parcelable one would look like this

public class ParcelablePerson implements Parcelable {

    private final Person person;

    private ParcelablePerson(Parcel parcel) {
        this.person = new Person(parcel.readInt(), parcel.readString(), parcel.readString());
    }

    public ParcelablePerson(Person person) {
        this.person = person;
    }

    public Person getPerson() {
        return person;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    // This is the method where you disassembly your object to pieces
    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeInt(person.getAge());
        parcel.writeString(person.getName());
        parcel.writeString(person.getEmail());
    }

    public static final Creator<ParcelablePerson> CREATOR = new Creator<ParcelablePerson>() {

        // And here you create a new instance from a parcel using the first constructor
        @Override
        public ParcelablePerson createFromParcel(Parcel parcel) {
            return new ParcelablePerson(parcel);
        }

        @Override
        public ParcelablePerson[] newArray(int size) {
            return new ParcelablePerson[size];
        }

    };
}

The crucial thing in the process is to have the same order of the variables in private ParcelablePerson(Parcel parcel) constructor and public void writeToParcel(Parcel parcel, int flags) method... You can see it on the age property which is an int.

Upvotes: 2

Zohaib
Zohaib

Reputation: 2865

try this out this code work for me. but i have implement serializable rather than parcelable. Try to implement parcelable rather than serializable . and try it if its work. i havnt tried this but implementing parcelable.

To pass and object to another activity:

in activity A
make sure the class implements the serializable interface
create a new intent
create a new bundle 
use the putSerializeable method to add the object to the bundle with a key
put the bundle in the intent by using the putExtras method
start the activity using the startActivity method


Specifically, 
        Intent intent = new Intent(ShoulderExerciseScreen.this, ExercisesScreen.class);

        Bundle bundle = new Bundle();
        bundle.putSerializable("exercise", new Exercise("BenchPress));

        intent.putExtras(bundle);

        startActivity(intent);
in activity B
declare and object of the type you want passed
use the getIntent method  to get the intent
use the getSerializeableExtra to get the the value using the key
cast the returned value from getSerializeableExtra and the desired type
    Specifically,
        Exercise ex = (Exercise)getIntent().getSerializableExtra("exercise");

        if(ex != null)
        {
            //do something
        }

Upvotes: -1

Related Questions