SharedPreferences and Rotation - android

I have a button in my Apps menu, by clicking on that button the will rotate.. BUT when I close the App and reopen the App its not rotated as I did left it.
I want to store and retrieve the Orientation with SharedPreferences.
I have tried many examples but non of them actually helped me.
Here is my menu code:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/** Rotation */
case R.id.menuRotate:
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
if (preferences.getBoolean("orientation", true)) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
return false;
}
I have nothing in my onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Thanks a lot guys in Advance

case R.id.menuRotate:
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = preferences.edit();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
editor.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
editor.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
editor.commit();
break;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
int orientation = preferences.getInt("orientation", -1);
if(orientation != -1){
setRequestedOrientation(orientation);
}
}
Hope this helps.

Related

Shared Preferences not saved or recovered after setup in Settings Activity

I have done a basic Settings Activity. What I want, is when user selects a option from a list (in Settings), this will save the value, and a "flag".
With this flag I want to use it in the Main Activity, to force an api call.
The problem is that the values in Shared Preferences are not "working" properly...
Here is how I set up the settings activity:
public class SettingsActivity extends AppCompatPreferenceActivity {
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.edit()
.putBoolean("reload_data", true).commit();
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
addPreferencesFromResource(R.xml.pref_general);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
/**
* {#inheritDoc}
*/
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return SettingsFragment.class.getName().equals(fragmentName);
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference(getString(R.string.languages_preferences_title)));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
}
Notice that I put the shared preference to save the flag as:
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.edit()
.putBoolean("reload_data", true).commit();
And here is how I'm reading in MainActivity
#Override
protected void onResume() {
boolean reloadData = PreferenceManager
.getDefaultSharedPreferences(getBaseContext())
.getBoolean("reload_data", true);
if (reloadData && presenter != null) {
if (this.dailiesMap != null) {
this.dailiesMap.clear();
}
presenter.getDailiesAchievementModels();
PreferenceManager
.getDefaultSharedPreferences(getBaseContext())
.edit()
.putBoolean("reload_data", false).apply();
}
super.onResume();
}
When user it comes from Settings is suposed to be a true if user selects some option from the list. But this is not working. it comes to false.
First image is before change language(preference option)
Second image is after change language
As you can see , language change but not "my custom" key

Save the theme selected in the preferences

