Adding dynamic checkbox preferences in Android, and display them in preference screen? - java

I want to implement functionality where user will be able to select which group of items to be displayed using checkbox shared preferences. To be precise I will read checked items from the preferences and display.
Here is my preferences 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 cannot understand how do I add more preferences dynamically and display them in preference screen.
Here 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();
}
});

AFAIK, there is no "visibility" option for preferences, which kinda makes sense when you think it's all just a ListView.
See [1]. For what I see, you could do something like this:
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 could do this [2]:
screen.addPreference(ckbox);
Additionally, remember to create your preference using the setOrder(int order) so that when you recreate, it will be recreated in the proper position.
As you can see, it could be worth to keep a global reference to the preference to make it easier and faster.
Of course, I don't need to tell that you should integrate that logic into your CheckboxPreference listener. See this answer by nobody else than Reto Meier himself to see a good way of doing it (it's a checkbox, too). There he registers a listener to the whole screen and checks which preference triggered the listener, but you can do it simpler (but more verbose later on) by just setting its setOnPreferenceChangeListener.
*edit: I see that you're also using a button to add the preference. You can also implement the same logic above into the button itself. It all depends if you want to do this using a checkbox or a button.
Finally, it could be worth to just set the enabled state, unless you are doing something like "see advanced preferences" or something worth to keep novice users away from doing dangerous stuff to your app. But generally the enable states work better for user experience, IMHO.
I hope this answers your question.

Related

How to make users come back to a particular activity after they kill the app

I am working on an app, so basically, when the user launches the app for the first time, activity A comes up, which asks the user for a bunch of data. Now, that I have the data, I take the user to activity B. Here, if the user kills the app completely, and relaunches it, the app reopens activity A, instead of B... Is there a way to control this behaviour? I want to be able to control what activity the app should open after a particular action by the user... Note : I am a complete newbie, so I have no idea how to do this.. I tried to ask this up on a google search, but couldn't find anything proper ig.
You can store boolean by shared preference to do that. Here your AcitivityA class. Store user provided data before user land to ActivityB.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
//Store user data here
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
The easiest way to use user data in all over the app. Make a separate class for storing user data and make the getter and setter to get and set the data.
public class UserSharedPrefs {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
#SuppressLint("CommitPrefEdits")
public UserSharedPrefs(Context context) {
sharedPreferences = context.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void setIsLogin(boolean isLogin) {
editor.putBoolean("isLogin", isLogin);
editor.apply();
}
public boolean getIsLogin() {
return sharedPreferences.getBoolean("isLogin", false);
}
In Activity A makes the reference of that class and get the data and use it as your need. And send the user to desired Activity
if(userSharedPrefs.getIsLogin()){
moveToActivityB()
}

Save state of Button in activity Android

I have two buttons(button1, button2) in my activty. botton1 is 'Enabled'(true) , while the other one isn't.
When I click on button1, button2 becomes 'Enabled'. I want to record this activity in this state for the next utilization of my application.
You can save state in sharedPrefrences, try this
SharedPreferences prefs = getSharedPreferences("Your preference name here", MODE_PRIVATE)
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
b2.setEnabled(true);
prefs.edit().putBoolean("b2enabled", true).commit();//saving State here
}
});
And now where you want to use this state simple get the state as.
Boolean b2state= prefs.getBoolean("b2enabled", false); //false is the default value
And if you want to enable or disable button on result do
if (b2state){
b2.enabled(true);
}
else{
b2.enabled(false);
}
Well, you can use the help of a data storage option. For a simple task like this,
shared preference is enough.
use something like this to store the state change.
function setState(boolean state){
SharedPreferences sharedPref =this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("state",state);
}
you can retrieve the data at anytime (usually in in the beginning) like this. Note that the second argument serves the default value.
int state=this.getPreferences(Context.MODE_PRIVATE).getBoolean("state",false);
Hope this helps.

Android Studio: custom dialog only re-occurs if no is pressed

Okay so I have this message popup that asks the user to kindly rate the app. They can choose Yes or No. If Yes is pressed, the app in the app store will be opened. If no is pressed, the dialog box closes (for now). I want it so that if Yes is pressed, the dialog box will no longer ever show (even if the user only presses yes but does not actually rate the app..) even after they close and re-open the app.
The purpose of this is so that the user doesn't keep getting asked to rate the app even when they may have already done that.
Dialog Class:
public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.btn_yes);
no = (Button) findViewById(R.id.btn_no);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.nianticlabs.pokemongo&hl=en"));
getContext().startActivity(intent);
dismiss();
break;
case R.id.btn_no:
dismiss();
break;
default:
break;
}
dismiss();
}
}
(I know the link is for pokemon go lol its just for trial purposes.)
any help will be greatly appreciated :)
________edit_______
code where i show the dialog (occurs when the user enters a specific class):
public class Final1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final1);
CustomDialogClass cdd=new CustomDialogClass(Final1.this);
cdd.show();
You may need to store a state about whether the user pressed YES button. And before you want to show your dialog, check the state.
Since you only need a Boolean value, SharedPreferences is recommended.
It would be helpful if I could see where you show the actual dialog box, the code you provide for that only goes to the market page again... but we can still work with this.
If you want to never show this box to the user again, I recommend using SharedPreferences. This will enable us to store (basically) permanent variables.
Example:
SharedPreferences settings = getContext().getSharedPreferences("your-app", 0);
if(settings.getBoolean("btn_pressed", false)){
//show dialog
}
This will make sure the dialog doesn't open if we have the Shared Preferences boolean "btn_pressed" set to true.
To set this boolean after the yes button is pressed:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
SharedPreferences.Editor edit = c.getSharedPreferences("your-app", 0).edit();
edit.putBoolean("btn_pressed", true);
edit.apply();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.nianticlabs.pokemongo&hl=en"));
getContext().startActivity(intent);
dismiss();
break;
case R.id.btn_no:
dismiss();
break;
default:
break;
}
dismiss();
}
Shared Preferences is an easy way for your app to remember permanent user settings or things of this nature. Hope this helps!
EDIT: please note syntax correction, the editor has a capital (SharedPreferences.editor becomes SharedPreferences.Editor)

