Shared-preferences working just with Fragment Activity - android

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.

Related

onSaveInstanceState null in Fragment everytime

I search everywhere and for the solution but not find it, I need some help.
I have an app that has Two activity's, Activity A and Activity B, but B have fragments, the first fragment from B, have an important data that I don't want to lose when the user press back when going to Activity A.
My problem is this every time I'm back to Activity A and go to B, my Data go empty because android clear it, so I made some search and changes on the code and still not find the solution. Now my code :
ACTIVITY A
fbReceive.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, OmniActivity.class));
}
});
I call B from this line and when they go to B this is the code :
ACTIVITY B
public class OmniActivity extends BaseActivity {
private View parent_view;
private TabLayout tab_layout;
FragmentOmni fragmentOmni = new FragmentOmni();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_omni_om);
parent_view = findViewById(R.id.container);
Tools.setSystemBarColor(this, R.color.new_purple_O200);
openFragment(fragmentOmni);
initToolbar();
initComponent();
}
public void openFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.containerView, fragment, fragment.getTag());
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, MainActivity.class);
startActivityForResult(intent, 1);
}
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Voltar");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.getNavigationIcon().setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_ATOP);
toolbar.setNavigationOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(OmniActivity.this, MainActivity.class);
startActivityForResult(intent, 1);
}
});
}
And when the application executes OpenFragment() they go to this code from Fragment :
FRAGMENT A
public class FragmentOmni extends Fragment {
RecyclerView recyclerView;
MDOmniturn controller;
List<HashMap<String, String>> listproduct;
private ArrayList<Product> producttypelist;
Product tpobjproduct;
private ActionMode actionMode;
private ActionModeCallback actionModeCallback;
private ListProductAdapter lpAdapter;
private NestedScrollView nested_scroll_view;
private ImageButton bt_toggle_input;
private Button bt_hide_input;
private View lyt_expand_input;
EditText edOmni, edMani,edEan ;
LinearLayout layoutNoResult;
Handler time;
TextWatcher textexample;
private ProgressBar progressBarProduct;
LinearLayout linearLayout;
public FragmentOmni() {
}
public static FragmentOmni newInstance() {
FragmentOmni fragment = new FragmentOmni();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null){
producttypelist = savedInstanceState.getParcelableArrayList("list");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_omni, container, false);
return root;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("list", producttypelist);
super.onSaveInstanceState(outState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (savedInstanceState != null) {
producttypelist = savedInstanceState.getParcelableArrayList("list");
}
initexpand(view);
linearLayout = (LinearLayout) view.findViewById(R.id.container);
edOmni = (EditText) view.findViewById(R.id.edOmni);
edMani = (EditText) view.findViewById(R.id.edBManifesto);
edEan = (EditText) view.findViewById(R.id.edEan);
progressBarProduct = (ProgressBar) view.findViewById(R.id.progressBarProduct);
layoutNoResult = (LinearLayout) view.findViewById(R.id.layoutNoResult);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addItemDecoration(new LineItemDecoration(getActivity(), LinearLayout.VERTICAL));
recyclerView.setHasFixedSize(true);
controller = new MDOmniturn(getActivity());
producttypelist = new ArrayList<>();
listproduct = new ArrayList<>();
addListenerTextChange(edOmni);
//set data and list adapter
lpAdapter = new ListProductAdapter(getActivity(), producttypelist);
recyclerView.setAdapter(lpAdapter);
lpAdapter.setOnClickListener(new ListProductAdapter.OnClickListener() {
#Override
public void onItemClick(View view, Product obj, int pos) {
if (lpAdapter.getSelectedItemCount() > 0) {
enableActionMode(pos);
} else {
// read the inbox which removes bold from the row
Product product = lpAdapter.getItem(pos);
Toast.makeText(getActivity(), "Read: " + product.prd_description, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onItemLongClick(View view, Product obj, int pos) {
enableActionMode(pos);
}
});
actionModeCallback = new ActionModeCallback();
}
The savedInstanceState from FRAGMENT A always go NULL, what i'm doing wrong?
Replace your code to the following order
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("list", producttypelist);
}
It might be possible you are expecting data during the wrong state too.
For example, the savedInstanceState will always be null the first time an Activity is started which also points to your fragment, but may be non-null if an Activity is destroyed during rotation, because onCreate is called each time activity starts or restarts.
This line transaction.addToBackStack(null); is unnecessary. You can save the fragment state on its onStop() and onPause() and restore onResume() and onCreate().
You can remove the onBackPressed() in Activity B now
Alternatively, you can use Shared Preferences. When exiting the application, (onBackPressed, onPause ...) save the item you want. For Example the high score of a game.
activity.getSharedPreferences(getString(R.string.app_name),
Context.MODE_PRIVATE).edit().putInt("score", highScore).apply();
And retrieving the score would be:
int value = activity.getSharedPreferences(getString(R.string.app_name),
Context.MODE_PRIVATE).getInt("score", 0);

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

Am I setting up my SharedPreferences correctly to visit login page only once?

Whenever I run my activity in the emulator, it always takes me to MainActivity (if not logged into facebook then goes through FacebookLoginFragment) and then ProfileActivity where ProfileActivity is created twice (still trying to figure this one out). I am still trying to understand the SharedPreferences class, so would appreciate someone explaining that to me!
Ideal Scenario
If app is launched first time MainActivity launches, user is logged into facebook and directed to ProfileActivity
MainActivity is killed in case user hits back button on android
If user exits app and resumes at a later time it should launch at ProfileActivity
Problem
Is my code setup correctly?
How would I set it up correctly, so that login page is only visited once?
Would implementing an onResume() method in MainActivity help?
Code is here:
First activity MainActivity:
public class MainActivity extends FragmentActivity {
private FacebookLoginFragment mainFragment;
protected LoginButton fbLogin;
private ImageView splashLogo;
protected Animation anim;
private static final String FIRST_LAUNCH = "first_launch";
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = prefs.edit();
Intent i;
//Assume false if the key does not yet exist
if (prefs.getBoolean(FIRST_LAUNCH, false)) {
editor.putBoolean(FIRST_LAUNCH, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null){
//Add the fragment on initial activity setup
mainFragment = new FacebookLoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
//Or set the fragment from restored state info
mainFragment = (FacebookLoginFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
splashLogo = (ImageView)findViewById(R.id.appLogoFixed);
anim = AnimationUtils.loadAnimation(this, R.anim.fade_in);
} else {
editor.putBoolean(FIRST_LAUNCH, true);
editor.commit();
//Go to profile page
i = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(i);
finish();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
splashLogo.startAnimation(anim);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Second Activity: ProfileActivity:
public class ProfileActivity extends Activity {
protected ProfilePictureView profilePicture;
private TextView userInfoTextView;
private String userId;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_facebook);
Intent i = getIntent(); //Grab the intent from previous activity
userId = i.getStringExtra("Fb_id");
profilePicture = (ProfilePictureView)findViewById(R.id.profilePicture);
profilePicture.setProfileId(userId);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onResume() {
super.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
}
your FIRST_LAUNCH variable is little bit confusing for me as I expected it to be true on first start, because it's not yet set. And later set it to false, because it's not "first launch" anymore.
Anyway what I see, in first block of your code in MainActivity > onCreate, you set
editor.putBoolean(FIRST_LAUNCH, true);
but you probably forget to execute editor.commit(), so your new preferences are never saved.
EDIT: just very short explanation. Seems you understand SharedPreferences correctly. It's just important to keep in mind, that till you call editor.commit() all changes are not saved!! If you do not call commit, you changes will be lost.

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

Categories

Resources