Java – Add dynamic checkbox preferences in Android and display them in the preferences screen?

Add dynamic checkbox preferences in Android and display them in the preferences screen?… here is a solution to the problem.

Add dynamic checkbox preferences in Android and display them in the preferences screen?

I want to implement the ability for users to select groups of items to display using checkbox sharing preferences. To be precise, I will read the selected items from the preferences and display them.

This is my preference class

 public class Preferences extends PreferenceActivity {

@Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

One way to add default preferences
    addPreferencesFromResource(R.xml.prefs);

For now I prefer this
    setPreferenceScreen(defaultPref());

}

 The first time application is launched this should be read
private PreferenceScreen defaultPref() {
    PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);

CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
    checkboxPref.setKey("1");
    checkboxPref.setTitle("SomeRandomStuff");
    root.addPreference(checkboxPref);

return root;
 }
     public showAllPreferences () {
           TO SHOW ALL THE PREFERENCES BUT NOT SURE HOW TO DISPLAY THEM
     }
}

Now I don’t understand how to dynamically add more preferences and show them in the preferences screen.

This is the main Activity class

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        setContentView(R.layout.main);
    }catch (Exception e) {
        e.printStackTrace();
    }

exView = (ExpandableListView) findViewById(R.id.expandableListView1);

 STUFF TO ADD IN PREFERENCES 
    editText = (EditText) findViewById(R.id.editText1);
    BUTTON TO ADD PREFERENCES. (SEARCH TERM IS IDENTIFIED AND ADDED TO PREF)
    addButton = (ImageButton) findViewById(R.id.imageButton1);
     BUTTON TO DISPLAY PREFERENCES
    prefButton = (ImageButton) findViewById(R.id.imageButtonPref);

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    final SharedPreferences.Editor editor = settings.edit();

addButton.setOnClickListener(new OnClickListener() {

@Override
        public void onClick(View arg0) {
             TODO Auto-generated method stub

PrefObject obj = new PrefObject();
            String key = Integer.toString(i);
            String title = editText.getText().toString();
            prefArray.add(obj);
            editor.putString(key, title);
            editor.commit();
                            i++

}
    });
    prefButton.setOnClickListener(new OnClickListener() {
         This method should show the preferences activity with new data
        @Override
        public void onClick(View v) {
             TODO Auto-generated method stub
            Intent intent = new Intent(Main.this, Preferences.class);
                    startActivity(intent);
                             I know how to call the intent but I am not sure if
                             how to read the saved contents and display it
                            Preferences pref = new Preferences();
                            pref.showAllPreferences();  

}
    });

Solution

As far as I can tell, the preference doesn’t have a “visibility” option, which makes a bit of sense when you think it’s just a ListView.

See [ 1 ]

PreferenceScreen screen = this.getPreferenceScreen();
 Use "1" since you're using "1" to create it.
CheckBoxPreference ckbox = (CheckBoxPreference) this.findPreference("1");
screen.removePreference(ckbox);

To recreate, you can [ 2 ]:

screen.addPreference(ckbox);

Also, remember to use setOrder(int order) to create your preference so that when you recreate it, it will be recreated in the correct place.

As you can see, it pays to keep a global reference to the preference to make it easier and faster.

Of course, I don’t need to tell you that you should integrate that logic into your CheckboxPreference listener. See this answer No one else sees a good approach except Reto Meier himself (it’s also a checkbox). He registers a listener across the screen and checks which preference triggers the listener, but you can make it simpler by setting its setOnPreferenceChangeListener (but more on that later).

* EDIT: I see you also used a button to add preferences. You can also implement the same logic described above in the button itself. It all depends on whether you want to use a checkbox or a button to do this.

Finally, it

may be worthwhile to set only the enabled state, unless you’re doing something like View advanced preferences or it’s worth keeping novice users away from dangerous actions on your app. But IMHO, generally enabling the state is better for the user experience.

I hope this answers your question.

Related Problems and Solutions