首页 > 解决方案 > 在 Android Studio 中从 Intent 接收数据时出现问题

问题描述

我正在编写通过 Intent 发送和接收数据的代码

但是,代码总是有问题:summaryResult

请问,谁能帮帮我?

发送数据的代码:

    ``` nextPage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent senderIntent = new Intent(getApplicationContext(), UserRegistration2.class);
            Bundle sendlerBundler = new Bundle();
            sendlerBlundler.putString("summaryResult", summaryResult);

            senderIntent.putExtras(sendlerBundler);
            startActivity(senderIntent);

            Toast.makeText(getApplicationContext(), "It was sent: " + summaryResult, Toast.LENGTH_LONG).show();
            Intent intent = new Intent(getApplicationContext(), UserRegistration2.class);
            startActivity(intent);

            Bundle param = new Bundle();

            param.putString("name", name);
            param.putString("birthDate", birthDate);
            parame.putString("city", city);
            param.putString("summaryResult", summaryResult);

            senderIntent.putExtras(param);
            startActivity(senderIntent);
            startActivity(intent);
        }
    });``` 

接收数据的代码:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.userRegistration);

        Intent receiverIntent = getIntent();
        Bundle receiverBundle = receiverIntent.getExtras();
        String summaryResult =
                receiverBundle.
                        getString
                                **("summaryResult");**
        Toast.makeText(UserRegistration.this, "Receiving the Summary Result: " +summaryResult, Toast.LENGTH_LONG).show();```

标签: javaandroidxml

解决方案


您声明了 startActivity 4 次,这是错误的,首先您应该将所有需要的数据放入包中,将包添加到意图中,然后只启动一次活动。代码应如下所示:

 public void onClick(View view) {
        Intent senderIntent = new Intent(getApplicationContext(), UserRegistration2.class);
        Bundle sendlerBundler = new Bundle();
        sendlerBlundler.putString("summaryResult", summaryResult);

        senderIntent.putExtras(sendlerBundler);
        startActivity(senderIntent);

    }

接收活动中的代码:

   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.userRegistration);

    Intent receiverIntent = getIntent();
    Bundle receiverBundle = receiverIntent.getExtras();
    String summaryResult = receiverBundle.getString("summaryResult");

}

推荐阅读