I need to have some information saved, what I have used in the past is sharedpreferences...
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Data", (Data));
editor.commit();
So I would do something like this to save the Data, however for this project I am using the public class Tab3 extends View implements OnTouchListener type of class and Im not sure if thats why this isnt working but its not I cant use the Shared Prefences onTouch I get an error on getSharedPreferences saying "The method getSharedPreferences(String, int) is undefined for the type Tab3" what do I need to do in order to save this data in some way so I can use it later on in my app?
You need a context to get access to shared preferences. The best way is to create MyApplication as a descendant of Application class, instantiate there the preferences and use them in the rest of your application as MyApplication.preferences:
public class MyApplication extends Application {
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
For example, if you need access to your preferences somewhere else, you may call this to read preferences:
String str = MyApplication.preferences.getString( KEY, DEFAULT );
Or you may call this to save something to the preferences:
MyApplication.preferences.edit().putString( KEY, VALUE ).commit();
(don't forget to call commit() after adding or changing preferences!)
I'd do what lenik says but don't make them static, lazy init them instead.
public class MyApplication extends Application {
public SharedPreferences preferences;
public SharedPreferences getSharedPrefs(){
if(preferences == null){
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
}
return preferences;
}
Then in your view:
MyApplication app = (MyApplication) getContext().getApplicationContext();
SharedPreferences settings = app.getSharedPrefs();
As eric says this Application class needs to be declared in your manifest:
<application android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
Reference:
getApplicationContext()
Android Global Vars
edit
(From your comment) the issue is that you aren't actually saving any data, this line doesn't make sense you aren't actually saving a variable:
editor.putString("Data", (Data));
Here is an example of the above in use:
MyApplication app = (MyApplication) getContext().getApplicationContext();
SharedPreferences settings = app.getSharedPrefs();
String str = settings.getString("YourKey", null);
And to save something to the preferences:
settings.edit().putString("YourKey", "valueToSave").commit();
A more specific example of using in a custom View would be:
public class MyView extends View {
SharedPreferences settings;
// Other constructors that you may use also need the init() method
public MyView(Context context){
super(context);
init();
}
private void init(){
MyApplication app = (MyApplication) getContext().getApplicationContext();
settings = app.getSharedPrefs();
}
private void someMethod(){ // or onTouch() etc
settings.edit().putString("YourKey", "valueToSave").commit(); //Save your data
}
private void someOtherMethod(){
String str = settings.getString("YourKey", null); //Retrieve your data
}
}
Related
I have one activity that sets various variables to either true or false, to be used as settings for other activities. I need to be able to call the state of these variables in my other activities but I can't figure out how. I know for strings I can use
getApplicationContext().getResources().getString(R.string.stringName);
but the same thing won't work for Boolean. Someone suggested using
activityName.variableName
but that won't work either. Any suggestions?
Instead of static variable or application variable use SharedPreference to achieve this which also persist on application close.
SettingsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("YOUR_KEY1", true);
editor.putBoolean("YOUR_KEY2", false);
editor.putBoolean("YOUR_KEY3", true);
editor.commit();
....
}
Then in other activity or fragment use getBoolean() to retrieve those data.
OthersActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//here false is the default value if key is missing
boolean value1 = sharedPreferences.getBoolean("YOUR_KEY1", false);
boolean value2 = sharedPreferences.getBoolean("YOUR_KEY2", false);
boolean value3 = sharedPreferences.getBoolean("YOUR_KEY3", false);
....
}
you can make global variables using many ways most common two
1- use of Application class
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
sure don't forgt to declare in manifest file
<application
android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
How to use?
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
2- by using Extra as a variable to be passed from activity to others with help of Intent
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
to read it in second activity use
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
for setting screens suggest to use SharedPreference you can learn how to use from here
I'm trying to create a simple Settings Activity with a single setting to change the language of the App.
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/locale">
<ListPreference
android:key="lang"
android:title="#string/language"
android:summary="#string/languageDesc"
android:entries="#array/languages"
android:entryValues="#array/languageValues"
android:defaultValue="#string/locale_en"/>
</PreferenceCategory>
public class TCPreferenceActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("lang")) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("lang", sharedPreferences.getString(key, "en_US"));
editor.commit();
settings();
}
}
public void settings() {
Intent intent = new Intent(this, TCPreferenceActivity.class);
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, TCPreferenceFragment.class.getName());
intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true);
startActivity(intent);
}
#Override
protected void attachBaseContext(Context newBase) {
SharedPreferences pref = newBase.getSharedPreferences("lang", MODE_PRIVATE);
String lang = pref.getString("lang", null);
Locale locale = new Locale(lang);
Context context = TCContextWrapper.wrap(newBase, locale);
super.attachBaseContext(newBase);
}
}
When I debug the activity, i see the updated value being received in the method onSharedPreferenceChanged.
However when i call the Intent to reload the activity, with the context wrapper in order to change the language, the value received from the call to newBase.getSharedPreferences("lang", MODE_PRIVATE) is still the original unchanged value.
When i click again on the preference in the interface, i see that the value hash changed.
Do I need to save the value?
Why doesn't it changed in the SharedPreferences class?
I'm trying to replicate what0s being done in the exemple here:
Android context.getResources.updateConfiguration() deprecated
Thanks in advance.
Try changing:
SharedPreferences pref = newBase.getSharedPreferences("lang", MODE_PRIVATE);
To:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TCPreferenceActivity.this);
For what ever reason, you are loading up private "lang" preferences, which im pretty sure you are not saving to. Use the default preferences instead which the activity should be by default using else where.
I would rather that you user apply() instead of commit().
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk.
Do this;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("lang", sharedPreferences.getString(key, "en_US"));
editor.apply();
I have an app, and I am trying to limit the number of button clicks to five, and then once the user has pressed this button five times it should disable.
However I am getting the above error and I am not sure why.
Any ideas ?
buttonadd.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
int clicks = 0;
clicks++;
if (clicks >= 5){
buttonadd.setEnabled(false);
}
SharedPreferences prefs = Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("clicks", clicks);
editor.apply();
}
});
You are wrongly trying to use the virtual method getSharedPreferences() in a static way, that's why its giving that compile-time error.
If that code is in an Activity, replace
Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
with
getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
If it is in a Fragment, use
getActivity().getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
EDIT:
use
if (clicks >= 5){
buttonadd.setEnabled(false);
buttonadd.setClickable(false);
buttonadd.setFocusable(false);
buttonadd.setFocusableInTouchMode(false);
}
and make clicks a class member, i.e. declare it as
private int clicks;
in the Activity.
EDIT 2:
I think I have understood the mistake you are making. In your code, replace
int clicks = 0;
with
SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int clicks = prefs.getInt("clicks", 0);
Try this. This should do it.
It means that you need an instance of a Context object to call the getSharedPreferences() method. If you're inside an Activity, try this:
this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE)
As the error message says getSharedPreferences() is a non-static method. When you do Context.getSharedPreferences(...) you are trying to call it directly from the class. Instead, you need to call it from a Context instance.
If your code is inside an Activity (as Activity extends Context) you can simply do:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
I develop android apps. I want my apps there guide when first installed. and the guide will disappear when I press the Start Application button. when the application back at the local launch the guide will not reappear. Thanks Before :D
Use shared preferences, see my answer to: Shared Preferences in View Page Indicator
Store a boolean when user press the button, if the boolean is set, you can skip the guide.
Will work for the lifetime of the app installation.
First create the PreferencesData class (kept the String methods from link and added boolean ones)
public class PreferencesData {
public static void saveString(Context context, String key, String value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putString(key, value).commit();
}
public static String getString(Context context, String key, String defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getString(key, defaultValue);
}
public static void saveBoolean(Context context, String key, Boolean value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putBoolean(key, value).commit();
}
public static Boolean getBoolean(Context context, String key, Boolean defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getBoolean(key, defaultValue);
}
}
Now, in your MainActivity (I assume you have a MainActivity and a GuideActivity here)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// will return the default value true if never been set before
if (PreferencesData.getBoolean(this, "showGuide", true) {
startActivity(new Intent(MainActivity.this, GuideActivity.class));
// you can do this from the last step of your guide instead
// to make sure that the guide is shown again if user
// quit before completing it
PreferencesData.saveBoolean(this, "showGuide", false);
finish();
} else {
// continue application
setContentView(R.id.yourlayout);
...
}
}
Set the walkthrough guide as the app's main activity, but before you instantiate any layout for that activity, check for the presence of a flag that says whether or not the guide has been dismissed once before. This flag needs to be somewhere that stays around when the app is closed - either in a properties file or a database. The first time a user dismisses the guide, set that flag to true; the next time you check it on startup, you'll be able to skip the layout for the walkthrough and send your app straight to its first "real" activity.
EDIT:
Beaten to it. Yes - use SharedPreferences unless you already have a database setup you'd rather use.
I cant seem to return a string to an activity in my android application from shared preferences.
In my UI class I have this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
format = preferences.getString("BallPref", "number");//not sure what needs to be in value
in Preferences.xml I have this:
<ListPreference
android:name="BallDisplayPreference"
android:key="BallPref"
android:summary="Show numbers or notes on balls"
android:title="Balls"
android:defaultValue="Fret"
android:entries="#array/listArray"
android:entryValues="#array/listValues" />
In the settings class I have this:
public class Settings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("BallPref", "Fret"); // value to store
editor.commit();
}
What I want to do is go into settings, and select my string option. then i want to find out what the user selected when the game starts. this doesn't seem to be working, any ideas on where I am going wrong?