How to send an object from one Android Activity to another using Intents?

后端 未结 30 3442
-上瘾入骨i
-上瘾入骨i 2020-11-21 04:47

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?

相关标签:
30条回答
  • 2020-11-21 05:13
    public class SharedBooking implements Parcelable{
    
        public int account_id;
        public Double betrag;
        public Double betrag_effected;
        public int taxType;
        public int tax;
        public String postingText;
    
        public SharedBooking() {
            account_id = 0;
            betrag = 0.0;
            betrag_effected = 0.0;
            taxType = 0;
            tax = 0;
            postingText = "";
        }
    
        public SharedBooking(Parcel in) {
            account_id = in.readInt();
            betrag = in.readDouble();
            betrag_effected = in.readDouble();
            taxType = in.readInt();
            tax = in.readInt();
            postingText = in.readString();
        }
    
        public int getAccount_id() {
            return account_id;
        }
        public void setAccount_id(int account_id) {
            this.account_id = account_id;
        }
        public Double getBetrag() {
            return betrag;
        }
        public void setBetrag(Double betrag) {
            this.betrag = betrag;
        }
        public Double getBetrag_effected() {
            return betrag_effected;
        }
        public void setBetrag_effected(Double betrag_effected) {
            this.betrag_effected = betrag_effected;
        }
        public int getTaxType() {
            return taxType;
        }
        public void setTaxType(int taxType) {
            this.taxType = taxType;
        }
        public int getTax() {
            return tax;
        }
        public void setTax(int tax) {
            this.tax = tax;
        }
        public String getPostingText() {
            return postingText;
        }
        public void setPostingText(String postingText) {
            this.postingText = postingText;
        }
        public int describeContents() {
            // TODO Auto-generated method stub
            return 0;
        }
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(account_id);
            dest.writeDouble(betrag);
            dest.writeDouble(betrag_effected);
            dest.writeInt(taxType);
            dest.writeInt(tax);
            dest.writeString(postingText);
    
        }
    
        public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
        {
            public SharedBooking createFromParcel(Parcel in)
            {
                return new SharedBooking(in);
            }
            public SharedBooking[] newArray(int size)
            {
                return new SharedBooking[size];
            }
        };
    
    }
    

    Passing the data:

    Intent intent = new Intent(getApplicationContext(),YourActivity.class);
    Bundle bundle = new Bundle();
    i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
    intent.putExtras(bundle);
    startActivity(intent);
    

    Retrieving the data:

    Bundle bundle = getIntent().getExtras();
    dataList2 = getIntent().getExtras().getParcelableArrayList("data");
    
    0 讨论(0)
  • 2020-11-21 05:14

    If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).

    From the docs, a simple example for how to implement is:

    // simple class that just has one member property as an example
    public class MyParcelable implements Parcelable {
        private int mData;
    
        /* everything below here is for implementing Parcelable */
    
        // 99.9% of the time you can just ignore this
        @Override
        public int describeContents() {
            return 0;
        }
    
        // write your object's data to the passed-in Parcel
        @Override
        public void writeToParcel(Parcel out, int flags) {
            out.writeInt(mData);
        }
    
        // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
        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];
            }
        };
    
        // example constructor that takes a Parcel and gives you an object populated with it's values
        private MyParcelable(Parcel in) {
            mData = in.readInt();
        }
    }
    

    Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).

    Once you have your objects implement Parcelable it's just a matter of putting them into your Intents with putExtra():

    Intent i = new Intent();
    i.putExtra("name_of_extra", myParcelableObject);
    

    Then you can pull them back out with getParcelableExtra():

    Intent i = getIntent();
    MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
    

    If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:

    i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
    i.putExtra("serializable_extra", (Serializable) myParcelableObject);
    
    0 讨论(0)
  • 2020-11-21 05:15

    Short answer for fast need

    1. Implement your Class to Serializable.

    If you have any inner Classes don't forget to implement them to Serializable too!!

    public class SportsData implements  Serializable
    public class Sport implements  Serializable
    
    List<Sport> clickedObj;
    

    2. Put your object into Intent

     Intent intent = new Intent(SportsAct.this, SportSubAct.class);
                intent.putExtra("sport", clickedObj);
                startActivity(intent);
    

    3. And receive your object in the other Activity Class

    Intent intent = getIntent();
        Sport cust = (Sport) intent.getSerializableExtra("sport");
    
    0 讨论(0)
  • 2020-11-21 05:18

    There are a couple of ways by which you can access variables or objects in other classes or Activity.

    A. Database

    B. shared preferences.

    C. Object serialization.

    D. A class that can hold common data can be named Common Utilities it depends on you.

    E. Passing data through Intents and Parcelable Interface.

    It depends upon your project needs.

    A. Database

    SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions, and prepared statements.

    Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html

    B. Shared Preferences

    Suppose you want to store username. So there will be now two things a Key Username, Value Value.

    How to store

     // Create an object of SharedPreferences.
     SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
     //now get Editor
     SharedPreferences.Editor editor = sharedPref.edit();
     //put your value
     editor.putString("userName", "stackoverlow");
    
     //commits your edits
     editor.commit();
    

    Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.

    How to fetch

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String userName = sharedPref.getString("userName", "Not Available");
    

    http://developer.android.com/reference/android/content/SharedPreferences.html

    C. Object Serialization

    Object serialization is used if we want to save an object state to send it over the network or you can use it for your purpose also.

    Use java beans and store in it as one of his fields and use getters and setter for that

    JavaBeans are Java classes that have properties. Think of properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

    public class VariableStorage implements Serializable  {
    
        private String inString ;
    
        public String getInString() {
            return inString;
        }
    
        public void setInString(String inString) {
            this.inString = inString;
        }
    
    
    }
    

    Set the variable in your mail method by using

    VariableStorage variableStorage = new VariableStorage();
    variableStorage.setInString(inString);
    

    Then use object Serialzation to serialize this object and in your other class deserialize this object.

    In serialization, an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

    After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

    If you want a tutorial for this to refer this link

    http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

    Get variable in other classes

    D. CommonUtilities

    You can make a class by your self which can contain common data which you frequently need in your project.

    Sample

    public class CommonUtilities {
    
        public static String className = "CommonUtilities";
    
    }
    

    E. Passing Data through Intents

    Please refer to this tutorial for this option of passing data.

    http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/

    0 讨论(0)
  • 2020-11-21 05:19

    You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.

    In that case you just put the string return value from (new Gson()).toJson(myObject); and retrieve the string value and use fromJson to turn it back into your object.

    If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.

    0 讨论(0)
  • 2020-11-21 05:19

    In your first Activity:

    intent.putExtra("myTag", yourObject);
    

    And in your second one:

    myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");
    

    Don't forget to make your custom object Serializable:

    public class myCustomObject implements Serializable {
    ...
    }
    
    0 讨论(0)
提交回复
热议问题