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();
}
Related
How to display an AlertDialog based on the number of execution of an activity(MainActivity). For example if MainActivity is opened for 5 times then i need to display an AlertDialog.
Saving data in Preference:
private static void saveCounter(Context context, int value) {
SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("count", value);
editor.commit();
}
Retrieve data from preference:
private static int getCounter(Context context) {
SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try {
return prefs.getInt("count", 0);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
These methods will make your work easy and you just have to pass the incremented value to saveCounter for saving the value and then for getting the value use getCounter
Dear archana,
Please save the varible/flag in SharedPreferences. Check varialble value (whether 5) then increment on every execution of activity until 5 and save to sharedprefrences and get it from there with every launch of activity.
In oncreate method of activity please update the variable with increment+1 and save it and check it in next launch
For more visit:
http://www.tutorialspoint.com/android/android_shared_preferences.htm
Thanks
Initialize your counter to 0 and increment it in onCreate() and onResume() methods of your activity. As soon as you increment these values, store these values in Shared Prefrences(as described in above answer). If you have trouble using Shared Preferences, try TinyDB, it is based on Shared Preferences and is much easier to handle.
I am creating my first android app and I don’t have enough knowledge in programming unlike other here. So please help me with this matter. I want to save player’s name and score. I’ve searched and read a lot about SharedPreference but was unable to understand it very well especially when I am already applying the codes on my activity. I have tried it twice and everytime I run it, it shows”Not Responding” message and closes. But when the codes for sharedpreference are not indicated there it works fine. So here’s how I want to do with these. On the first game, the very first score should be saved after the time is over (the user will be typing their name and click save). So when another user or player plays the game the Top Score should be indicated in the screen using a textview, below this Top Score textview is the Current Score textview. If the Current Score is greater than the Top Score then it should overwrite the score. If not then the Top Score should stay the same. How can I achieve this?
P.S. I have 3 different activities that needs this SharedPreferences but with the same functionalities. Thanks in advance. And please explain it more clearly (coz sometimes I can’t understand some words) thank you :)
This is the code i use, i put it in Oncreate
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", name);
editor.putInt("score", score);
editor.commit();
I think following link will surely help you out SharedPreferences Explained in detail
.
Try this
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value); //similar way you can push integer values
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sp.getString(key, null); //default value will be null in this case, if there is no such key
You can write a Utility class to reuse this methods wher you want. like below
public class PreferenceUtility {
public static void saveString(Activity activity, String key, String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public static String readString(Activity activity, String key, String defaultValue){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity.getApplicationContext());
return sp.getString(key, defaultValue);
}
}
static SharedPreferences sh_Pref;
public static String Preference_Name = "AppData";
public static String getPreference(String key, String Default,
Activity activity)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
return sh_Pref.getString(key, Default);
}
public static void setPreference(String key, String value, Activity activity)
{
if (value != null)
{
sh_Pref = activity.getSharedPreferences(Preference_Name, Context.MODE_PRIVATE);
Editor editor = sh_Pref.edit();
editor.putString(key, value);
editor.commit();
}
}
}
** Here a set and get value from SharedPreferences**
I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");
In one of my views the user makes a selection. I want to store that selection in a variable I can use across all views so it can be used for further database queries such as "bookId".
How can I make "bookId" a global variable that is set on one view and can be accessed across the other views when needed?
----- Edit: What I'm attempting to do based on comments and answers -----
On my main activity where the SharedPreference is stored I have this before the onCreate:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Integer bookId;
In my onCreate I've done this:
settings = getSharedPreferences(PREFS_NAME, 0);
bookId = settings.getInt("bookId", 0);
After the button press I'm storing a custom attribute and attempting to set bookId in the SharedPreference:
SharedPreferences.Editor editor = settings.edit();
editor.putInt("bookId",bookKey);
editor.commit();
In another view I'm attempting to get the bookId from the SharedPreference and, for testing purposes, I'm trying to set the stored value to a textView just to make sure it stored and carried over correctly.
Before the onCreate on the second view:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Inside the onCreate:
settings = getSharedPreferences(PREFS_NAME, 0);
Integer bookId = settings.getInt("bookId", (Integer) null);
tempBookTextView = (TextView) findViewById(R.id.tempBookTextView);
tempBookTextView.setText(bookId);
I have a two questions, how does this look so far? Any ideas why the app crashes when I use
Integer bookId = settings.getInt("bookId", (Integer) null);
Instead of using global variable to access variable value through out the app try using SharedPreferences.
sample activity:
public class Book extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
String mBookId = null;
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
mBookId = settings.getString("book_id", null);
// use book_id;
}
#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("book_id", mBookId);
// Commit the edits!
editor.commit();
}
}
Preferences are typically created private and can be accessed via all over the application components. Sharing data with other application with world readable or writable preference file is rarely used, as the external component would need to know the exact filename and location of the file.
To kill the spirit of encapsulation,
public class Globals {
public static int x;
public static int y;
}
and later
if (Globals.x == 0) { ... }
But please don't do exactly that, any class can contain static variables, find a class responsible for the value you want to store.
OTOH, android processes may be restarted when you don't expect it, in which case all the variables will be reset. So it's better to use shared preferences and if they don't work as expected (which I have seen in at least one release of Android), store the instance of shared preferences in a static variable.
You can use Shared Preferences
Saved at once !
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ProjectAct.this).edit();
editor.putInteger(StaticVariable.BOOKID, "1");
p.get("contract_no"));
editor.commit();
Then call from anywhere like that
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int book_id = prefs.getInteger(StaticVariable.BOOKID,null);
See more at How to use SharedPreferences in Android to store, fetch and edit values
I'm trying to write an activity that would be able to both write and read sharedpreferences data.
I initiate SharedPreferences at the beginning
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Then this function writes an int to SP and call another function.
public void SetHue(int i)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", i); // value to store
editor.commit();
ApplyHue();
}
this other function should read that int from SP...
public void ApplyHue()
{
int hueInt = preferences.getInt("storedInt", 0);
/// adjust background image hue according to hueInt.
}
I can't simply pass this int from one function to another, because I need other activities to be able to run ApplyHue() function, which should use hueInt from memory.
What do you think might be causing it to crash?
Thanks!
I think you wrote this line in the class before your onCreate method.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Decalare SharedPreferences preferences; in the class and then in onCreate
preferences = PreferenceManager.getDefaultSharedPreferences(this);
Hopefully your problem will be solved