I have been struggling with implementing a "clear preferences" option in the 3dot (overflow) menu... sample screen shot here:
Coding wise... I tried this but it does not do the job:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clearsp) {
SharedPreferences preferences = getSharedPreferences("dyna_cb_prf", 0);
preferences.edit().clear().commit();
Intent i = new Intent(Intent.ACTION_VIEW);
startActivity(i);
}
return super.onOptionsItemSelected(item);
Tips on how to modify this? Basically, I want it to clear ALL sharedprefs upon clicking that option (I may have multiple xml files to clear sometimes)
One solution would be to create a SharedPreferencesManager class, that keeps track of all the different SharedPreference xml files, and has a method to clear them all.
Simple example with two types of SharedPreferences:
public class SharedPreferencesManager {
public static SharedPreferences forDynaCpPrf(Context ctx) {
return ctx.getApplicationContext().getSharedPreferences("dyna_cb_prf", 0);
}
public static SharedPreferences forSomethingElse(Context ctx) {
return ctx.getApplicationContext().getSharedPreferences("something_else", 0);
}
public static void clearAllSharedPreferences(Context ctx) {
forDynaCpPrf(ctx).edit().clear().commit();
forSomethingElse(ctx).edit().clear().commit();
}
}
Then, if the user selects the menu item to Clear Preferences, just call the clearAllSharedPreferences() method:
if (id == R.id.clearsp) {
SharedPreferencesManager.clearAllSharedPreferences(this);
}
Note that instead of calling getSharedPreferences("dyna_cb_prf", 0) outside of the SharedPreferencesManager class, you would just call the forDynaCpPrf() method:
SharedPreferences preferences = SharedPreferencesManager.forDynaCpPrf(this);
Related
I have three button in my activity when I click any of two both will get disable but when I went back to my activity they won't restore the previous state.I have tried to achieve this using shared preference but Couldn't hold button state .Can anyone tell me about the mistake that I'm doing in shared preference.
Here I'm sharing my code with you.
on create method
spStateButton= getApplicationContext().getSharedPreferences("Button_State", 0);
spEditor = spStateButton.edit();
In Activity
public void setButtonState(boolean enabled) {
spEditor.putBoolean("btn_state", enabled);
spEditor.commit();
}
public boolean getButtonState(){
return spStateButton.getBoolean("btn_state", true);
}
button place in my activity
holder.btn_Fwd.setEnabled(getButtonState());
setButtonState(false);
holder.btn_Rec.setEnabled(getButtonState());
setButtonState(false);
You used method setButtonState(boolean enabled) for saving value to shared preference and you always call that method with parameter as false. So in shared preference the key "btn_state" having value always false.
So if you want to enable button for next time activity starts, call something like
setButtonState(true);
You can also use Singleton class to save a status value across app. Create class as below
public class SingleTon {
private static final SingleTon instance = new SingleTon();
private Boolean buttonState = true //initially visible
private SingleTon(){}
public static Boolean getButtonState(){
return buttonState;
}
public void setButtonState(Boolean buttonState){
return instance;
}
public SingleTon getInstance(){
return instance;
}
}
I have an OverviewActivity that contains a listview. When an item is selected, an intent is created to move to the DetailActivity and I pass an int with it.
This int is assigned to a private variable and is used to query the database.
DetailActivity code:
private int mIssueId;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_issue_detail);
mIssueId = getIntent().getIntExtra(IssueOverviewFragment.INTENT_ISSUE_ID, -1);
...
}
In the DetailActivity I can go to a GraphActivity. But when I press the upButton in the GraphActivity, the application crashes because the variable became -1 in the DetailActivity (and the database can thus not be queried properly).
The hierarchy is:
OverviewActivity -> DetailActivity -> GraphActivity
GraphActivity code:
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_graph );
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout: {
Utility.redirectToLogin(this);
break;
}
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
How do I retain the values of my mIssueId attribute in the DetailActivity?
The Intent intends to pass information between activities. When Activity1 pass control to Activity2 mostly related to the behavior of the activity.
If you have information you need to share across a complex hierarchy or to be available for your entire app, you can choice between Shared Preferences if you need persistence or use a Singleton class if the data only will be needed while the app is running.
This is a sample for a Singleton class keeping information to available to the entire app:
public class AppData {
private static AppData ourInstance = new AppData ();
public int score;
public static AppData getInstance () {
return ourInstance;
}
}
And how to access it:
AppData.getInstance().score = 100;
Hope it helps.
It looks like you are getting as a default value because there was an issue getting the intent in DetailActivity. You could try breaking up your request a little with
mIssueId = getIntent().getExtras().getInt();
But I think the issue is probably with how you are putting the int into the intent.
It should look something like
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra(IssueOverviewFragment.INTENT_ISSUE_ID, mIssueId);
startActivity(intent);
I made a class for handling important data changes such as App Purchase Status and other stuff .
For this goal I have created a class which does the setting and reading of the values. but the problem is whenever I call the appIsPurchased() method, the result is true while it hasen't been changed since app installation and its first initial launch.
This is my code:
/**
* Created by neemasa on 5/29/14.
* This class handles more crucial data values within app.
*/
public class AppCore {
private SharedPreferences settings;
private String keyPurchase = "app_purchased";
private Context context;
public AppCore(Context context){
this.context = context;
settings = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setAppInPurchasedMode(String status){
if (status.equals("successful")){
settings.edit().putBoolean(keyPurchase, true).commit();
}else if (status.equals("failed")){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
}
Question 1st: is there something wrong with my code? if there is then why appIsPurchased() always return true?
Question 2nd: do all values in the shared preferences are true by default?
Meanwhile when I use this class in my code the toast "Purchased!" runs even when app is running for the first time.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCore appCore = new AppCore(getApplicationContext());
if (appCore.appIsPurchased()){
Toast.makeText(getApplicationContext(),"Purchased!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"Not Purchased!",Toast.LENGTH_SHORT).show();
}
}
Actually there is a problem in your code!! thats why its always showing purchased!!
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
in this lines if the keyPurchased tag if not used , u are passing true value by default
so when u call
if (appCore.appIsPurchased()){
it always return a true value.. The solution is that make sure that the preference values are set before u call them.. hope this helps
Found It, the problem is that I was thinking
settings.getBoolean(keyPurchase,false)
returns the value of keyPurchased variable but the fact is it only returns the variable itself not its value so I fixed the problem by changing the method of my class to this:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase,false);
}
you are setting the default value to true, so either your sharedpreference does not contains an entry for key_purchased or setAppInPurchasedMode is never called or is called wit status successful. On the minor side, your
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
can be implemented like:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase, false);
}
about setAppInPurchasedMode, if I were in you I would change the way you compare status, this way:
public void setAppInPurchasedMode(String status){
if ("successful".equals(status)){
settings.edit().putBoolean(keyPurchase, true).commit();
} else if ("failed".equals(status)){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
the difference is that if status is null, the way you implemented will crash your application with NPE. With my implementation you'll get false, because "successful" instanceof null is always false, and instanceof is the first check for equals
For those still having a problem, remember to apply the changes to your preferences.
private SharedPreferences sharedPreferences ;
private SharedPreferences.Editor sharedPreferencesEditor;
sharedPreferencesEditor.putBoolean("myVariable", false);
sharedPreferencesEditor.apply();
In my android application i want to make a feedback dialog that will show the second time the application is started.
How can i do this ?
Can i do it by variables in a PreferenceActivity. If the a variable in the preference activity is edit by feks ++; will this be the result of the variable next time the app is started ?
Edit:
I dont get any of the suggested answers to work, can i create a text file on the ext or internal store the first time the app is started and check if the file exists ?
Use SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences mSharedPrefs;
private static final String PREF_LAUNCH_COUNTER = "launch_counter";
private int mLaunchCount = 0;
#Override
public void onCreate(Bundle savedState) {
mSharedPrefs = getPreferences(Context.MODE_PRIVATE);
if (savedState != null) {
mLaunchCount = savedState.getInt(PREF_LAUNCH_COUNTER, 1);
} else {
mLaunchCount = mSharedPrefs.getInt(PREF_LAUNCH_COUNTER, 1);
if(mLaunchCount > 1) {
//code to handle when the app was launched after the first time.
} else {
//code for when the app was launched for the first time..
}
mSharedPrefs.edit().putInt(PREF_LAUNCH_COUNTER, mLaunchCount++);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(PREF_LAUNCH_COUNTER, mLaunchCount);
}
}
No, variables do not persist through activity restarts, because the entire object is garbage collected and recreated.
You can use SharedPreferences to store data that must be persisted between application launches.
It's kinda of a barbarian solution, but it did not have Eclipse or and Android phone close to me.
You can do something like that I think :
protected boolean isSecondLaunchTime() {
SharedPreferences settings = getPreferences(MODE_PRIVATE);
int time = settings.getInt("launchTimes", 1);
if(time==1 || time>2) return false;
settings.edit().putString("launchTimes", ++time);
settings.edit().commit();
if(time==2) return true;
else return false;
}
Good luck !
I have a problem with SharedPrefences and initializations.
My application has a login where you insert an user, and for that user, you have a specific preferences... so, I need to save preferences according to the user to load it later.
I though that SharedPrefences would be the solution, and it really is I think, but I have a problem to initialize they: I have an Activity class called Options. It has static functions that returns the value of the options... but I have a problem, I call that functions before I have create that activity (intent), so I think that the functions are returning the last value that the last user has selected on the options...
How can I load the options before that calls?
I though to use first of all an Intent sending extra data with the user and in onCreate() of the Options, initialize they, but if I make an intent, then the Options will appear (xml will load).
Any help pls?
Try something like this.... adding methods for each variable you want to save.
public class PreferenceManager {
private static PreferenceManager self;
private SharedPreferences preferences = null;
private SharedPreferences.Editor editor = null;
private boolean isInitialised = false;
private static final String MY_PREFERENCE = "mypreferencekey";
private String myPreference = null;
public void initialise(Context context) {
if (!isInitialised) {
preferences = context.getSharedPreferences("MyPreferencePlace", Context.MODE_PRIVATE);
editor = preferences.edit();
loadPreferences();
isInitialised = true;
}
}
public static PreferenceManager getInstance() {
if (self == null) {
self = new PreferenceManager();
}
return self;
}
private PreferenceManager() {
}
public void setPreference(String newPreferenceValue) {
this.myPreference = newPreferenceValue;
savePreferences();
}
public String getPreference(){
return myPreference;
}
private void savePreferences() {
editor.putString(MY_PREFERENCE, myPreference);
editor.commit();
}
private void loadPreferences() {
myPreference = preferences.getString(MY_PREFERENCE, null);
}
}
All the SharedPreferences need is a context and it can be initialized. As your application always opens an Activity to start with, you always have a context to work with.
I would advise you to wrap the SharedPreferences in a Singleton class and just pass a context as parameter at the getInstance method. You should be able to access your shared preferences at all Activities this way.
I work on the dependency injector for android, and content of shared preferences is already injectable into annotated fields ( see: https://github.com/ko5tik/andject , PreferenceInjector). Patches and improvements are welcome. Saving of preferences comes soon