SharedPreferences 有问题,它不会将值保存到 SharedPreferences。调用时只显示默认值

Having a problem with SharedPreferences where it does not save a value to SharedPreferences. When called, only default value showing

我在使用 SharedPreferences 时遇到问题。相同的代码在另一个应用程序的一个 activity 中有效,但在该应用程序的其他任何地方都不起作用,而在这个应用程序中它根本不起作用。你能告诉我我做错了什么吗?我之前曾尝试为 sharedprefand 值键创建 public final static String,但即使这样也没有用。代码是。

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;

public class SharedPrefs extends AppCompatActivity {

public int VO, VT, VTH;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    VO = 10;
    VT = 15;
    VTH = 25;

    SharedPreferences Stats = getSharedPreferences("STATS", MODE_PRIVATE);
    SharedPreferences.Editor StatEdit = Stats.edit();
    StatEdit.putInt("VOP", VO);
    StatEdit.putInt("VTP", VT);
    StatEdit.putInt("VTHP", VTH);
    StatEdit.apply();

}

我正在接收

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class MM extends AppCompatActivity {

Button b1, b2;
TextView text;
public int VO, VT, VTH;

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

    SharedPreferences Stats = getSharedPreferences("STATS", MODE_PRIVATE);
    VO = Stats.getInt("VOP", 0);
    VT = Stats.getInt("VTP", 0);
    VTH = Stats.getInt("VTHP", 0);



    b1 = findViewById(R.id.button);
    b2 = findViewById(R.id.button2);
    text = findViewById(R.id.textView);

    text.setText("YOU " + VO + VT + VTH);

}
SharedPreferences Stats = getSharedPreferences("STATS", MODE_PRIVATE);

到(可选)

SharedPreferences Stats = getSharedPreferences("STATS", Context.MODE_PRIVATE);

 StatEdit.apply();

 StatEdit.commit();

您必须找零钱。

代码没有问题。我以为 SharedPreferences 会自动 运行 并在应用程序启动时加载所有值,但事实证明需要打开 SharedPreferences 所在的活动才能执行该方法。

我要感谢那些试图提供帮助的人,非常感谢你们的努力。