I want to create a game that counts the clicks made in 60 seconds and saves the record. I would like this record to be saved on the device even after the app is closed. Is there some kind of variable that allows me to do this?
Android's Shared Preferences seem to be the most relevant option for you.
Refer to the official documentation for an in depth look:
https://developer.android.com/training/data-storage/shared-preferences
These code samples should help you as well:
To save a value into the Shared Preferences:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key); //set a default/backup option
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
Make sure to keep the key identical between placing values into the preferences and retrieving.
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
SharedPreferences is probably the place to start with this. You can view Android documentation related to it here along with code examples: Save key-value data
There are some other options for saving data in an Android app on the left pane of that page, but SharedPreferences is probably the most applicable based on your described use case.
Related
I try to develop some fitness application which will use Google Fit.
And i have one question. Assume that user make some sport activity a few days in a week. And want to show him his best result. The only way I know I can do this - is load all data from user history and then select the set with maximum value.
And its obvious that I dont like that method because of the fact that I should load all the history. (And the user can have history for a few years).
Another way is to store data in local database (so i dont need to load all history every time the user want to see his best result) and synch it with google fit data, but I think its too dificult.
Do we have some other options for that kind of tasks?
Use sharedpreferences to save the value,
To set value
SharedPreferences prefs = this.getSharedPreferences("myhighestscore", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
To get value
SharedPreferences prefs = this.getSharedPreferences("myhighestscore", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0);
here is a link.
Using Shared Preferences
I am working with Android Studio 2.2.3 in order to watch data received from a bluetooth module in my smartphone's screen. I can see these values in my activity but as I am receiving values each 10 seconds (for example) I would like to save all this data in an array, database or anyplace. Once it was saved I would like to build a graphic using this saved data.
Here I have a picture of what I receive:
enter image description here
So now I would like to save those values (53,54,55...) and I don't know how. Is there any way like making an ArrayList or some function to save it? I read about "SharedPreferences" but I think it is not designed for what I am looking for.
Thank you very much!
P.D: I hope I explained okay and sorry for my english.
Shared Preferences could be, it allow to use Sets. You could convert your List into a HashSet or something similar and store it like that. When your read it back, convert it into an ArrayList.
//Retrieve the values
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Set<String> set = prefs .getStringSet("key", null);
yourListOfStrings.addAll(set);
//Set the values
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Set<String> set = new HashSet<String>();
set.addAll(yourListOfStrings);
prefs.putStringSet("key", set);
prefs.commit();
Regards,
I'd like my app to allow a single user to create a profile that is accessed every time they run the app. The user's profile contains a String entry and five int entries. I've thought about using an SQLite database to store the info between sessions, but it seems like overkill since I'd only need one row in a single table to store the data. However, I'm not sure if it's possible to use SharedPreferences on a String type of data.
Can anyone provide some insight into this issue please? Thank you!
Yes you can use SharedPreferences.
To write
Editor editor = getSharedPreferences("file_name", MODE_PRIVATE).edit();
editor.clear();
editor.putString("pref_name", myStringValue);
editor.commit();
To read back
SharedPreferences preferences = getSharedPreferences("file_name", MODE_PRIVATE);
String myStringValue = preferences.getString("pref_name", "default_value");
Regards.
Okay, I have come across many tutorials on creating and writing/reading a file. What I want my Android app is to create a small text file where it will read and write some settings so my user information can be saved. The problem is every tutorial I have come across uses the SDcard (which allows the user and any other app to read) or use MODE_WORLD_READABLE which makes any app read off of it.
I was wondering how I can create and read/write my file but private or atleast keep it on the internal storage of the phone.
Here's an easy example. To read a preference do this:
SharedPreferences preferences = getSharedPreferences("YourAppName", MODE_PRIVATE);
String thisString = preferences.getString("KeyForThisString", "default");
You can getInt, getLong, etc.
To store the preferences, use these lines:
SharedPreferences preferences = getSharedPreferences("YourAppName",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("KeyForThisString", thisString);
editor.commit();
As before, you can putInt, putLong, etc.
The available methods for this API are here: http://developer.android.com/reference/android/content/SharedPreferences.html
dont know how to use it much and from what im seeing at least, its not much of a difference unless im wrong.
I still recommend to use SharedPreferences technique. It's explicitly easy and save a lot of time.
You can use it to save any primitive data: booleans, floats, ints, longs, and strings.
For example, you can do that each time when user invokes any changes to your Application because it's high performance technique. By this way even on crash all edited info will be stored.
Suppose you have an Activity.
Use this method where data is your String that you wanted to save to file.
private void saveInfo(String data){
String key = "myKey";
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(key , data);
editor.commit();
}
Now, when you launch your application again onCreate method invoked and you can load your information back:
private void loadInfo(){
String key = "myKey";
SharedPreferences mPrefs = context.getSharedPreferences(LauncherUI.PREFS_NAME, 0);
String yourData = mPrefs.getString(key, ""); // "" means if no data found, replace it with empty string
}
Here is a link to 5 types to store data: Storage Options
On my app I've got a Database which i have to fill one time with some entries. I have packed this step in my splashscreen. Now I got the problem every time i open up my application it puts again all entries to my database.
I'm looking for a way to let this happen only on the really first time the app gets opend. But i don't find out, how i can realize this.
I'm happy over every input and Idea!
Have a nice day
safari
Notes
I had an idea to realize that. I make a boolean in my SplashScreen, which takes a look at the database table if there is nothin, it inputs all the entries and makes a mark in a table that its filled like yes.
Afterwards if i open the app again it takes a look at the database if theres a yes or what ever i definied, it doesn't put again all entries in my database.
Sorry for that crappy definition of what my idea is, my english isnt the best.
I'm searching for an easier way than this.
why not have a startup activity that checks if the app is launched for the first time ( and stores the value in the app preferences ) and either forwards to the database setup activity or to the main activity....
Here's a sample on how to read and write to the preferences:
Define preference key:
public static final String KEY_APP_IS_INITIALIZED = "APP_INITIALIZED";
read boolean value from preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
boolean appIsInitialized = prefs.getBoolean(KEY_APP_IS_INITIALIZED, false);
store boolean value to preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
Editor editor = prefs.edit();
editor.putBoolean(KEY_APP_IS_INITIALIZED, true);
editor.commit();
Launching the activities:
Intent intent = new Intent(startup_activity,
db_initialized ?
MainActivity.class :
DbInitActivity.class);
startup_activity.startActivity(intent);
You could use SharedPreferences to store a boolean value which indicates if the database is already filled.
You can store the data using this code:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
and then when you start the application you just read your value using:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
pref.getBoolean(value, false);
// Check if DB is set up on start
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
String DbSetUp = settings.getString("dbsetup", "no");
// DbSetUp is "no" or "yes"
// Set that DB is set up
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("dbsetup", "yes");
editor.commit();
Not an optimal solution, but you could check for one of your entries, if they don't exist, add them to your DB, otherwise ignore them.
Try this....
Have one bool value in shared preferences.
Check that variable is set or not on each start of the application.
if not set then set it and perform db operation.
if set don't do db operation just go to next steps.
I've got an idea, reading other answers.
Use a version for the database to write in the sharedpreference, so next time you'll need to update the database, just delete the old one and refill the new one with you data.
public void populateResDB(int version){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int resDbVersion = prefs.getInt("ResDBVersion", 1);
if(resDbVersion<version){
//Populate database here
//Delete table/db
//Populate the table/database with new or updated data
//Update ResDBVersion for the next time
Editor editor = prefs.edit();
editor.putInt("ResDBVersion", version);
editor.commit();
}else{
//installed db has the same version as the one we want to install
//so, do nothing.
}
}
I'm trying it now, not yet tested.
In the onCreate of the splash activity use:
populateResDB(1); //1 is for the first time, increase it manually
You can use method onCreate in your database helper - it's used only, when new database is created, so I think that is what you're looking for.