public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyData myData = new MyData(getApplicationContext());
myData.number = 23;
myData.save();
int y = myData.load();
String TAG = "mytag";
Log.d(TAG, "onCreate: " + y);
}
}
public class MyData {
public int number;
private Context context;
public MyData(Context context) {
this.context = context;
}
public void save() {
String name = context.getResources().getString(R.string.MY_DATA);
String key = context.getResources().getString(R.string.MY_KEY);
SharedPreferences shp = context.getSharedPreferences("name",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shp.edit();
editor.putInt(key,number);
editor.apply();
}
public int load() {
String name = context.getResources().getString(R.string.MY_DATA);
String key = context.getResources().getString(R.string.MY_KEY);
SharedPreferences shp = context.getSharedPreferences("name",Context.MODE_PRIVATE);
int x =shp.getInt(key,context.getResources().getInteger(R.integer.defvalue));
number = x;
return x;
}
}