How to pass an object from one activity to another on Android

后端 未结 30 3796
遇见更好的自我
遇见更好的自我 2020-11-21 04:03

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

The code for t

相关标签:
30条回答
  • 2020-11-21 04:51

    If you choose use the way Samuh describes, remember that only primitive values can be sent. That is, values that are parcable. So, if your object contains complex objects these will not follow. For example, variables like Bitmap, HashMap etc... These are tricky to pass by the intent.

    In general I would advice you to send only primitive datatypes as extras, like String, int, boolean etc. In your case it would be: String fname, String lname, int age, and String address.

    My opinion: More complex objects are better shared by implementing a ContentProvider, SDCard, etc. It's also possible to use a static variable, but this may fastly lead to error-prone code...

    But again, it's just my subjective opinion.

    0 讨论(0)
  • 2020-11-21 04:52

    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 which can hold common data can be named as 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

    B. Shared preferences

    Suppose you want to store username. So there will now be two things, a key username, value value.

    How to store

     // Create 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(), and 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 serlization is used if we want to save an object state to send it over a 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 tutorial for this refer to:

    • Serialization in Java (blog post)

    • Get variable in other classes (Stack Overflow)

    D. CommonUtilities

    You can make a class by yourself 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 the tutorial Android – Parcel data to pass between Activities using Parcelable classes for this option of passing data.

    0 讨论(0)
  • 2020-11-21 04:52

    The best way is to have a class (call it Control) in your application that will hold a static variable of type 'Customer' (in your case). Initialize the variable in your Activity A.

    For example:

    Control.Customer = CustomerClass;
    

    Then go to Activity B and fetch it from Control class. Don't forget to assign a null after using the variable, otherwise memory will be wasted.

    0 讨论(0)
  • 2020-11-21 04:53
    • Using global static variables is not good software engineering practice.
    • Converting an object's fields into primitive data types can be a hectic job.
    • Using serializable is OK, but it's not performance-efficient on the Android platform.
    • Parcelable is specifically designed for Android and you should use it. Here is a simple example: Passing custom objects between Android activities

    You can generate Parcelable code for you class using this site.

    0 讨论(0)
  • 2020-11-21 04:53

    Pass object from one activity to another activity.

    (1) source activity

    Intent ii = new Intent(examreport_select.this,
                        BarChartActivity.class);
    
                ii.putExtra("IntentExamResultDetail",
                        (Serializable) your List<ArraList<String>> object here);
                startActivity(ii);
    

    (2) destination acitivity

    List<ArrayList<String>> aa = (List<ArrayList<String>>) getIntent()
                .getSerializableExtra("IntentExamResultDetail");
    
    0 讨论(0)
  • 2020-11-21 04:55

    Use gson to convert your object to JSON and pass it through intent. In the new Activity convert the JSON to an object.

    In your build.gradle, add this to your dependencies

    implementation 'com.google.code.gson:gson:2.8.4'
    

    In your Activity, convert the object to json-string:

    Gson gson = new Gson();
    String myJson = gson.toJson(vp);
    intent.putExtra("myjson", myjson);
    

    In your receiving Activity, convert the json-string back to the original object:

    Gson gson = new Gson();
    YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);
    

    For Kotlin it's quite the same

    Pass the data

    val gson = Gson()
    val intent = Intent(this, YourActivity::class.java)
    intent.putExtra("identifier", gson.toJson(your_object))
    startActivity(intent)
    

    Receive the data

    val gson = Gson()
    val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"), YourObject::class.java)
    
    0 讨论(0)
提交回复
热议问题