app is crashing after quickly changes preferences with commit( - android

I need to check the user input in the preferences if they want to save a new value. I believe the code is correct... because if I'm change the values slowly there's no problem at all. If I change too quick the app is crashing.
i'm using commit() for editing the preferences. Is this a too slow methode?
What I'm trying?: If a user gave an empty string, I give an alert dialog and intern I change the pref back to the old value. Here is the code:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
//save settings
static String SMStext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
//-- First get SMStext and save in Strings
SMStext = sp.getString("SMSText", "0");
//SharedPreferences.Editor prefEditor = sp.edit();
sp.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
String smstriggerworderror = "String cannot be empty";
if (key.equals("SMSText")) {
if sp.getString("SMSText", "0").equals(""){
SharedPreferences.Editor prefEditor = sp.edit();
prefEditor.putString("SMSText", SMStext);
prefEditor.commit();
//write current value back to value and refresh interface
SMStext = sp.getString("SMSText", "0");
//Show alert dialog
showdialog(smstriggerworderror);
//finish();
}
//write current value back to value
SMStext = sp.getString("SMSText", "0");
}
private void showdialog(String message) {
//create alertbox
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(message);
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// Click listener on the neutral button or alert box
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
// show the alert box
alertbox.show();
}

Inside of onSharedPreferenceChanged your doing a prefEditor.commit(); this will then call the onSharedPreferenceChanged listener, which wil then call commit() over and over until............... StackOverFlow error.
Fix:
Don't change your SharedPreferences inside of the OnSharedPreferencesChanged listener.

Related

Android - Update TextView on dialog dimiss listener

I show a dialog where the user can enter a String value in an edittext and I want to display this value in an textview in the main layout after the dialog is dismissed. When the user clicks on the button "Ok" of the dialog, the textview is well refreshed, but I tried to do the same from the dismiss listener on the dialog it isn't, but I know the rest of the code is run. I tried to make it run on the mainthread but it didn't solve the problem. Here is the code, thanks for your help.
final Dialog dialogStatus = new Dialog(Activity.this);
dialogStatus.setContentView(R.layout.dialog_layout);
Button Bok = (Button) dialogStatus.findViewById(R.id.bt_dialog_ok);
final EditText ETname = (EditText) dialogStatus.findViewById(R.id.et_dialog);
Bok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
update(String.valueOf(ETname.getText()));
dialogStatus.dismiss();
}
});
dialogStatus.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
update(String.valueOf(ETname.getText()));
}
});
}
});
dialogStatus.show();
}
public void update(String etValue){
final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
settings.putString(STRING_VALUE, etValue);
TextView.setText(sharedPrefUnitScore.getString(STRING_VALUE, etValue, ""));
settings.commit();
}
public void update(String etValue){
final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
settings.putString(STRING_VALUE, etValue);
settings.commit();
TextView.setText(etValue);
}
Because you were trying to get the value from shared preference before committing it.
If you won't commit it then it won't save.

clear the value of sharedpreferences

i am kind of new to android programming , i am designing a program that has login page and main page.When i sign in for the first time with a username and password, i created a sharedpreferences to remember that username and whenever i enter program , it skips login page and redirects me to main page.What i want to do is, when i press logout button in login page ,i want sharedpreferences forget the value of username in my database(it wont delete it from database) and force me to login me again with the same or different username and password , and i dont want to be redirected to main page when i enter application.I found something like SharedPreferences.Editor.remove() , SharedPreferences.Editor.clear(),commit() ,etc.. But code didnt work.Can you help?
public static class SaveSharedPreference {
static final String PREF_USER_NAME = "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx) {
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Button btnSignIn, btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uye_kayit_giris);
if (SaveSharedPreference.getUserName(UyeKayitGirisActivity.this).length() == 0) {
Intent i = new Intent(UyeKayitGirisActivity.this, MainActivity.class);
startActivity(i);
// finish();
}
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Refference Of Buttons
btnSignIn = (Button) findViewById(R.id.buttonSignIN);
btnSignUp = (Button) findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The Activity
Intent intentSignUP = new Intent(getApplicationContext(), SignUPActivity.class);
startActivity(intentSignUP);
}
});
Button btn_exit;
// super.onCreate(savedInstanceState);
// setContentView(R.layout.main1);
btn_exit = (Button) findViewById(R.id.buttonLogOUT);
btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WHAT SHOULD I WRITE IN HERE?????????????
Toast.makeText(UyeKayitGirisActivity.this, "ÜYE GİRİŞİ TEKRAR ZORUNLU HALE GETİRİLDİ!!!", Toast.LENGTH_LONG).show();
}
});
}
Try like this
SharedPreferences pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
Editor editor = pref.edit();
editor.clear();
editor.commit();
Here is the Method
private void removePreference(Context context, String prefsName, String key) {
SharedPreferences preferences = context.getSharedPreferences(prefsName, Activity.MODE_PRIVATE);
android.content.SharedPreferences.Editor editor = preferences.edit();
editor.remove(key);
editor.apply();
}
You can call it like:
public void removeUser() {
removePreference(context, FILENAME, KEY_USER);
}
Since you have mentioned that you do NOT want to delete the value of login from shared preference but only ask for login page each time, I believe you are looking for something where you want to clear application cache programatically.
Please check, Clear Cache in Android Application programmatically and Clear Application's Data Programmatically
It is also worth reading this wonderful answer - Don't delete database or shared Preference on clear app
To remove them all SharedPreferences.Editor.clear() followed by a commit()