does not work switching the theme of the application from the settings menu. starts a theme from the "else" block
SharedPreferences sharedPrefs;
final String CURRENT_THEME = "CURRENT_THEME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String theme = sharedPrefs.getString("CURRENT_THEME",null);
if(theme != null && theme.equals("light"))
{
setTheme(R.style.AppThemeLight);
}
else
{
setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lightTheme:
SharedPreferences.Editor editor1 = sharedPrefs.edit();
editor1.putString(CURRENT_THEME, "light");
editor1.commit();
return true;
case R.id.darkTheme:
SharedPreferences.Editor editor2 = sharedPrefs.edit();
editor2.putString(CURRENT_THEME, "dark");
editor2.commit();
return true;}
Change the theme after selecting it from the options menu.
And use editor.apply() instead of editor.commit()
final String CURRENT_THEME = "CURRENT_THEME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
changeTheme();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lightTheme:
SharedPreferences.Editor editor1 = sharedPrefs.edit();
editor1.putString(CURRENT_THEME, "light");
editor1.apply();
changeTheme();
return true;
case R.id.darkTheme:
SharedPreferences.Editor editor2 = sharedPrefs.edit();
editor2.putString(CURRENT_THEME, "dark");
editor2.apply();
changeTheme();
return true;}
private void changeTheme(){
String theme = sharedPrefs.getString(CURRENT_THEME,"light");
if(theme != null && theme.equals("light"))
{
setTheme(R.style.AppThemeLight);
}
else
{
setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
SharedPreferences sharedPrefs;
final String CURRENT_THEME = "CURRENT_THEME";
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
changeTheme();
setContentView(R.layout.activity_main);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lightTheme:
SharedPreferences.Editor editor1 = sharedPrefs.edit();
editor1.putString(CURRENT_THEME, "light");
editor1.apply();
changeTheme();
return true;
case R.id.darkTheme:
SharedPreferences.Editor editor2 = sharedPrefs.edit();
editor2.putString(CURRENT_THEME, "dark");
editor2.apply();
changeTheme();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void changeTheme(){
String theme = sharedPrefs.getString(CURRENT_THEME,"light");
if(theme != null && theme.equals("light"))
{
setTheme(R.style.AppThemeLight);
}
else
{
setTheme(R.style.AppTheme);
}
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
}

Shared-preferences working just with Fragment Activity

I have this Fragment Activity which is my main activity and include 2 Fragment Activity.
/** SharedPreferences */
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
int currentOrientation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/** Rotation SharedPreferences */
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
int orienation = preferences.getInt("orientation", -1);
if (orienation != -1) {
setRequestedOrientation(orienation);
}
/** End */
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (outState == null) {
outState = new Bundle();
}
outState.putInt("currentOrientation",
Integer.valueOf(currentOrientation));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentOrientation = savedInstanceState.getInt("currentOrientation");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menus, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/** Rotation */
case R.id.menuRotate:
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = preferences.edit();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
editor.putInt("orientation",
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
editor.putInt("orientation",
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
editor.commit();
break;
}
return false;
}
}
I had set the orientation option in the menu.
The user can change the orientation from the menu to be in landscape or portrait.
Its working nice, BUT the problem is the other activities.
How can I read from the shared-preferences that I'v already declared in my main activity
what I want is that all activities in my app get the same orientation what the users choice from the menu.
This is one of my other activity:
public class MainList extends Activity {
LinearLayout b1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_list);
b1 = (LinearLayout) findViewById(R.id.list_a);
b1.setOnClickListener(mb1);
}
View.OnClickListener mb1 = new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainList.this, List_1.class));
}
};
Thanks in Advance :)
So, in each you should be using the same context and not just "this".
private Context context;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
You can make this context accessible by other classes that do not have a type (just function holders).
Then, in your use of Shared Prefs :
final SharedPreferences prefList = context.getSharedPreferences(
Constants.PREFERENCE_NAME, Context.MODE_PRIVATE);
If everyone is using getApplicationContext() then they will be able to talk to one another as they are all using the same Context. I would always suggest that you use Context.MODE_PRIVATE unless you need external applications to be able to grab information from those SharedPreferences.

How can I retrieve shared preferences onCreate?

In the preferences I would like to change the preference view according the Unit type(Imprial or metric). On the create method I am checking what was the last value of the
measurement_unit preference, but always return metric on the app startup.
I also have a OnSharedPreferenceChangeListener where I am changing the view according the user entry, which is working. How can I get the saved preference when the onCreate is called?
public class PrefMainActivity extends PreferenceActivity{
String TAG="BlueGlucose";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.action_settings);
this.init_view();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
PrefMainActivity.this.init_view();
}
// your stuff here
};
private void init_view(){
try
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String metric = getResources().getString(R.string.imperial);
if (prefs.getString("measurement_unit",metric) == metric)
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefMainFragmentImperial()).commit();
else
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefMainFragmentMetric()).commit();
prefs.registerOnSharedPreferenceChangeListener(spChanged);
}
catch(Exception ex)
{
}
}
if (prefs.getString("measurement_unit",metric) == metric)
String in java need to be compared by equals or equalsIgnoreCase

SharedPreference not recreating menu

