无法找到正确传递数据的方法 b.w 两项活动

Can't find a way to properly pass data with intent b.w two activities

每当我从第一个 activity 移动到第二个活动然后回到第一个 activity 时,第一个 activity 中给出的值变为 null ,即使我正在传递该值通过意图来回。

Activity - 1

String date = getIntent().getStringExtra("date");
String name = getIntent().getStringExtra("name");



            textView1.setText(date);
            textView2.setText(name);



        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent(Main.this,date.class);
                intent.putExtra("name1", name);

                startActivity(intent);
            }
        });


  

Activity - 2

calendarView=(CalendarView)findViewById(R.id.calendarView);
        String name1 = getIntent().getStringExtra("name1");
        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {

                String date = dayOfMonth+"-"+month+"-"+year;
                Intent intent = new Intent(date.this , Main.class);
                intent.putExtra("date", date);
                intent.putExtra("name", name1);
                startActivity(intent);
            }
        });



您没有取回数据,因为您正在开始一个新的 activity,而不是返回到之前的 activity 从您的第一个 activity 开始,为结果

开始 activity
int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);

从你的第二个 activity return 结果

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

终于在您的第一个 activity 上,在 onActivityResult

上收到第二个 activity 的结果
Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            // Write your code if there's no result
        }
    }
} //onActivityResult