How to pass an object from one activity to another

2018-12-31 00:23发布

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 the customer class:

public class Customer {

    private String firstName, lastName, Address;
    int Age;

    public Customer(String fname, String lname, int age, String address) {

        firstName = fname;
        lastName = lname;
        Age = age;
        Address = address;
    }

    public String printValues() {

        String data = null;

        data = "First Name :" + firstName + " Last Name :" + lastName
        + " Age : " + Age + " Address : " + Address;

        return data;
    }
}

I want to send its object from one Activity to another and then display the data on the other Activity.

How can I achieve that?

30条回答
临风纵饮
2楼-- · 2018-12-31 00:41
  1. I know that static is bad, but it seems that we're forced to use it here. The problem with parceables/seriazables is that the two activities have duplicate instances of the same object = waste of memory and CPU.

    public class IntentMailBox {
        static Queue<Object> content = new LinkedList<Object>();
    }
    

Calling activity

IntentMailBox.content.add(level);
Intent intent = new Intent(LevelsActivity.this, LevelActivity.class);
startActivity(intent);

Called activity (note that onCreate() and onResume() may be called multiple times when the system destroys and recreates activities)

if (IntentMailBox.content.size()>0)
    level = (Level) IntentMailBox.content.poll();
else
    // Here you reload what you have saved in onPause()
  1. Another way is to declare a static field of the class that you want to pass in that very class. It will serve only for this purpose. Don't forget that it can be null in onCreate, because your app package has been unloaded from memory by system and reloaded later.

  2. Bearing in mind that you still need to handle activity lifecycle, you may want to write all the data straight to shared preferences, painful with complex data structures as it is.

查看更多
情到深处是孤独
3楼-- · 2018-12-31 00:42

While calling an activity

Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);

In toClass.java receive the activity by

Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj");

Please make sure that customer class implements parcelable

public class Customer implements Parcelable {

    private String firstName, lastName, address;
    int age;

    /* all your getter and setter methods */

    public Customer(Parcel in ) {
        readFromParcel( in );
    }

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

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


    @Override
    public void writeToParcel(Parcel dest, int flags) {

        dest.writeString(firstName);
        dest.writeString(lastName);
        dest.writeString(address);
        dest.writeInt(age);
    }

    private void readFromParcel(Parcel in ) {

        firstName = in .readString();
        lastName  = in .readString();
        address   = in .readString();
        age       = in .readInt();
    }
查看更多
冷夜・残月
4楼-- · 2018-12-31 00:42

Yeah, using a static object is by far the easiest way of doing this with custom non-serialisable objects.

查看更多
后来的你喜欢了谁
5楼-- · 2018-12-31 00:47

In my experience there are three main solutions, each with their disadvantages and advantages:

  1. Implementing Parcelable

  2. Implementing Serializable

  3. Using a light-weight event bus library of some sort (for example, Greenrobot's EventBus or Square's Otto)

Parcelable - fast and Android standard, but it has lots of boilerplate code and requires hard-coded strings for reference when pulling values out the intent (non-strongly typed).

Serializable - close to zero boilerplate, but it is the slowest approach and also requires hard-coded strings when pulling values out the intent (non-strongly typed).

Event Bus - zero boilerplate, fastest approach, and does not require hard-coded strings, but it does require an additional dependency (although usually lightweight, ~40 KB)

I posted a very detailed comparison around these three approaches, including efficiency benchmarks.

查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 00:47

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.

查看更多
何处买醉
7楼-- · 2018-12-31 00:47

Start another activity from this activity and pass parameters via Bundle Object

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);

Retrive data on another activity (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

This is ok for simple kind of data type. But if u want to pass complex data in between activity. U need to serialize it first.

Here we have Employee Model

class Employee{
    private String empId;
    private int age;
    print Double salary;

    getters...
    setters...
}

You can use Gson lib provided by google to serialize the complex data like this

String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);

Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
            Gson gson = new Gson();
            Type type = new TypeToken<Employee>() {
            }.getType();
            Employee selectedEmp = gson.fromJson(empStr, type);
查看更多
登录 后发表回答