如何将数据从一个活动(意图)发送到另一个活动?

我使用此代码发送数据:

Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);

当前回答

科特林

第一项活动

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)

第二项活动

val value = getIntent().getStringExtra("key")

建议

始终将密钥放在常量文件中,以便于管理。

companion object {
    val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}

其他回答

我们可以通过简单的方法做到这一点:

在FirstActivity中:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

在SecondActivity中:

    try {
        Intent intent = getIntent();

        String uid = intent.getStringExtra("uid");
        String pwd = intent.getStringExtra("pwd");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("getStringExtra_EX", e + "");
    }

加起来

设置数据

String value = "Hello World!";
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
intent.putExtra("sample_name", value);
startActivity(intent);

获取数据

String value;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    value = bundle.getString("sample_name");
}

如果您试图获取碎片中的额外数据,则可以尝试使用:

放置数据时使用:

Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);

使用以下方法获取数据:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


  getArguments().getInt(ARG_SECTION_NUMBER);
  getArguments().getString(ARG_SECTION_STRING);
  getArguments().getBoolean(ARG_SECTION_BOOL);
  getArguments().getChar(ARG_SECTION_CHAR);
  getArguments().getByte(ARG_SECTION_DATA);

}
//  How to send value using intent from one class to another class
//  class A(which will send data)
    Intent theIntent = new Intent(this, B.class);
    theIntent.putExtra("name", john);
    startActivity(theIntent);
//  How to get these values in another class
//  Class B
    Intent i= getIntent();
    i.getStringExtra("name");
//  if you log here i than you will get the value of i i.e. john

如果在FragmentActivity中使用,请尝试以下操作:

第一页扩展了FragmentActivity

Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);

在片段中,您只需要首先调用getActivity(),

第二页扩展片段:

String receive = getActivity().getIntent().getExtras().getString("name");