尝试使用 java Android Studio 永久设置文本

Trying to permanently setText using java Android Studio

我正在尝试使用以下代码设置文本,代码工作正常,但是当我更改 activity 然后恢复为 activity 时,setText 似乎重置了。还有其他方法可以解决这个问题吗?

       public void onClick(View v) {
            String Note = editTextNote.getText().toString();
            String Email = mAuth.getCurrentUser().getEmail();
            String Status = ("IN");
            
            
            tvClockingStatus.setText("You are clocked: IN");

Android 中的活动在正常应用程序生命周期的不同时间创建和销毁(例如,当您旋转屏幕或离开时)。如果您希望数据的保存时间长于 Activity 的生命周期,您需要将其存储在更永久的地方。

存储少量数据的一个常见位置是 SharedPreferences,它将 key-value 对写入磁盘,因此即使应用程序停止并重新启动或 [=24] =] 被销毁并重新创建。

这是一个简单的示例,说明如何使用 SharedPreferences 保存“打卡上班”状态字符串。在 onResume 调用中,数据从保存的首选项加载并应用于 TextView。

public class MainActivity extends AppCompatActivity {

    private SharedPreferences prefs;
    private TextView status;
    private static final String statusKey = "CLOCKED_STATUS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        Button clockIn = findViewById(R.id.clock_in);
        Button clockOut = findViewById(R.id.clock_out);
        status = findViewById(R.id.clocking_status);

        clockIn.setOnClickListener(v -> {
            updateStatus("Clocked In");
        });

        clockOut.setOnClickListener(v -> {
            updateStatus("Clocked Out");
        });
    }

    private void updateStatus(String newStatus) {
        // save the new state in the preferences - can use 
        // putInt, putBoolean, or several other options to 
        // save different data types
        SharedPreferences.Editor ed = prefs.edit();
        ed.putString(statusKey, newStatus);
        ed.apply();

        // Update the data shown in the TextView
        status.setText(newStatus);
    }

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

        // Load the saved status and show it in the TextView
        String defaultStatus = "Clocked Out";
        String savedStatus = prefs.getString(statusKey, defaultStatus);
        status.setText(savedStatus);
    }
}