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:38

I had always wondered why this can't be as simple as calling into a method of the other activity. I recently wrote a utility library that makes it almost as simple as that. You can check it out here(https://github.com/noxiouswinter/gnlib_android/wiki/gnlauncher).

GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in tha Activity with the required data as parameters. It introduces type safety and removes all the hastles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.

Usage

Define an interface with the methods you want to call on the Activity to launch.

public interface IPayload {
    public void sayHello(String name, int age);
}

Implement the above interface on the Activity to launch into. Also notify GNLauncher when the activity is ready.

public class Activity_1 extends Activity implements IPayload {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Notify GNLauncher when the Activity is ready. 
        GNLauncher.get().ping(this);
    }

    @Override
    public void sayHello(String name, int age) {
        Log.d("gnlib_test", "Hello " + name + "! \nYour age is: " + age);
    }
}

In the other Activity, get a proxy to the above Activity and call any method with the desired parameters.

public class Activity_2 extends Activity {
    public void onClick(View v) {
        ((IPayload)GNLauncher.get().getProxy(this, IPayload.class, Activity_1.class)).sayHello(name, age);
    }
}

The first activity will be launched and the method called into with the required parameters.

Prerequisites

Please refer to https://github.com/noxiouswinter/gnlib_android/wiki#prerequisites for information on how to add the dependencies.

查看更多
呛了眼睛熬了心
3楼-- · 2018-12-31 00:38

I used to set object with Pacelable or Serializable to transfer, but whenever I add other variables to object(model), I have to register it all. It's so nconvenient.

It's super easy to transfer object between activities or fragments.

Android DataCache

查看更多
只靠听说
4楼-- · 2018-12-31 00:38

Pass one activity to another:

startActivity(new Intent(getBaseContext(),GetActivity.class).putExtra("passingkey","passingvalue"));

Get values:

String myvalue= getIntent().getExtras("passingkey");
查看更多
ら面具成の殇う
5楼-- · 2018-12-31 00:40

This question is also discussed in another Stack Overflow question. Please have a look at a solution to Passing data through intent using Serializable. The main point is about using Bundle object which stores the necessary data inside Intent.

 Bundle bundle = new Bundle();

 bundle.putSerializable(key1, value1);
 bundle.putSerializable(key2, value2);
 bundle.putSerializable(key3, value3);

 intent.putExtras(bundle);

To extract values:

 Bundle bundle = new Bundle();

 for (String key : bundle.keySet()) {
 value = bundle.getSerializable(key));
 }

Advantage of Serializable is its simplicity. However, you should consider using Parcelable method if you need many data to be transferred, because Parcelable is specifically designed for Android and it is more efficient than Serializable. You can create Parcelable class using:

  1. an online tool - parcelabler
  2. a plugin for Android Studio - Android Parcelable code generator
查看更多
梦寄多情
6楼-- · 2018-12-31 00:40

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");
查看更多
余欢
7楼-- · 2018-12-31 00:41

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)
查看更多
登录 后发表回答