I want to store my app data in a file so it could be accessed every time from the app - for example: money, user score, user current sprite...
I have never seen encryption in my life, and I wanted to know if there is an easy way to encrypt data and write it to the phone, and then decrypt it next time the app is open.
If there is no easy way, it would be great if someone could explain how the encryption/decryption works to me.
Use SharedPreferences.
I've used them, and you dont need to encrypt the data.
http://developer.android.com/guide/topics/data/data-storage.html#pref
EXAMPLE(from developer.android):
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
Related
I have one application that uses SharedPreferences to record the checkin or checkout state of the user.
If the checkin is pressed, it's button is grayed out the checkout becomes available, the opposite work as well.
However some users tells me that "sometimes" they will make another checkin on the next day and the checkout is still available.
Im supecting that they are forgetting to tap it, but i want to know if is there by any chance that this SharedPreferencces get cleared by itself?
this is the part of my code that i save the checkin state:
SharedPreferences preferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("statuscheckin", 1); //1 for checkin, 0 for checkout
editor.commit();
this is the part where i check it
if (getSharedPreferences("MyPreferences", Context.MODE_PRIVATE).getInt("statuscheckin", 0) == 1) {...}
Unless you clear the storage/cache, SharedPreferences won't get cleared by itself.
Make sure you are not clearing it by yourself for any condition happening.
If you are getting the default value only, it's possible that you are using it before the value gets committed.
Try this code,
Session Manager code:
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
public static final String KEY_CHECKIN= "checkin";
public void setCheckin(boolean login){
editor = sharedPreferences.edit();
editor.putBoolean(KEY_CHECKIN,checkin);
editor.apply();
}
public boolean getCheckin(){
return sharedPreferences.getBoolean(KEY_CHECKIN,false);
}
In your Java code:
SessionManager sessionmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionmanager = new SessionManager(this);
//Condition for checkin
if(user checkedIn){
sessionmanager.setCheckin(true);}
//Retrieving the value when user again opens the app:
if(sessionmanager.getCheckin()){}////proceed with your logic.
I have 27 characters that I want a player to unlock by beating scores, e.g. if his score is greater than 200 he unlocks character #1. I have a hard time trying to do that.
I have a class for characters that contains its number, the score required to unlock it, and a boolean to check if he is unlocked. But when it comes down to saving, I can't do that.
The main game loop is in file GameScreen. It has a value points counting the score.
When GameState changes to PlayerDead I want to check if any new character has been unlocked, and whether the high score has been beaten to save points.
Please help, I'm struggling with it for over a week and I can't find a good tutorial for SharedPrefs because all of them apply to GUI based activity that saves the name and surname you entered.
if you need sharedPrefs I can help you.
I can give some some example code.
or you can send your code and error if you get one, we update it.
but sharedPrefs is a good idea for that ? if user goes to application settings and clears data of your app, all data will be lost.
why dont you try create a sqlite databade, save it into assets directory and use it?
It's actually pretty simple, you use SharedPreferences to store key-value pairs. You can either call
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
From the GameScreen and then define a constant:
public static final String KEY_SCORE = "score";
To use as the key for the saving.
In order to actually save, you need an Editor:
SharedPreferences.Editor mEditor = mPrefs.edit();
//save data now, mPlayerScore is the score you keep track of
//if it's another type call putString(), etc
mEditor.putInt(KEY_SCORE, mPlayerScore);
//if that is the only thing you want for noe
//close and commit
mEditor.commit();
And in order to retrieve the saved score, during your onCreate() you can do:
public void getUserProgress() {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//no need for an editor when retrieving
mPlayerScore = mPrefs.getInt(KEY_SCORE, 0);
//second value passed was the default score
//if no score was found
}
In order to check for new character s being unlocked, you can call the following code after every game:
private void checkForUserUnlocks() {
if (mPlayerScore >= MyUnlockableCharacter.SCORE_NEEDED_TO_UNLOCK)
MyUnlockableCharacter.isUnlocked = true;
//and same for other unlockabld characters
}
There are other ways to access SharedPreferences, let me know if you need more info.
Use the below code to store and retrieve Score from SharedPreference.
public static void saveScore(Context context, int score){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("SCORE", value);
editor.commit();
}
public static int loadScore(Context context){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
int score = sharedPreferences.getInt("SCORE", 0);
return score;
}
Read Sample;
public int Read() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
int mCounter = mSharedPrefs.getInt("Counter", 0);
return mCounter;
}
Write Sample;
public void Write() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
mPrefsEditor.putInt("Counter", 15);
mPrefsEditor.commit();
}
When connected to the server i get the Cookies and store them in a List.
While making connections later i add these cookies to the DefaultHttpClient.
The problem is, when the Application is in background for sometime, all the class data is being lost including the DefaultHttpClient.
Hence i am losing the cookie.
Is there a way to keep the DefaultHttpClient alive forever?
or any better way to store and use cookies?
Thank You
Get it from the cookie, then save it in the shared prefferences when the app is killed (e.g. onStop method). Then reload it on onCreate(). Something similar to this:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String silent = settings.getString("cookie", null);
if(cookie == null) {
// first time, get cookie again and save it
} else {
// set cookie manually for HTTPClient
}
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("cookie", theCookie);
// Commit the edits!
editor.commit();
}
}
(I have omited the code for getting and setting the cookie, I assume that's not a problem)
i am creating login in my app. User type his info i send it to web service to check and get his ID. Now i need to save it somewhere in my app that i could check if he had login.
So where this info should be saved ? I know that every app have it's settings so there should be this info ? Maybe someone could give me more info what and how this is doing.
Thanks.
I found this post:
What is the most appropriate way to store user settings in Android application
I believe my question was duplicate. But it would be nice if you have something to share more.
First of all save user info like uname & password in SharedPreferences with this code.
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Username",txtUname.getText().toString());
editor.putString("Password",txtPWD.getText().toString());
editor.commit();
and then get SharedPreferences from below code
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
txtUname.setText(settings.getString("Username", "").toString());
txtPWD.setText(settings.getString("Password", "").toString());
Answer is Use Application Class or Shared Preferences
I assume you can easily search for the Example of Application Class, SharedPreferences and SQLite Database
So I am mentioning Where Do I Use Which Options
Application Class
When I got anything(var , array , list , objects) to store just only for the LifeTime of the Application..and As it got close (for Android Force Close) I use Application Class.
SharedPreferences
I use this when I got some short information like id,token,username,flags and I want to store that as long as the application rest in the Device..and need to use those information everytime I start the Application..
SQLite Database
When there is a bulk data in Record format (Row - Column) I used it to store in database so it becomes easy to store , retrive and manipulate.
You can use SharedPreferences for this.
Some codes from references (taken from documentation):
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
if user clear the application data from setting -> application manager -> your application -> clear data
then all data saved in shared preferences will get removed
My application has only one service class (not activity) in which I keep value of one variable that is being dynamically calculated through one method. Then i need to save that value for further comparing.
For example:
class MyClass extends Service{
static int number1;
private void Method(){
int number 2;
/// some calculations for number2 ///
if number2 != number1 { number1 = number2 }
}
I need to compare that variable (number1) to the some other variable (number2) that my application has calculated. This is working well, but when Android OS kills my service, and start that service on some intent (let say after phone reboot) the value of number1 is being lost and I can't use it for comparing.
So how to do it? I thought to write simple TXT file in which one i could keep value of number1 after killing the service,
is there any other way?
the quickest way is to save your variable's value in SharedPreferences and retrieve it for later use.
For example:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
this code is taken from android developer's page which is for Activity but you may adapt it in your service easily by changing it
You have to save the value to a file or a database as Android users usually monitor services and applications and can close the service
so
persist it in database so later when your service is started you can check the saved value.