Save the theme selected in the preferences - android

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);
}

Related

Save optionMenu item icon to shared preferences

I have a list of data with two different views in my Fragment, my default view is Listview and another is Gridview. I switch between this two views by clicking on an icon on my toolbar.
And I set the switch item icon dynamically inside onOptionsItemSelected method like this:
//global variables
private int currentViewMode = 0 ;
static final int VIEW_MODE_LISTVIEW = 0;
static final int VIEW_MODE_GRIDVIEW = 1;
.
.
.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.switchView:
if (VIEW_MODE_LISTVIEW == currentViewMode){
item.setIcon(R.mipmap.ic_gridview);
currentViewMode = VIEW_MODE_GRIDVIEW;
}else {
item.setIcon(R.mipmap.ic_listview);
currentViewMode = VIEW_MODE_LISTVIEW;
}
switchView();
SharedPreferences sharedPreferences = activity.getSharedPreferences("ViewMode",currentViewMode);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("currentViewMode",currentViewMode);
editor.commit();
return false;
default:
break;
}
return super.onOptionsItemSelected(item);
}
And I get my view from shared preferences like this:
SharedPreferences sharedPreferences = activity.getSharedPreferences("ViewMode",activity.MODE_PRIVATE);
currentViewMode = sharedPreferences.getInt("currentViewMode",VIEW_MODE_LISTVIEW);
But I don't know how can I save the item icon and how to retrive it.
Can you help me please?
Menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/switchView"
android:title=""
android:icon="#mipmap/ic_listview"
app:showAsAction="always"/>
</menu>
You can add another item inside your menu.xml for your gridView Then create a boolean that carries the visibility of this two items. when you switch to listview, set the visibility of gridItem to false, And when you switch to gridview, set the listItem to false; In this way you'll be able to save and retrieve the visibilities with shared preferences as a boolean.
Change your code like this:
<item
android:id="#+id/switchListView"
android:title=""
android:icon="#mipmap/ic_listview"
app:showAsAction="always"/>
<item
android:id="#+id/switchGridView"
android:title=""
android:icon="#mipmap/ic_gridview"
android:visible="false"
app:showAsAction="always"/>
Inside your Fragment:
boolean isGridView;
Then:
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
isGridView = myPrefs.getBoolean("menu_item", false);
And finally change your onOptionItemSelected method like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
final SharedPreferences.Editor editor = myPrefs.edit();
isGridView = myPrefs.getBoolean("menu_item", false);
switch (item.getItemId()) {
case R.id.switchListView:
if (VIEW_MODE_LISTVIEW == currentViewMode){
isGridView=true;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_gridview);
currentViewMode = VIEW_MODE_GRIDVIEW;
}else {
isGridView=false;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_listview);
currentViewMode = VIEW_MODE_LISTVIEW;
}
switchView();
SharedPreferences sharedPreferences = activity.getSharedPreferences("ViewMode",currentViewMode);
SharedPreferences.Editor et = sharedPreferences.edit();
et.putInt("currentViewMode",currentViewMode);
et.commit();
return false;
case R.id.switchGridView:
if (VIEW_MODE_LISTVIEW == currentViewMode){
isGridView=true;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_gridview);
currentViewMode = VIEW_MODE_GRIDVIEW;
}else {
isGridView=false;
editor.putBoolean("menu_item", isGridView);
editor.commit();
activity.invalidateOptionsMenu();
item.setIcon(R.mipmap.ic_listview);
currentViewMode = VIEW_MODE_LISTVIEW;
}
switchView();
sharedPreferences = activity.getSharedPreferences("ViewMode",currentViewMode);
et = sharedPreferences.edit();
et.putInt("currentViewMode",currentViewMode);
et.commit();
return false;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
if(isGridView==true){
menu.findItem(R.id.switchListView).setVisible(false);
menu.findItem(R.id.switchGridView).setVisible(true);
}else{
menu.findItem(R.id.switchListView).setVisible(true);
menu.findItem(R.id.switchGridView).setVisible(false);
}
super.onPrepareOptionsMenu(menu);
}
Important note
How to implement optionMenu inside Fragments:
1. If you have implemented optionMenu inside your MainActivity, then you should return false in your MainActivity's onOptionsItemSelected, otherwise your Fragment's optionMenu will not work.
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
//
}
return false;
}
2. you have to setHasOptionsMenu(true); inside your onCreate in your Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}

Why does using Locale in Fragment result in lots of bugs?

