Saving data on android APP - android

Hello I'm working on app android which notices the scores of a card's game.
I'm looking for how to save the actual scores and teams' name when the app getting destroyed or stopped to find them when i open it again.
public class ShowScore extends AppCompatActivity {
SharedPreferences save = null;
private TextView nameTeam1= null;
private TextView nameTeam2= null;
private TextView scoreTeam1 = null;
private TextView scoreTeam2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_score);
nameTeam1= (TextView) findViewById(R.id.team1);
nameTeam2= (TextView) findViewById(R.id.team2);
scoreTeam1 = (TextView) findViewById(R.id.score1);
scoreTeam2 = (TextView) findViewById(R.id.score2);
nameTeam1.setText(save.getString("Team1","Team 1"));
nameTeam2.setText(save.getString("Team2","Team 2"));
scoreTeam1.setText(String.valueOf(save.getInt("Score1", 0)));
scoreTeam2.setText(String.valueOf(save.getInt("Score2", 0)));
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
save = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = save.edit();
editor.putString("Team1", nameTeam1.getText().toString());
editor.putString("Team2", nameTeam2.getText().toString());
editor.putInt("Score1", Integer.parseInt(scoreTeam1.getText().toString()));
editor.putInt("Score2", Integer.parseInt(scoreTeam2.getText().toString()));
editor.commit();
}
}
EDIT It is fixed i should add
save = getApplicationContext().getSharedPreferences("MyPref", 0);
Into the onCreate().

Recently i started investing in sqlite database, just purely because it stays on the system, and is further exportable. but a great tutorial i followed was
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
This has all the C.R.U.D for database application.

You can try many options if data is small and just variables then you can try shared preferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
just like that and value will be stored
and for retriving data then you need just
pref.getString("key_name", null); // getting String

Related

Shared Preferences Appearing On-Screen

