How to get a preference value in preference fragment - android

I want to show the value of preferences in a custom preference screen. For this I need to get the values, in this case strings, within the preference fragment. In non fragments (activities) I get the values with e.g. final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); and get the string with String phonenumber = prefs.getString("preference_name", null); but in the preference fragment getDefaultSharedPreferences is not applicable for preference fragment.
Any idea how to solve this?
Here's my code snippet:
public class PreferencesFragment extends PreferenceFragment implements
OnSharedPreferenceChangeListener {
TextView tvusername, tvphonenumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
// entering preference phonenumber in text view
String phonenumber = prefs.getString("phonenumber", null);
;
tvphonenumber.setText(phonenumber);
// entering preference username in text view
String username = prefs.getString("username", null);
;
tvusername.setText(username);
}

In onActivityCreated (It's the time when the activity is created) of your fragment class, you do
Context hostActivity = getActivity();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(hostActivity);
That's how you access the hostActivity from the attached fragment.

Related

How to save viewpager page position as bookmark?

I have MainActivity where i define viewpager and i also define button on toolbar.
I want when i click on button it save the viewpager page position with title in another activity in listview.
Provide complete example.
Try saving position of viepager in a shared preference.
save when going away from activity
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("viepager_position", postion);
editor.apply();
retrieve when user comes back to activity
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int position = prefs.getInt("viepager_position",default_position);

How to call strings in fragment from activity?

I have Activity A that has String that updates every 1s.
I also have Fragment B which has a Button and a TextView.
When I press my button in Fragment B I want to get String from Activity A to my TextView.
How do I do this?
SharedPreferences.Editor editor = getSharedPreferences(YOUR_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("DATA_NAME", "YOUR_DATA");
editor.commit();
On the Button Click
SharedPreferences prefs = getSharedPreferences(YOUR_PREFS_NAME, MODE_PRIVATE);
String restoredData = prefs.getString("DATA_NAME", DEFAULT);
yourTextView.setText(restoredData );

Set textView text in navigation drawer fragment from another activity

This is my first time posting so bare with please.
I'm trying to set the text of a textView item in the navigation drawer fragment from another activity.
I've tried:
public class SomeActivity{
...
...
NavigationDrawerFragment.textViewName.setText("words");
}
public class SomeActivity{
...
...
NavigationDrawerFragment frag = (NavigationDrawerFragment )
getFragmentManager().findFragmentByTag("NavigationDrawerFragment");
frag.GetTextFromActivityMethod("words");
}
and I get a null pointer exception and class not loaded (NavigationDrawerFragment) error in debugger.
Try SharedPreference, here is a sample for your case:
public class SomeActivity{
NavigationDrawerFragment.textViewName.setText("words");
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
editor.putString("WORDS", b);
editor.commit();
}
public class SomeActivity {
NavigationDrawerFragment frag = (NavigationDrawerFragment)
getFragmentManager().findFragmentByTag("NavigationDrawerFragment");
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
String words = pref.getString("WORDS", null);
textView.setText
}
From main activity you can set the fragment drawer's text view value. I have set it and it works well!
In navigation Drawer Bar
public TextView test_text;
test_text = (TextView) viewtype.findviewbyid(R.id.xyz);
In the main activity
String ABC = preference.getString(key);
test_text.setText(ABC);

How to call another intent without losing previous data?

I have 2 pages in my application. From Page A I am calling Page B. On page B I have a ListView which is filled by users. Now when User clicks on Back Button of the phone he comes back to Page A. But when he clicks menu and select Add Items again, it opens Page B but my ListView is empty. How can I get back to Page B without losing data in ListView?
Override the onBackPressed in page B, and save your data some where..
then in the onStart of page B reload the data..
One way to accomplish this is to use the SharedPreferences:
public void onStop(Bundle bundle)
{
SharedPreferences mySharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("myBool",true);
//Continue saving all the data you need to recreate the listView
}
Then when you restart the activity, you can reload the preferences in the OnCreate() method like this:
public void onCreate(Bundle bundle)
{
SharedPreferences mySharedPreferences = getPreferences(MODE_PRIVATE);
// Retrieve the saved values.
boolean myBool = mySharedPreferences.getBoolean("myBool");
//Recreate the ListView here
}
It might not be the cleanest way to do so. But since onSavedInstanceState can't be used in your case, it will have to do :)
You can use SharedPreferences to save and load the data in a list
I.e
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settingsActivity.edit();
prefEditor.putString(LISTFROMB, savedItems);
prefEditor.commit();
}
return super.onKeyDown(keyCode, event);
}
And then load it in A like :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.list);
ArrayList<String> selectedItems = new ArrayList<String>();
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
String savedItems = settingsActivity.getString(LISTFROMB, "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
[CALL YOUR ADAPTER HERE WITH THE SELECTED ITEMS LIST]
}
Thanks for your help. I solved the problem just by declaring the ArrayList in Page A. So now when I go back to Page B the source of the ListView is in Page A so easy to load it back.
Don't know if this approach is wrong. Please leave your comment if you think this shouldn't be done.

How do I make a checkbox stay in the same state every time I open my app?

I have a checkbox on my activity. I'm wondering how to make its state stay the same (checked/unchecked) everytime I open my app.
You can use SharedPreferences to implement CheckBox which retains its state even if application is closed.
When user checks/un-check CheckBox.Save it's state in Shared
Preferences.
Whenever user Opens your activity. Read previously saved value from
Shared-Preferences, and set the state of check box.
Here is an Example code to for Saving state of checkbox even if app is closed.
public class TestActivity extends Activity{
CheckBox checkBox = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBox = (CheckBox) findViewById(R.id.my_check_box);
boolean isChecked = getBooleanFromPreferences("isChecked");
Log.i("start",""+isChecked);
checkBox.setChecked(isChecked);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
Log.i("boolean",""+isChecked);
TestActivity.this.putBooleanInPreferences(isChecked,"isChecked");
}
});
}
public void putBooleanInPreferences(boolean isChecked,String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.commit();
}
public boolean getBooleanFromPreferences(String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/my_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
checkBox.setChecked(true);
If you want the last state, simply write the checked state to SharedPreferences in the onPause() method and get the state in the onResume() method.
Reference: http://developer.android.com/reference/android/widget/CheckBox.html
http://developer.android.com/reference/android/content/SharedPreferences.html
Your best option is to implement SharedPreferences in your app and save it's state. When you run your app you retrieve the status from the preferences and check/uncheck the checkbox.
In order to remember application state, you will want to make use of the onSaveInstanceState() and onRestoreInstanceState() methods (see this answer for more info) to determine if the box should be checked or unchecked...
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("IsCheckboxChecked", _myCheckbox.isChecked());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
_myCheckbox.setChecked(savedInstanceState.getBoolean("IsCheckboxChecked"));
}
Your best bet is to use SharedPreference. You can use it like this:
Save the current state to sharedpreference:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putBoolean("isChecked", true); //true or false
editor.commit(); //saves it in shared preference
then when your activity starts you can check that value in the SharedPreference like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);
checkBox.setChecked(sharedPreferences.getBoolean("isChecked", false));
}
Hope you can use this information

Categories

Resources