I have two activity namely MainActivity.java and Settings.java and others are fragments, MainActivity is the fragment_container, every fragment is attached here. Settings activity has the settings of changing language. MainActivity contains three buttons and if I click on the button next fragment in a same container displays listview.
If I change the language then if I come back to MainActivity from settings activity and then click on button the listview is still displaying English language. If I pressed back and again click on button then finally language are changed. Although the language aren't change in menu(onOptionsCreateMenu). I saved those settings in the sharedPreferences.
Now, after I exit my app and again come back then again same thing, if I click the button for the first time the language are in English if I come back to fragment and again click on button it changes language. What might be I missing? I searched related question in Stack Overflow but these aren't helpful. Below is my code:
MainActivity.java (This holds all Fragments)
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ImageButton img_boy, img_girl, img_dog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
img_boy = (ImageButton) findViewById(R.id.img_boy);
img_boy.setOnClickListener(this);
img_girl = (ImageButton) findViewById(R.id.img_girl);
img_girl.setOnClickListener(this);
img_dog = (ImageButton) findViewById(R.id.img_dog);
img_dog.setOnClickListener(this);
Boolean isFirstRun = getSharedPreferences("Preference", MODE_PRIVATE).getBoolean("isFirstRun", true);
if (isFirstRun) {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Dark_theme);
builder.setTitle(R.string.chooselanguage).setItems(R.array.language, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 1:
SharedPreferences ensharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor eneditor = ensharedPreferences.edit();
eneditor.putString("language", "en");
eneditor.commit();
case 2:
SharedPreferences npsharedPrefrences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor npeditor = npsharedPrefrences.edit();
npeditor.putString("language", "ne");
npeditor.commit();
break;
}
}
}).setCancelable(false).create().show();
getSharedPreferences("Preference", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();
}
}
public void onBackPressed() {
CallForBackButton();
}
private void CallForBackButton() {
int count = getFragmentManager().getBackStackEntryCount();
switch (count) {
case 0:
QuitDialog();
break;
default:
getFragmentManager().popBackStack();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(MainActivity.this, Settings.class));
break;
case android.R.id.home:
CallForBackButton();
break;
case R.id.exit:
QuitDialog();
}
return true;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.img_boy:
Recycler rc = new Recycler();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, rc);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
// other case
}
}
Settings.java
public class Settings extends AppCompatActivity {
public static final String DEFAULT = "N/A";
Switch aSwitch, aSwitch2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
aSwitch = (Switch) findViewById(R.id.swic);
aSwitch2 = (Switch) findViewById(R.id.swic2);
SharedPreferences sharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
String s1 = sharedPreferences.getString("language", DEFAULT);
if (s1.matches("ne")) {
aSwitch.setChecked(true);
} else {
aSwitch.setChecked(false);
}
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (aSwitch.isChecked()) {
SharedPreferences npsharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor npeditor = npsharedPreferences.edit();
npeditor.putString("language","ne");
npeditor.commit();
aSwitch.setChecked(true);
Toast.makeText(Settings.this, "Nepali Language Selected", Toast.LENGTH_LONG).show();
} else {
SharedPreferences ensharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor eneditor = ensharedPreferences.edit();
eneditor.putString("language","en");
eneditor.commit();
Toast.makeText(Settings.this, "English Language Selected", Toast.LENGTH_LONG).show();
aSwitch.setChecked(false);
}
}
});
}
}
Recycler.java (This is RecyclerView where I put text to display)
public class Recycler extends Fragment {
private List<Name> names;
RecyclerView rv;
String[] nameCollection;
public static final String DEFAULT = "N/A";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recyclerview, container, false);
rv = (RecyclerView) view.findViewById(R.id.rv);
nameCollection = getActivity().getResources().getStringArray(R.array.babies_names);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeData();
initializeAdapter();
return view;
}
private void initializeAdapter() {
rvadapter adapter = new rvadapter(names);
rv.setAdapter(adapter);
}
public void initializeData() {
names = new ArrayList<>();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
String pine= sharedPreferences.getString("language", DEFAULT);
String languageToLoad=pine;
Locale locale=new Locale(languageToLoad);//Set Selected Locale
Locale.setDefault(locale);//set new locale as default
Configuration config = new Configuration();//get Configuration
config.locale = locale;//set config locale as selected locale
getActivity().getResources().updateConfiguration(config, getActivity().getResources().getDisplayMetrics());
for (int i = 0; i < nameCollection.length; i++) {
names.add(new Name(nameCollection[i]));
}
}
}
I just need to fix the language as selected by user.
One more thing, if I exit the app but not close from recent apps then, if I again go back to my app then everything works fine, languages also changes on menu(onOptionMenu). I think the quick fix for this is saving it in savedInstanceState but I am not sure and I don't know how to use that in my case.
I call Locale under MainActivity.java on onStart() callback instead of calling in instalizeData() on recyclerView and now everything working fine :D

SharedPreferences and Rotation

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.

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