I'm trying to use SharedPreferences to store a preference, then change the default checked state of the menu item based on the SharedPreference. But it does not seem to be working. The menu choice stays until the app is closed. When I reload the app, the setting is back to the default, instead of the new SharedPreference setting.
public class MainActivity extends Activity {
boolean prefs = true;
String FILENAME = "settings";
String string;
public static final String LOG_TAG = "dbryant423";
public static final String PREFS_NAME = "settings";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(LOG_TAG, "prefs value: " +prefs);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference == "us")
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference == "metric")
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
// called when an item is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { // decide which MenuItem was pressed based on it's id
case R.id.menu_us:
menuUS();
case R.id.menu_metric:
menuMetric();
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (prefs == true)
menu.findItem(R.id.menu_us).setChecked(true);
else if (prefs == false)
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
public void menuUS() {
prefs = true;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "us");
editor.commit();
}
public void menuMetric() {
prefs = false;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "metric");
editor.commit();
}
public void calculateCylinder(View v) {
Intent calculateCylinderUS = new Intent(this, CalculateCylinder.class);
Intent calculateCylinderMetric = new Intent(this, CalculateCylinderMetric.class);
Log.v(LOG_TAG, "prefs value: " +prefs);
if (prefs == true)
startActivity(calculateCylinderUS);
else if (prefs == false)
startActivity(calculateCylinderMetric);
}
Please note that onPrepareOptionsMenu gets called just before the menu is displayed to the user.
Looking at your code you are calling setChecked(true) on R.id.menu_us and R.id.menu_metric based on local variable prefs whose value will always be true whenever the activity is created. So in order to persist these states we must update menu-items based on preference values and not based on values of local variable.
I think you'd rather modify your onPrepareOptionsMenuand onCreateOptionsMenu functions as below and give it a try:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference == "us")
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference == "metric")
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
Don't compare string variables by == sign
here
if (preference == "us")
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference == "metric")
menu.findItem(R.id.menu_metric).setChecked(true);
instead use .equals()
if (preference.equals("us"))
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference.equals("metric"))
menu.findItem(R.id.menu_metric).setChecked(true);
I used a little bit from both answers, and I found some missing pieces myself. One of the main problems I figured out, is that I did not have a "break;" in my switch statement, and it was running both cases, no matter which one I selected. The other final fix was instead of calling
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference.equals("metric"))
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
in which my if/else if statements are trying to modify the setChecked attribute, I realized all I needed to do was modify the value of "prefs" instead in the onCreateOptionsMenu. like so:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
prefs = true;
else if (preference.equals("metric"))
prefs = false;
return true;
}
The onPrepareOptionsMenu still needs the "setChecked" in order to switch which choice has been selected.
here is the updated working code:
public class MainActivity extends Activity {
boolean prefs = true;
String FILENAME = "settings";
String string;
public static final String LOG_TAG = "dbryant423";
public static final String PREFS_NAME = "settings";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(LOG_TAG, "prefs value onCreate: " +prefs);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
prefs = true;
else if (preference.equals("metric"))
prefs=false;
return true;
}
// called when an item is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { // decide which MenuItem was pressed based on it's id
case R.id.menu_us:
menuUS();
break;
case R.id.menu_metric:
menuMetric();
break;
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
String preference = settings.getString("preference", string);
if (preference.equals("us"))
menu.findItem(R.id.menu_us).setChecked(true);
else if (preference.equals("metric"))
menu.findItem(R.id.menu_metric).setChecked(true);
return true;
}
public void menuUS() {
prefs = true;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "us");
editor.commit();
Log.v(LOG_TAG, "prefs value menuUS: " +prefs);
}
public void menuMetric() {
prefs = false;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("preference", "metric");
editor.commit();
Log.v(LOG_TAG, "prefs value menuMetric: " +prefs);
}
public void calculateCylinder(View v) {
Intent calculateCylinderUS = new Intent(this, CalculateCylinder.class);
Intent calculateCylinderMetric = new Intent(this, CalculateCylinderMetric.class);
Log.v(LOG_TAG, "prefs value calculateCylinder: " +prefs);
if (prefs == true)
startActivity(calculateCylinderUS);
else if (prefs == false)
startActivity(calculateCylinderMetric);
}

Categories

Resources