Android Save and check, radio button

Sorry for my bad english.
I have 2 classes,
1 MainActivity.java (Standard)
2 settings.java (for settings)
I have a RadioGroup with 5 Radiobuttons.
I save the state of the radio buttons as follows (in to settings.java class):
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("status", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("blue", blue.isChecked());
editor.putBoolean("orange", orange.isChecked());
editor.putBoolean("purple", purple.isChecked());
editor.putBoolean("grey", grey.isChecked());
editor.putBoolean("green", green.isChecked());
editor.commit();
}
public void loadSettings () {
SharedPreferences settings = getSharedPreferences("status", 0);
royalBlue.setChecked(settings.getBoolean("blue", false));
orange.setChecked(settings.getBoolean("orange", false));
purple.setChecked(settings.getBoolean("purple", false));
titan.setChecked(settings.getBoolean("grey", false));
eighties.setChecked(settings.getBoolean("green", false));
}
the status of the radio buttons is saved successfully. Even after a restart of the app the radio button is saved.
I would like now when the RadioButton orange (or other) is selected, the ImageButton will change my image. I would like to make in the MainActivity.
I have tried it in the Main Activity so but I always get a NullPoinException:
Code from the Main ...
private settings load = new settings();
...
...
public void change (){
if (load.orange.isChecked()){
imBuOn.setImageResource(R.drawable.orange);
}
as I said I can so unfortunately unable to access the status of the radio button.
Do I need to maybe use PreferenceManager? how shall I put it best?
You don't need to create an instance of the settings class and fetch the value of the checkBox. Instead, you should just use the same code as given in the loadSettings method since you are just accessing the SharedPreferences file.
So, in your MainActivity, just run this
private void checkAndSetImage()
{
SharedPreferences settings = getSharedPreferences("status", 0);
if(settings.getBoolean("orange", false))
{
imBuOn.setImageResource(R.drawable.orange);
}
}
Just call this function to wherever applicable.

Save item in listview with sharedpreferences

I need to stored my listview that i create dynamically by a "add" button. Of course right now if i go out of application the items disappears. I tryied in this way but something's wrong
public class MainActivity extends Activity{
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
// Eliminare un elemento al longClick con dialog di conferma
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
final int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setTitle("Are you sure");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
lvItem.setClickable(true);
lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = lvItem.getItemAtPosition(position);
Intent intent2 = new Intent(getApplicationContext(), MainActivity.class); // Mettere settings.class quando creata
MainActivity.this.startActivity(intent2);
}
});
}
private void setUpView() {
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, R.layout.customlistview,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert value");
return false;
} else {
return true;
}
}
// Shared preferences
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");
itemAdapter.add(dataSet);
itemAdapter.notifyDataSetChanged();
}
I don't know how "call" the shared preferences and i don't know if in this way it's correct. Right now nothing happen, nothing is saving. Someone can help me please? Thanks
You should look at this API training about activity life cycle:
http://developer.android.com/training/basics/activity-lifecycle/index.html
and also this:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
As you can see, your activity can be gone because the user actively destroy it (using the back button) or the system can destroy it. If they system destroy it you can use onSaveInstanceState to save the data and onCreate to retrieve it. In that case you do not have to use SharedPreferences - just use Bundle as described in the link.
However, if you want to persist your data when the user close it, you should save your data when the call back onDestroy() is called. And retrieve the data when onCreate() is called. onDestroy() is called before the system thinks that your activity is not needed anymore, like when the user click the "back" button. In that case you do have to use one of the storage method provided by android, including Shared preferences. Like someone else said, it requires a "key, value" mechanism, so it might not match 100% with what you do. Using sqlLite is a bit heavy weight for this task, since your data is not really of a table type either (a single column table, actually, which is still not database worthy IMO). I think the best way to store your list is to use internal file. When onDestroy() is called, grab all your data and save to a file. When onCreate() is called, read the file and repopulate your list. You can read about android file system, including internal files here:
http://developer.android.com/training/basics/data-storage/files.html
As a close note, if the user press the "Home" button, your activity will not be destroyed. If he then "Force close" your app then nothing will be saved. If you still want to save it even in that case, I suggest you to save your data when "onStop()" is called and reset your list when onStart() is called.
Right now nothing happen, nothing is saving.
That's because you never call your SavePreferences() method.
If you want to continue using SharedPreferences to store the data in your list, you will need to call SavePreferences() on every item in the list.
However, SharedPreferences are used for storing data in a key-value format. This means that every item in your list will require a key, and you need to know that key to retrieve the data. If your list can contain a variable number of items, SharedPreferences is likely not what you want.
I recommend reading the Storage Options documentation, which provides a complete example using Shared Preferences correctly, and discusses other options which may better suit your needs.

Categories

Resources