I'm having a problem with SharedPreferences. The same code works in one activity in another app, but does not work anywhere else within that app, and in this app it does not work at all. Could you please tell me what I'm doing wrong? I have previously tried to create public final static String for the sharedprefand value keys, but even that didn't work. The code is.
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();
}
And I'm receiving with
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);
}
There was no problem with the code. I thought SharedPreferences would automatically run and load all values when the app was started, but it turns out that the activities in which the SharedPreferences exist need to be opened in order for the method to be executed.
I would like to thank those that tried to help, I greatly appreciate your efforts.