I am creating an attendance tracker for a summer camp, where counsellors can input the time their camper signed in by typing into an editText and pressing the save button. This basic string should be saved into a textbox and loaded onto the screen every time the app is loaded. There are multiple boxes like this so the counsellors can track what times each student came in / left every day.
I have used sharedPreferences to save the input from the counsellor when a button is pressed, and then display it using another button. However, I CANNOT GET THE TEXT TO APPEAR ON THE SCREEN WHEN I CLOSE AND REOPEN THE APP. Is my code missing something??
public class AttendancePage extends AppCompatActivity {
EditText mondayMorn;
TextView displayMonMorn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
String counsellorName = getIntent().getStringExtra("Senior Counsellor Name");
TextView tv = (TextView)findViewById(R.id.counsellorName);
tv.setText(counsellorName + "'s");
mondayMorn = (EditText) findViewById(R.id.editText37);
displayMonMorn = (TextView) findViewById(R.id.displayMonMorn);
}
public void saveInput (View view) {
SharedPreferences checkInMon = getSharedPreferences("LoginTime", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.apply();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
}
public void updateSettings (View view){
SharedPreferences checkInMon = getSharedPreferences("LoginTime", Context.MODE_PRIVATE);
String time = checkInMon.getString("mondayIn", "");
displayMonMorn.setText(time);
}
Replace:
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.apply();
with:
SharedPreferences.Editor editor = checkInMon.edit();
editor.putString("mondayIn", mondayMorn.getText().toString());
editor.commit();
that should at least save the data in preferences.

Android: issue with data storage (SharedPreferences)

I'm learning android and for this project I need to save user's data - color change of buttons, in this case -. During the program the change occurs (onClick), but when I restart the app, nothing happens - the change has not been saved (or read...) Can someone help me? Code:
final String paintKey = "paint";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCreate();
preferences();
togglePlay();
}
public void preferences(){ //the issue in this method?
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
settings.getBoolean(paintKey,false);
String backGround = settings.getString("stage", "Indoors");
if (backGround.equals("Indoors")) {
Picasso.with(this).load(R.drawable.shocked_crowd).fit().centerCrop().into(stage);
}
if (backGround.equals("Street")) {
Picasso.with(this).load(R.drawable.coins).fit().centerCrop().into(stage);
}
}
public void changeColor(){
if(!paint) { //paint variable has global scope and it is set to false
c1.setBackgroundColor(Color.YELLOW);
paint = true;
}else{
c1.setBackgroundColor(Color.BLUE);
paint = false;
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("paint", paint);
editor.commit();
}
EDIT: the onClick method:
public void onClick(View v) {
if(v==color){
changeColor();
}
EDIT: this is how I have it now:
public void preferences(){
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
final String paintKey = "paint";
settings.getBoolean(paintKey,false);
Wrong? if I put editor instead of settings i get red underlined
In order to work with SharedPreferences you need a global key
final String paintKey = "paint"
To write boolean value info SharedPreferences use
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(paintKey, paint).commit();
To read that data later
paint = settings.getBoolean(paintKey, false);
settings.getBoolean(paintKey,false);
This line gets a value from the SharedPreferences and promptly ignores it. You must save the return value in a variable in order to use it later:
boolean paint = settings.getBoolean(paintKey,false);
This will create a local variable that can only be used in the same method. If you need to use the value in other methods, create a field instead.

How setup default value Shared Preferences in an android apk?

I make a setup class with shared preferences and in the first open apk the user use the default value and after edit if he want it with update value. My problem is when re open the apk and no create preference apk display default value else if there is old preference display this. I want update preferences onCreate with old save preferences if preferences exist(no with default value). How I create this? I want something if pref exist go to share preference...and read value...else use the default
String strValue ="http://www.power7.net/LEDstate.txt";//default value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
/* SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
String strValue = preferences.getString("Url","");
text = (TextView) findViewById(R.id.textUrl);
text.setText(strValue);
*/
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
}
public void Save(View view) {
SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
editor.putString("Url", strUrl); // value to store
// Commit to storage
editor.commit();
Change your code as for setting default value in TextView when user start your Application or any value not exist in SharedPreferences
SharedPreferences preferences;
String strValue="";
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
text = (TextView) findViewById(R.id.textUrl);
preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
strValue = preferences.getString("Url","");
if(!strValue.equals("")){
text.setText(strValue);
}
else{
text.setText("Set Default value here");
}
// your code here
In this way, you can get default value from preference if no value is their corresponding to your preference key
SharedPreferences preferences=getSharedPreferences(preferencename, MODE_PRIVATE);
String str=preferences.getString(key, defaultValue);

SharedPreferences doesn't save value

I have this code:
public class Register extends Activity {
private LinearLayout layout;
private TextView debug;
public static final String USER_CONFIG = "UserConfigs";
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
SharedPreferences settings = getSharedPreferences(USER_CONFIG, MODE_PRIVATE);
boolean registered = settings.getBoolean("registered", false);
layout = (LinearLayout) findViewById(R.id.layoutRegister);
if (!registered) {
debug = new TextView(this);
debug.setText("You have to register");
layout.addView (debug);
//TO DO user registration
settings.edit().putBoolean("registered", true);
settings.edit().commit();
} else {
debug = new TextView(this);
debug.setText("You have already registered");
layout.addView (debug);
//TO DO skip to next screen
}
}
}
But I'm always getting registered as "false" when I restart my app. I have tried to commit it on the onStop() as well and got the same result. I have seen other topics with this problem here but none of them had the same problem as I do.
Any ideas?
You can't do this:
settings.edit().putBoolean("registered", true);
settings.edit().commit();
You need to get the editor object, then make the changes:
Editor editor = settings.edit();
editor.putBoolean(...);
editor.commit();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
Editor edit = prefs.edit();
edit.putBoolean("registered", true);
edit.commit();
use this
The other answers are also correct.
You can also use this
settings.edit().putBoolean("registered", true).commit();

save variables after quitting application?

I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game)
How can I do this?
EDIT: Here my code:
TextView test1;
String punkte = "15";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences save = getSharedPreferences(punkte, 0);
save.edit().putString("score", punkte);
SharedPreferences load = getSharedPreferences(punkte, 0);
String points = load.getString("score", "0");
test1 = (TextView) findViewById(R.id.test1);
test1.setText(points);
}
You should be using SharedPrefences. They are quite simple to use and will store the variables in the application data. As long as the user never hits "Clear Data" in the settings for your application, they will always be there.
Here is a code sample.
To access variables:
SharedPreferences mPrefs = getSharedPreferences("label", 0);
String mString = mPrefs.getString("tag", "default_value_if_variable_not_found");
To edit the variables and commit (store) them:
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("tag", value_of_variable).commit();
Make sure both "tag" fields match!
Use SharedPreference, this is a better option.
To see this tutorial.
sample code:
save:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString("statepara1", ts);
editor.commit();
get:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
String ret = settings.getString("statepara1", "0");

Categories

Resources