After button click I need to wait till some information will be stored in SharedPreferences and then move on into the next activity. I try to use SharedPreferences.OnSharedPreferenceChangeListener() but it isn't work properly.
MapActivity
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition != null ) {
SharedPreferences preferences = PreferenceHelper.getPreferences(MapActivity.this);
SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i(TAG,"key "+key);
Intent i = new Intent(MapActivity.this, MainActivity.class);
i.putExtra("coordinates", currentPosition);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
}
};
preferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
PreferenceHelper.saveLocation(MapActivity.this,currentPosition);
}
}
});
PreferencesHelper
public class PreferenceHelper {
public static SharedPreferences appPreference;
public static SharedPreferences getPreferences(Context context){
return context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);
}
public static void saveLocation(Context context,LatLng location){
appPreference=context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appPreference.edit();
editor.putFloat(CURRENT_LOCATION_X, (float) location.latitude).apply();
editor.putFloat(CURRENT_LOCATION_Y, (float) location.longitude).apply();
editor.commit();
}
}
Commiting changes is something that happens in the main thread...You don't need a OnSharedPreferenceChangeListener. the change listener is useful when you want to be notified about changes in your shared preferences that were commited from other components of your application...not the one that commited the changes. Just do:
prefs.edit().putWhatever().commit();
startActivity(new Intent(....));
Related
I'm trying to get my app to look first if shared preferences is set. If not it must open a page where you type them in, and then hopefully save them which I will use later. It looks like it either finds some shared preferences or my code is wrong because the main activity opens (the else statement executes).
Here is my Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean check = sharedPreferences.getBoolean("Check",false);
if(check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
And here is the SharedPrefs:
public class SharedPrefs extends MainActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
I must be honest I'm not quite sure where I want Java to look for Shared preferences, "this makes the app run at least.
Inside the SharedPrefs{} class, declare the variable
public static boolean CHECK_VALUE = false;
In the same class inside onClick(View v) method after editor.commit();, set
CHECK_VALUE = true;
And in MainActivity{} class inside OnCreate() method
if(!SharedPrefs.CHECK_VALUE){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Actually you don't need a SharedPreference to check here. If you really do, then put
editor.putBoolean("check", true);
insideOnClick() method of SharedPrefs{} class and to get it from or to use it in MainActivity
SharedPreferences sharedPreferences = getSharedPreferences(SharedPrefs.MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Check = sharedPreferences.getBoolean("check", false);
if(!check){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
I have a Floating Action Button in my layout. Users can choose the position of this button, left or right. This can be selected in the preferences.
The code to do this works OK, but a change in the preference is not detected by the listener.
If the app is restarted, the Floating Action Button is displayed according to the new preference, so I know the process with this preference works, but unfortunately the listener seems to fail.
What do I have to do to get the listener firing when the preference has changed?
Listener in my MainActivity:
private final SharedPreferences.OnSharedPreferenceChangeListener
mPositionFabListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.e(TAG,"Are we getting here?");
// We do not get here when preference has changed. Why not??
// Code to update Floating Action Button to new position
}
};
I register the listener in the onResume() method of the MainActivity and unregister in the onPause().
#Override
protected void onResume() {
super.onResume();
PrefUtils.registerOnPrefChangeListener(mPositionFabListener);
}
#Override
protected void onPause() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onPause();
}
The registerOnPrefChangeListener method is declared in a seperate class:
public class PrefUtils {
public static boolean getBoolean(String key, boolean defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getBoolean(key, defValue);
}
public static void putBoolean(String key, boolean value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putBoolean(key, value);
editor.apply();
}
public static int getInt(String key, int defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getInt(key, defValue);
}
public static void putInt(String key, int value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putInt(key, value);
editor.apply();
}
public static void registerOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).registerOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
public static void unregisterOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).unregisterOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
}
UPDATE:
In the GeneralPrefsFragment class I put in this listener for testing purposes. This listener is working. So why does it not work in the MainActivity?
public class GeneralPrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Preference preference = findPreference(PrefUtils.POSITION_FLOATING_MENU_BUTTON);
Preference.OnPreferenceChangeListener mListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
PrefUtils.putBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, Boolean.TRUE.equals(newValue));
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit().commit(); // to be sure all prefs are written
Log.e(TAG, "The listener in " + TAG + " is listening");
// This listener is fired as soon as changes in the preference are made!
// Why is the same kind of listener not fired in the MainActivity?
return true;
}
};
preference.setOnPreferenceChangeListener(mListener);
}
}
SOLUTION:
I got a fix. I still do not know why the former setup didn't work, but I got it working, thanks to the code in this answer.
In the MainAcivity's onCreate() method I placed the following listener and this one gets triggered when the preferences have changed.
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener mPrefsFabListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (PrefUtils.POSITION_FLOATING_MENU_BUTTON.equals(key)) {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams paramsFab = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
if (PrefUtils.getBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, false)) {
paramsFab.gravity = Gravity.BOTTOM | Gravity.START;
} else {
paramsFab.gravity = Gravity.BOTTOM | Gravity.END;
}
}
}
};
prefs.registerOnSharedPreferenceChangeListener(mPrefsFabListener);
The OnSharedPreferenceChangeListener gets unregistered in the onPause() method of the MainAcitivity. That is a problem, because the MainActivity gets paused as soon as the General Preferences Activity is started in order to change the preferences. So, the listener is unregistered and therefore not listening right at the point where it is needed!
I removed the unregisterOnPrefChangeListener from the onPause() and put in the following code. This worked perfectly!
#Override
protected void onDestroy() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onDestroy();
}
I have a method to validate a EditTextPreference. My method is executed after the confirmation of data by implementing the onSharedPreferenceChanged class.
However, only occurs after you confirm the information. I would perform the check without closing the dialog box. And if ok then close or keep open for user to enter the data correctly.
If it's not possible, I would reopen the dialog box if the validation is false.
SettingsActivity.java
class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected static final String TAG = "SettingsActivity";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
SharedPreferences.Editor prefEditor = prefs.edit();
if(key.equals("pref_Url")){
String url = prefs.getString(key, "");
boolean response = (!new ConnectUtils().isConnected(this, url));
if(!response){
prefEditor.putString(key, Config.SERVER_URL_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(this,R.string.msgToast_server_url_invalid,Toast.LENGTH_SHORT).show();
}
}else if (key.equals("pref_Id")){
String url = Config.SERVER_URL_ID;
boolean reponse = (!new ConnectUtils().isConnected(this,url));
if(!reponse){
prefEditor.putString(key,Config.ID_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(Config.getContext(), R.string.msgToast_Id_invalid, Toast.LENGTH_SHORT).show();
}
}
}
private void reload(){
startActivity(getIntent());
finish();
}
}
'onPreferenceChangeListener' is a listener that is executed every time a preference is changed by the user. You can return true if data complains validation or false otherwise.
For example:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("pre_mail").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches(Constants.MAILPATTERN, (String) newValue);
}
});
}
}
Hope this help!
From last one week I am facing a strange problem with saved preferences.
I am working on a board which is android compatable.
The actual problem i am facing is,
I have 4 buttons and on the button click I am changing the background images of the button
Onfirstclick -> change the background image of the button to highlited -> second click ->change to normal background image and on first run I am keeping the normal background button image
but on reboot the button background images are not getting saved in my working board though I am using shared preferences.
I have a power button for on and off with which I am rebooting my board.
whatever Image(normal/highlited) I have in onclick that image I should get after rebooting the board
The good thing is that
the code is working perfectly in android mobile but not in my board
this is my code.
Any help is always appreciated.
public class SharedprefsActivity extends Activity {
protected static final String TAG = "HvacActivity";
/** Called when the activity is first created. */
private Button seatdirnbtn;
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private boolean isclick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seatdirnbtn = (Button) findViewById(R.id.seatdirnbtn);
seatdirnbtn.setOnClickListener(listner1);
}
public void onResume() {
super.onResume();
getPrefAndButtonState();
}
public void onPause() {
super.onPause();
setPrefAndButtonState();
}
#Override
public void onRestart() {
super.onRestart();
getPrefAndButtonState();
}
#Override
public void onStop() {
super.onStop();
setPrefAndButtonState();
}
public void getPrefAndButtonState(){
prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}
public void setPrefAndButtonState(){
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
isclick = false;
setPrefAndButtonState();
} else if (!isclick) {
isclick = true;
setPrefAndButtonState();
}
}
};
}
try using getApplicationContext() instead of this as:
in setPrefAndButtonState method :
public void setPrefAndButtonState(){
prefs = getApplicationContext().
getSharedPreferences(prefName, MODE_PRIVATE); <<missing this line
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
and in getPrefAndButtonState method
public void getPrefAndButtonState(){
prefs = getApplicationContext().getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}
I have a login page for my project.Here my requirement is,that login page always want to be logged-in,if once i log in.I have got some ideas through Google,ie., it recommended me to use shared-preference concept,right now i am following this concept and i have tried some code.
In my project the problem is after giving the proper username and password,it does not switch to another screen,at the same i am getting nothing on my log-cat too.How to achieve this concept?
Suggestions please..
please find my sources for reference
class SaveSharedPreferece
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, boolean userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}}
MainActivity.java
public class MainActivity extends Activity
{
Button btn;
EditText edt1,edt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void loginpage()
{
edt1 = (EditText)findViewById(R.id.editText_username);
edt2 = (EditText)findViewById(R.id.editText_password);
btn = (Button)findViewById(R.id.button_login);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(edt1.getText().toString().length()!=0 && edt1.getText().toString().length()!=0)
{
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
else
{
Toast.makeText(getApplicationContext(), "oops! empty..", Toast.LENGTH_SHORT).show();
}
}
});
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
loginpage();
}
else
{
// Call Next Activity
}
if (getIntent().getBooleanExtra("EXIT", false))
{
finish();
}
}
}
ResultActivity.java
public class ResultActivity extends Activity
{
Button btn_exit;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
btn_exit = (Button)findViewById(R.id.button_exit);
btn_exit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
});
}}
thanks for your precious time!..
You are saving boolean to SharedPreferences and getting String. How that is possible.
Better to save and get either boolean or String.
Change your setUserName() code in SaveSharedPreference class as below and it works
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
First add another field in SharedPrefernce file as password. Do same whatever you have done foe username(make it string instead of boolean in setter method) like setter and getter methods.
Create one method which will fetch values from sharedPrefernce like this :
private void validateUser(){
String username = SaveSharedPreference.getUserName(MainActivity.this);
String password = SaveSharedPreference.getPassword(MainActivity.this);
if (check_for_any_condition){
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
}
Call this method in your oncreate method.
Hope it will help you.