how can i use share preference in counter in android?

Excuse me because 3 of my simple question, but I need your help. I want to have a counter (with using shared preference) in my app like this:
At the first, there are 2 buttons, START and RESET. If RESET is
clicked, the counter starts from 0.
Also if START is clicked, the counter starts from shared preference data.
Start counting
At last time, I want to save counter in share preference. (but I don't know its better to save it in BACK btn or CLICK btn)
My problem is in share preference part. Please help me how can I do this? Thanks a lot!
Edit: this is my code
public class CountActivity extends Activity {
private Button click;
private int count,savedCount;
private String count_text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counting);
click= (Button) findViewById(R.id.vow_counting);
final Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf");
final SharedPreferences sharedPreferences=getSharedPreferences("counters", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor=sharedPreferences.edit();
AlertDialog.Builder fBuilder=new AlertDialog.Builder(VowCountActivity.this);
fBuilder.setMessage("please choose");
fBuilder.setCancelable(false);
fBuilder.setPositiveButton("start from beging", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter", 0);
click.setText("0");
click.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf"));
dialogInterface.cancel();
}
});
fBuilder.setNegativeButton("countinue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter",savedCount);
editor.putInt("counter",savedCount).commit();
dialogInterface.cancel();
}
});
fBuilder.show();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count++;
count_text=Integer.toString(count);
click.setText(count_text);
click.setTypeface(typeface);
savedCount = sharedPreferences.getInt("savedCounter", count);
vibrate(500);
}
});
}
// vibrate
public void vibrate(int duration) {
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
To get value on start button you can define this function and have value for shared preferences
public static int getIntPreferences(String key) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, 0);
return settings.getInt(key, 0);
}
Now to reset your shared preferences value you can use the following function
public static void updatePreferences(String key, int value) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
editor.commit();
}
Use
SharedPreferences preferences = getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
edit.putString("yourPreferenceName", yourPreferenceObject);
edit.commit();
for saving preference
and
SharedPreferences preferences = this.getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
String string = preferences.getString("yourPreferenceName", "defaultReturn");
for receiving your sharedPreferences
.get and .put with return type
Try this:
SharedPreferences preferences = getSharedPreferences("counterStat", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int counter = preferences.getInt("counter", 0);
// counter = counter + 1; start counting
edit.putInt("counter", counter).commit();
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putInt("counter", 0).commit();
}
});
Dialog back:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
Dialog cancel:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
edit.putInt("counter", 0).commit();
Then you can use: int savedCounter = preferences.getInt("savedCounter", 0); anywhere
Here is how to add an entry to SharedPrefs, and save to disk.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", "Adam");
editor.commit();
Here is how to read a saved value from SharedPrefs.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
String name = settings.getString("name", null);

Remember click in Android

I have created an activity that should be displayed only once. In this Activity, I added a button, and click its close and will not reopen anymore when the application is started again. I thought of using SharedPreferences, but I do not get the desired result.
I memorize a data in Shared:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString( "entrato", "entra" );
edit.commit();
this.finish();
break;
}
}
then, in OnCreate() of the previous activity call the Shared and if the data is present do not open the activity:
//remember click
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
String valore = userDetails.getString("entrato", "");
if (valore.equals("entra")){
return;
}else{
Intent intent = null;
intent = new Intent(this, Benvenuto.class);
startActivity(intent);
create share preference class like this:
public class MyPreference {
private static final String APP_SHARED_PREFS = "myPref";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MyPreference(Context context) {
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean loadServices(String servicName) {
return appSharedPrefs.getBoolean(servicName, false);
}
public void saveServices(String servicName, boolean isActivated) {
prefsEditor.putBoolean(servicName, isActivated);
prefsEditor.commit();
}
}
then On Oncreate activity check if service exist so wont show and exit.
public static MyPreference myPref = new MyPreference(this);
if(myPref.loadService("this is not first time")){
thisActivity.finish();
}else {
// so it's first time and you can do what ever you want to do
}
and go on you click events and save service like this.
public static MyPreference myPref = new MyPreference(this);
myPref.saveService("this is not first time");
Try this code instead
// save string
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
// retrieve String
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString(key, "");
return value;
}
I have Four activities
Splash
Have 2 Buttons And 1 CheckBox ( Remember Me)
3 & 4. Another Activity
If I check the remember me option using checkbox, then I have to remember the button I have clicked and then start the 3rd or 4th activity directly whenever next start.

android getsharedPreferences not sure how to show hide other activities

I decided to use sharedPreferences so I could store the value of a togglebutton on my activity Preferences. On my main activity I want to hide a twitter button when the user clicks the twitter button in the Preferences activity.
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
There is no need to transfer Preferences through activities using intent.
You can access your "shared"Preferences from any activity.
You just put the button status with a string key inside:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
And in another activity you retrieve these preferences using string key ("twitterButtonStatus"):
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
See: http://developer.android.com/guide/topics/data/data-storage.html
Edit:
Youre saving SharedPrefs now, to get them back and set your Button Gone do something like this:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);

Categories

Resources