如何在 Android Studio 中将数据从一个 activity 传输到另一个?

How do I transfer data from one activity to another in Android Studio?

我正在创建一个番茄钟应用程序。它有 2 个活动:

我想创建第三个 activity 从第二个 activity 获取输入时间并将它们存储在列表中,但我不知道如何传输从第二个 activity 到第三个 ?

的输入数据

Activity 1:


import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        Button newTime = findViewById(R.id.newTime);
        Button currentTime = findViewById(R.id.currentTime);
        Button recents = findViewById(R.id.recentTime);

        newTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent activity2Intent = new Intent(getApplicationContext(), Activity2.class);
                startActivity(activity2Intent);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
            }

        });

//        currentTime.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent currentActivityIntent = new Intent(getApplicationContext(), currentActivity.class);
//                startActivity(currentActivityIntent);
//                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
//            }
//        });



    }
}

Activity 2:

package com.example.pomotimer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Locale;

public class Activity2 extends AppCompatActivity {



    private TextView TextViewCountdown;
    private Button Button_Start_Pause;
    private Button Reset;
    private Button buttonSet;
    private Button select_Time;
    private EditText edit_Text_Input;


    private CountDownTimer countDownTimer;
    public long mStartTimeinMillis;
    private long timeLeft = mStartTimeinMillis;

    private boolean timerRunning;



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

        TextViewCountdown = findViewById(R.id.textViewCount);
        Button_Start_Pause = findViewById(R.id.bnStartPause);
        Reset = findViewById(R.id.reset);
        select_Time = findViewById(R.id.selectTime);
        edit_Text_Input = findViewById(R.id.edit_Text_Input);
        buttonSet = findViewById(R.id.buttonSet);


        select_Time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_Text_Input.setVisibility(View.VISIBLE);
                buttonSet.setVisibility(View.VISIBLE);

                buttonSet.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String input = edit_Text_Input.getText().toString();
                        if (input.length() == 0){
                            Toast.makeText(Activity2.this, "Field can't be empty", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        long millisInput = Long.parseLong(input)*60000;
                        if (millisInput == 0){
                            Toast.makeText(Activity2.this, "Timer cannot be set to 0", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        setTime(millisInput);
                        edit_Text_Input.setText("");
//                        Intent res = new Intent(getApplicationContext(), currentActivity.class);
//                        startActivityForResult(res, (int) millisInput, null);
                    }


                });


            }




        });





        Button_Start_Pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (timerRunning){
                    pauseTimer();
                }

                else{
                    startTimer();
                }
            }
        });

        Reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetTimer();
            }
        });
        int minutes = (int) (timeLeft/1000)/60;
        int seconds = (int) (timeLeft/1000)%60;

        String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
        TextViewCountdown.setText(timeLeftFormatted);


    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    public void setTime(long milliseconds){
         mStartTimeinMillis = milliseconds;
         resetTimer();

    }

    private void startTimer(){
        countDownTimer = new CountDownTimer(timeLeft,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // The countdown timer has an automatic method of reducing time by 1s
                    timeLeft = millisUntilFinished;

                    int minutes = (int) (timeLeft/1000)/60;
                    int seconds = (int) (timeLeft/1000)%60;

                    String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
                    TextViewCountdown.setText(timeLeftFormatted);

            }

            @Override
            public void onFinish() {
                timerRunning = false;
                Button_Start_Pause.setText("Start");
                Button_Start_Pause.setVisibility(View.INVISIBLE);

            }
        }.start();

        timerRunning = true;
        Button_Start_Pause.setText("pause");

    }

    private void pauseTimer(){
        countDownTimer.cancel();
        timerRunning = false;
        Button_Start_Pause.setText("Start");

    }

    private void resetTimer(){
            timeLeft = mStartTimeinMillis;
        int minutes = (int) (timeLeft/1000)/60;
        int seconds = (int) (timeLeft/1000)%60;
        Button_Start_Pause.setVisibility(View.VISIBLE);

        String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
        TextViewCountdown.setText(timeLeftFormatted);
    }

    @Override
    protected void onStop() {
        super.onStop();

        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putLong("millisleft", timeLeft);
        editor.putBoolean("timerRunning", timerRunning);

        editor.apply();

    }

    @Override
    protected void onStart() {
        super.onStart();

        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        timeLeft = prefs.getLong("millisleft",mStartTimeinMillis);
        timerRunning = prefs.getBoolean("timeRunning", false);

        int minutes = (int) (timeLeft/1000)/60;
        int seconds = (int) (timeLeft/1000)%60;

        String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
        TextViewCountdown.setText(timeLeftFormatted);

    }



}

我们可以使用 Intent 将数据传递给另一个 activity。

和startActivity之前一样,我们需要做的是: intent.putExtra("数据", 数据);

在 thirdActivity onCreate 中我们需要做的 intent.getStringExtra("数据");

里面Activity2

您可以直接将数据放在 Intent 中,也可以将它们放在 Bundle 中,然后再放在 Intent 中。避免同时使用两者以保持一致性。

  Intent activity3Intent = new Intent(getApplicationContext(), Activity3.class);
  //Direct Intent approach
  activity3Intent.putExtras("YOUR_STRING_KEY","YOUR_DATA");
  //OR Bundle approach
  Bundle bundle = new Bundle();
  bundle.putString("YOUR_STRING_KEY","YOUR_DATA");
  activity3Intent.putExtras(bundle);
  startActivity(activity3Intent);

里面 Activity3 class.

//if direct intent approach
String value = getIntent.getStringExtra("YOUR_STRING_KEY") 
//If bundle approach was used.
String value = getIntent().getExtras().getString("YOUR_STRING_KEY");