Upon reinstalling my app the code within my if statement is being accessed despite my SharedPreferences entry not yet having been created. I'm using an emulator with eclipse, does the data need to be cleared some other way than reinstalling? Thanks
prefs = getSharedPreferences("appData", 0);
Gson gson = new Gson();
String gsonStr = prefs.getString("playerString", null);
if(gsonStr != null)
{
//This code is being accessed on the apps first onCreate() call prior to being reinstalled
Player[] tempArray = gson.fromJson(gsonStr, Player[].class);
Log.d("First Player", "" + tempArray[0]);
}
protected void onPause()
{
super.onPause();
if(savedPlayers != null)
{
Gson gson = new Gson();
String gsonStr = gson.toJson(savedPlayers.toArray());
prefs = getSharedPreferences("appData", 0);
SharedPreferences.Editor editor = prefs.edit();
//editor().clear();
Log.d("GSONString",gson.toString());
editor.putString("playerString", gsonStr);
editor.putInt("ArraySize", savedPlayers.size());
editor.commit();
}
}
Most likely the app is simply being reinstalled. In order for the data to be cleared, the app actually has to be uninstalled first. Reinstalling won't actually clear the data. The emulator actually allows for a runtime option that will wipe all user data when you run the emulator, but I don't believe it runs each time your run the app. You can set this option in the Run Configurations for the app if you are using eclipse.
To do it from inside the emulator, go to settings->applications->manage applications->your app->clear data
A shared preference and sqlite db doesnt get removed on a reinstall. To delete them, go to Settings-->Appications-->Manage Applications-->Click on you application-->Click on "Clear Data" on emulator. this will clear the data stored.
Related
I have a Native Android App in the Store. This App has its Settings stored in the SharedPreferences. Now I am working on an Update for the App. The Update is a Xamarin Cross-Platform App. App Name, Package Name, and those things are the same as in the Native App. But I can't get the values from SharedPreferences now. Did I make something wrong? I guess it's because of a different Application Context. But I don't know why.
Here is how the Native App is loading the Values:
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final Set<String> keySet = prefs.getAll().keySet();
for (final String key : keySet) {
if (key.startsWith(DatabaseSetting.DATABASE_SETTING_KEY_PREFIX)) {
//Do stuff
}
}
After updating the App I can not see any keys in the prefs.
C# Xamarin Code to also load these prefs:
ISharedPreferences sharedPrefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
foreach (string key in sharedPrefs.All.Keys)
{
if(key.StartsWith(DATABASE_SETTING_KEY_PREFIX))
}
The App was updated without uninstalling the old one. Just deployed the new one.
Is it giving you a nullpoint?
Are you storing app context (Android.App.Application.Context) or class context(Context)?
Are there any other exceptions thrown that you possibly aren't catching?
I know there must be douzens of answers to this question out there, but either i cant't find them or I don't understand them.
The Question:
How do I get my app to exactly start as it was left?
F.e. dynamicly added checkBoxes shouldn't dissapear!
There is no "out of the box" way of doing it. You could save the current state of your Activity in some way (More on persistence)
Then you need to be able to rebuild the desired state of the persisted state in your Activity lifecycle
You could save and load with the shared preferences for example:
public void saveState(YourState state) {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
sharedPreferences.edit()
.putString("CustomAtt", state.getCustomAtt())
}
public YourState loadState() {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
String customAtt = sharedPreferences.getString("CustomAtt", "DefaultValue")
return new YoutState(customAtt)
}
And use it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
YourState state = loadState();
// Rebuild your activity based on state
someView.setText(state.getCustomAtt())
}
You can store such values in SharedPreferences.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
It is using key-value approach for saving. So you can save some values and read it from SharedPreferences whenever you want to.
This is the best approach for small data, that can be used on the app launch. So you can quit your app and the data is still present - so can be read on the next app launch.
Or save the condition of your program to a text file, so that the program can "translate" it back into conditions before it stops, or what I do not recommend, it saves every object created with ObjectOutputStream.
I use Shared Preferences to fetch and store a variable, I then fetch that variable across a different class. After I restart the app, the initial variable stored is to be updated by the new one. What I can see is that on quitting the application, I should set my shared preference to be cleared and then again fetch the fetch value.
However, the problem is that even on restart, the shared preference still store the older value and do not update themselves.
Here is the code where I initially save the value
protected void onLoginSuccess(String cookieString, String userName) {
// set cookie and initialize data center.
mCookieString = cookieString;
SharedPreferences settings =getSharedPreferences("cookie",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("cookie", cookieString);
editor.commit();
//editor.apply();
mDataCenter = new LsApiDataCenter(this, userName);
mCachedUserData.clear();
System.out.println("shhhhhhhhhhhh iis original : "+cookieString);
mSendersObservers.clear();
mMessageObservers.clear();
mNotificationObservers.clear();
Later, Upon exit I want the shared preference to be cleared and this is how I do it
protected void onLogoutSuccess() {
// clear cookie and data center.
SharedPreferences settings =getSharedPreferences("cookie",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.clear().commit();
mCookieString = null;
mDataCenter = null;
mCachedUserData.clear();
mSendersObservers.clear();
mMessageObservers.clear();
mNotificationObservers.clear();
Finally, this is how I fetch them in a completely different class
SharedPreferences settings = mMainActivity.getSharedPreferences("cookie", Context.MODE_PRIVATE);
count = settings.getString("cookie","");
The problem is that the value which I get upon fetching is the old value and not the latest value since i am fetching a value provided by a server via api used when the user logs in. However, I get the old value and the latest value is not fetched.
Thanks
If you want to clear the value of cookie variable you can do like this
SharedPreferences settings =getSharedPreferences("cookie",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("cookie", null);
editor.commit();
I am working on a small project that requires a details screen where the user inputs his details and they are permanently stored. The user must have the option to change the details as well if he needs to do so. I looked into the saved preferences library however it does not seem to offer such functionality.
To give a visual idea of what is required, something like this screen should be fine:
http://www.google.com.mt/imgres?start=97&num=10&hl=en&tbo=d&biw=1366&bih=643&tbm=isch&tbnid=aQSZz782gIfOeM:&imgrefurl=http://andrejusb.blogspot.com/2011/10/iphone-web-application-development-with.html&docid=YpPF3-T8zLGOAM&imgurl=http://2.bp.blogspot.com/-YRISJXXajD0/Tq2KTpcqWiI/AAAAAAAAFiE/-aJen8IuVRM/s1600/7.png&w=365&h=712&ei=rbX6ULTDCOfV4gTroIDoCg&zoom=1&iact=hc&vpx=834&vpy=218&dur=2075&hovh=314&hovw=161&tx=80&ty=216&sig=108811856681773622351&page=4&tbnh=155&tbnw=79&ndsp=35&ved=1t:429,r:4,s:100,i:16
Any help is much appreciated. Thanks in advance
You could easily use Shared Preferences to store user's details. Everytime the Preference screen is opened the stored data can then be extracted from the Shared Preferences and presented to the user for edit. ONce the edit is done the new data can be updated back in the the Shared Preferences.
Also look at this thread to see how this can be done.
Using SharedPreferences would be perfect for this kind of small amount of data which you want to store persistently.
// 'this' is simply your Application Context, so you can access this nearly anywhere
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To obtain from the preferences:
// You can equally use KEY_LAST_NAME to get the last name, etc. They are just key/value pairs
// Note that the 2nd arg is simply the default value if there is no key/value mapping
String firstName = prefs.getString(KEY_FIRST_NAME_CONSTANT, "");
Or to save:
Editor editor = prefs.edit();
// firstName being the text they entered in the EditText
editor.putString(KEY_FIRST_NAME_CONSTANT, firstName);
editor.commit();
You can achieve such functionality using SharedPreferences Class in android.
public void onCreate(Bundle object){
super.onCreate(object);
// Initialize UI and link xml data to java view objects
......
SharedPreferences myPref = getPreferences(MODE_PRIVATE);
nameView.setText(myPref.getString("USER_NAME", null));
passView.setText(myPref.getString("PASSWORD", null));
}
public void onStop(){
super.onStop();
if (isFinishing()) {
getPreferences(MODE_PRIVATE).edit()
.putString("USER_NAME", nameView.getText().toString())
.putString("PASSWORD", passView.getText().toString())
.commit()
}
}
I am trying to detect if my app has been run before, by using this code:
(This is in my default Android activity)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Log.w("activity", "first time");
setContentView(R.layout.activity_clean_weather);
} else {
Log.w("activity", "second time");
setContentView(R.layout.activity_clean_weather);
}
}
When I first run the app it says first time, when I run it a second time, first time, and a third, first time....
I am using an actual Android device and I am not using the run button each time. I run the app once with the Eclipse run button, then I close the app and press on its icon on my phone.
Is there something wrong with my code?
savedInstanceState is more for switching between states, like pausing/resuming, that kind of thing. It must always be created by you, also.
What you want in this case is SharedPreferences.
Something like this:
public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't change this after it's saved something
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if (firstRun) {
Log.w("activity", "first time");
setContentView(R.layout.activity_clean_weather);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.commit(); // Save all changed settings
} else {
Log.w("activity", "second time");
setContentView(R.layout.activity_clean_weather);
}
}
I basically took this code directly from the documentation for Storage Options and applied it to your situation. It's a good concept to learn early.
You may use a self-defined shared preference to archive your goal.
The fact is that savedInstanceState holds persistent data across activities. As such if you restart the app, savedInstanceState will be null across runs. You should either use a Preference or some data base entry to keep track of your first run. I myself use a SharedPreference for this purpose.
savedInstanceState will be null if the app is not already loaded in memory. If you want to detect whether the app has run for the very first time, you have to apply different technique, such as using sharedPrefs / DB to store a property for the first run.
i.e. Check sharedPrefs for property "firstRun"
if exists, then it is not a first run
else it is the first run
set the firstRun property to true