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

我使用此代码发送数据:

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

当前回答

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

放置数据时使用:

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);

}

其他回答

科特林

第一项活动

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"
}

首先,使用getIntent()方法获取开始活动的意图:

Intent intent = getIntent();

如果额外的数据表示为字符串,则可以使用intent.getStringExtra(字符串名称)方法。在您的案例中:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");

按意图放置数据:

Intent intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);

按意图获取数据:

String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);

如果我们对意图使用整数值,则必须在getIntent().getIntExtra(“instituteId”,0)中将第二个参数设置为0。否则,我们不使用0,Android会给我一个错误。

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

在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 + "");
    }

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

放置数据时使用:

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);

}