I realized that, even though the Sharedprefs, saves the checkbox state, it doesn't keep the drawable resource background thingy that way...... any way to save that too? I was hoping it stays like the picture below. EDIT : So my objective would be that, On checkbox being checked, background changes, because of sharedprefs, the checked state is saved and on exiting the app, the checkbox remains checked but the background of the checkbox returns to its "un-highlighted" state without the drawable background
CheckBox C1,C2,C3;
//Creating keys for sharedpreference
private static final String C1key = "C1_key";
private static final String C2key = "C2_key";
private static final String C3key = "C3_key";
SharedPreferences shp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anime);
//sharedpreference created with the name as anime
shp = getSharedPreferences("Anime",MODE_PRIVATE);
//This is just background gradient animation
ConstraintLayout constraintLayout = findViewById(R.id.layout_anime);
AnimationDrawable animationDrawable = (AnimationDrawable) constraintLayout.getBackground();
animationDrawable.setEnterFadeDuration(2000);
animationDrawable.setExitFadeDuration(4000);
animationDrawable.start();
//Initializing checkboxes
C1 = findViewById(R.id.C1);
C2 = findViewById(R.id.C2);
C3 = findViewById(R.id.C3);
//mapping checkbox and string for ease of use during sharedprefs
Map<String, CheckBox> checkBoxMap = new HashMap();
checkBoxMap.put(C1key,C1);
checkBoxMap.put(C2key,C2);
checkBoxMap.put(C3key,C3);
//loading initial values from sharedprefs, and also creating onCheckedChangeListeners from the map
loadInitialValues(checkBoxMap);
setupCheckedChangeListener(checkBoxMap);
}
public void loadInitialValues(Map<String, CheckBox> checkboxMap) {
for (Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
boolean checked = shp.getBoolean(checkboxEntry.getKey(), false);
checkboxEntry.getValue().setChecked(checked);
}
}
public void setupCheckedChangeListener(Map<String, CheckBox> checkboxMap) { //for loop to cover all the checkboxes and keys in the map
for (final Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
checkboxEntry.getValue().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences.Editor editor = shp.edit();
editor.putBoolean(checkboxEntry.getKey(), isChecked);
editor.apply();
// this part is to turn the background of the checkbox to a specified drawable when its checked and when it isn't
if(checkboxEntry.getValue().isChecked()) //checkboxentry.getvalue().ischecked is to check whether specific checkboxes are in the checked state or not, Ex C1.ischecked() C2.ischecked() and so on
{
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background);
}
else
{
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background_default);
}
}
});
}
Than i believe should be something like this:
//If is selected set the background
if (C1.isChecked()) {
C1.setSelected(true);
C1.setBackgroundResource(R.drawable.[name of the background]);
}else{
//If is not selected
C1.setBackgroundResource(0);
}
Thanks to Suehtam for helping me out with this really appreciate it!!! this the solution
private void loadInitialValues(Map<String, CheckBox> checkboxMap) {
for (Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
boolean checked = shp.getBoolean(checkboxEntry.getKey(), false);
checkboxEntry.getValue().setChecked(checked);
if (checkboxEntry.getValue().isChecked()) {
checkboxEntry.getValue().setSelected(true);
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background);
}else{
//If is not selected
checkboxEntry.getValue().setBackgroundResource(0);
}
}
}
private void setupCheckedChangeListener(Map<String, CheckBox> checkboxMap) {
for (final Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
checkboxEntry.getValue().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences.Editor editor = shp.edit();
editor.putBoolean(checkboxEntry.getKey(), isChecked);
if (checkboxEntry.getValue().isChecked()) {
checkboxEntry.getValue().setSelected(true);
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background);
}else{
//If is not selected
checkboxEntry.getValue().setBackgroundResource(0);
}
editor.apply();
}
});
}
}
Humm, if i understood what you want to do is not to save the value but instead to set the box selected.
something like this:
if(C1.isChecked()){
//In this way the box would be with the selected view.
C1.setSelected(true)
}
if is not the state selected and is just the drawable you could do the same:
It's just an example since i don't know which drawable function you are going to use.
Ex:
if(C1.isChecked()){
C1.setCheckMarkDrawable([drawable location]);
}
Related
I am currently creating an app that has a music in android studio. So I created a music icon on the settings menu and when it is clicked it should mute or remove the music. So here is the problem, when I click the music icon it changes to the muted music icon however when I leave the settings menu and go to the settings menu again, the supposedly muted icon returns to the normal music icon. I don't know why it changes back to its original icon. It is supposed to be muted and when the user clicks on it again then it should be unmuted. I am new to android development so I still don't know this kind of stuff.
Here is my code for the music and sound settings:
public void showSettings(View v){
TextView exitTxt;
LinearLayout music,sound;
Button quitBtn;
ImageView soundIC, musicIC;
settingsMenu.setContentView(R.layout.activity_settings);
settingsMenu.setCancelable(false);
exitTxt = settingsMenu.findViewById(R.id.exitBtn);
music = settingsMenu.findViewById(R.id.music);
sound = settingsMenu.findViewById(R.id.sound);
soundIC = settingsMenu.findViewById(R.id.soundOnIC);
musicIC = settingsMenu.findViewById(R.id.musicOnIC);
exitTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
settingsMenu.dismiss();
}
});
music.setOnClickListener(new View.OnClickListener() {
boolean isClicked = false;
#Override
public void onClick(View v) {
if(!isClicked) {
musicIC.setImageResource(R.drawable.ic_music_off);
music.setBackgroundResource(R.drawable.outline_clicked);
isClicked = true;
}
else{
music.setBackgroundResource(R.drawable.outline);
musicIC.setImageResource(R.drawable.ic_music);
isClicked = false;
}
}
});
sound.setOnClickListener(new View.OnClickListener() {
boolean isClicked;
#Override
public void onClick(View v) {
if(!isClicked) {
soundIC.setImageResource(R.drawable.ic_sound_off);
isClicked = true;
}
else{
soundIC.setImageResource(R.drawable.ic_sound);
isClicked = false;
}
}
});
settingsMenu.show();
}
You will have to save the settings information somewhere.
Easy way is just to use Shared Preferences, This is my code that i use
public class Preferences {
SharedPreferences preferences;
public Preferences(Context context){
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public void StorePreference(String Field,String Value){
if(preferences!=null){
SharedPreferences.Editor editor = preferences.edit();
if(editor!=null){
editor.putString(Field,Value);
editor.apply();
}
}
}
public String ReadPreference(String Field){
String returnData=null;
if(preferences!=null){
returnData=preferences.getString(Field,"");
}
return returnData;
}
public boolean ExistsPreference(String Field){
boolean returnData=false;
if(preferences!=null){
returnData=preferences.contains(Field);
}
return returnData;
}
}
Add Preferences as a static to the file which extends Application.
Then to save the data use Preferences.StorePreference(Name of your field,Value).
To read from preferences use Preferences.ReadPreference(Name of your field).
For other methods on how to save data you can look here https://developer.android.com/training/data-storage#pref
I've been struggling with this for some time now and could not find a solution. Currently I'm population my RecyclerView with all the installed apps on the device using PackageManager. This works perfectly, here is the result I get:
The issue I'm having is that I can't figure out how to store/retrieve the selected checkbox, let me elaborate.
When I select a Checkbox I do the following inside onBindViewHolder:
holder.mAppSelect.setOnCheckedChangeListener(null);
holder.mAppSelect.setChecked(mDataSet.get(position).isSelected());
holder.mAppSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).setSelected(isChecked);
if (holder.mAppSelect.isChecked()){
//Ok great, I can use this to get the position, package name and app name that was selected/checked
}else{
//and it was un-sellected
}
So, I can used the above to store the package name of the selected checkbox and also store a boolean of the state of the checkbox in SQLite, like this:
holder.mAppSelect.setOnCheckedChangeListener(null);
holder.mAppSelect.setChecked(mDataSet.get(position).isSelected());
holder.mAppSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).setSelected(isChecked);
if (holder.mAppSelect.isChecked()){
dbManager.insert(holder.mTextViewPackage.getText().toString(), true);
}else{
dbManager.insert(holder.mTextViewPackage.getText().toString(), false);
}
This is where I have difficulty.. Lets say I close the Activity and open it again, I would like to get the packages/checkboxes that was selected from SQLite and set it again.
So, I'm looking for a way to "cycle" though each holder, get the package name from the holder so that I can check in SQLite if the checkbox was selected previously and set it accordingly.
I think it's also worth mentioning that applications may have been uninstalled or installed since the last time the application was launched. So that would mean that the getAdapterPosition will not remain the same.
EDIT 1:
This is how I populate the Array called mDataSet:
public class AppManager {
private Context mContext;
private AppInfo appInfo;
private ArrayList<AppInfo> myApps;
public AppManager(Context c) {
mContext = c;
myApps = new ArrayList<AppInfo>();
}
public ArrayList<AppInfo> getApps() {
loadApps();
return myApps;
}
private void loadApps() {
List<ApplicationInfo> packages = mContext.getPackageManager().getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
AppInfo newApp = new AppInfo();
newApp.setAppName(getApplicationLabelByPackageName(packageInfo.packageName));
newApp.setAppPackage(packageInfo.packageName);
newApp.setAppIcon(getAppIconByPackageName(packageInfo.packageName));
myApps.add(newApp);
}
Collections.sort(myApps, new Comparator<AppInfo>() {
#Override
public int compare(AppInfo s1, AppInfo s2) {
return s1.getAppName().compareToIgnoreCase(s2.getAppName());
}
});
}
// Custom method to get application icon by package name
private Drawable getAppIconByPackageName(String packageName) {
Drawable icon;
try {
icon = mContext.getPackageManager().getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
// Get a default icon
icon = ContextCompat.getDrawable(mContext, R.drawable.ic_launcher_background);
}
return icon;
}
// Custom method to get application label by package name
private String getApplicationLabelByPackageName(String packageName) {
PackageManager packageManager = mContext.getPackageManager();
ApplicationInfo applicationInfo;
String label = "Unknown";
try {
applicationInfo = packageManager.getApplicationInfo(packageName, 0);
if (applicationInfo != null) {
label = (String) packageManager.getApplicationLabel(applicationInfo);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return label;
}
}
what you can do is use shared preferences
when you start activity retrive state from shared preference like this
SharedPreferences sharedPreference PreferenceManager.getDefaultSharedPreferences(getAppContext());
for(i=0;i<mDataSet.size();i++)
{
mDataSet.get(i).setSelected(sharedPreference.getBoolean(mDataSet.get(i).getAppPackage(),false));
}
and in your adapter save state like this.
holder.mAppSelect.setOnCheckedChangeListener(null);
holder.mAppSelect.setChecked(mDataSet.get(position).isSelected());
holder.mAppSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).setSelected(isChecked);
sharedPreference.edit().putBoolean(mDataSet.get(position).getAppPackage(), isChecked).commit();
});
As I can see, you are following the right steps to show the checkbox selected, if isSelected() returns true, and to save the state(checked/unckecked) of the checkbox in SQLite.
TO display the saved state of the checkboxes from SQLite when you close and open the Activity again, you just need to do is:
First, you need to get the latest list of installed packages.
Select data/checkbox values from SQLite where package name matches with the
latest list of packages.
Now, as you have the saved checkbox values from SQLite, create data set
using the latest installed app list and the checkbox values which you
got from SQLite.
Pass it to your RecyclerViewAdeptor.
It should work fine.
You can try OnClickListener instead of OnCheckedChangeListener
Try this method,
1.Use a list which will have selected items. //selectedlist
If you want to store it permanantly, then use SharedPref.
2.Choose item's data which will be unique //appname as string
3.Set checked state based on the selected list item.
if(selectedlist.get(appname)!=null
&& (selectedlist.get(appname).equals("selected"))) {
holder.checkBox.setChecked(true);
}
else {
holder.checkBox.setChecked(false);
}
4. Add listener to your checkbox,
View.OnClickListener listener=new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedlist.get(appname)==null) {
selectedlist.put(appname, "selected");
else if (selectedlist.get(appname).equals("selected"))
selectedlist.put(appname, "not selected");
else
selectedlist.put(appname, "selected");
notifyDataSetChanged();
}
};
holder.checkBox.setOnClickListener(listener);
I am new for android, I have ListView with custom adapter, I pass one string if matches in ListView item want to change list item text color from Activity.
Here my code:
MyActivity:
public void handleResult(String rawResult) {
if(Utility.isNotNull(rawResult.getText().toString())) {
for(int i=0;i<listView.getAdapter().getCount();i++){
if(rawResult.equals(listItems.get(i).getStockItems())){
// listView.getChildAt(i).setBackgroundColor(ContextCompat.getColor(context, R.color.hint));
/* Here I want to change list item text color*/
adapter.notifyDataSetChanged();
}
}
}
}
Thanks in advance!
In your model class add one paramter like this
public class DataHolder{
private String StockItems;
private int isSelected;
public DataHolder(String StockItems, int isSelected) {
this.StockItems = StockItems;
this.isSelected = isSelected;
}
public String getStockItems() {
return StockItems;
}
public void setStockItems(String StockItems) {
this.StockItems = StockItems;
}
public int getiIsSelected() {
return isSelected;
}
public void setIsSelected(String isSelected) {
this.isSelected = isSelected;
}
}
initialise IsSelected zero
public void handleResult(String rawResult) {
if(Utility.isNotNull(rawResult.getText().toString())) {
for(int i=0;i<listView.getAdapter().getCount();i++){
if(rawResult.equals(listItems.get(i).getStockItems())){
listItems.get(i).setIsSelected(1);
adapter.notifyDataSetChanged();
}
}
}
}
In your cusom adapter class check
if(listItems.get(i).getiIsSelected()==1)
{
//set red text color
}
else
{
//set black text color
}
UI tasks can only be done on the UI Thread. If u want to run it from the handler, you have to define a runOnUiThread method. Take a look at this ans
how to use runOnUiThread
try this code:
for(int i=0;i<listView.getChildCount();i++) {
// yours code
View item = listView.getChildAt(i);
item.setBackgroundResource(R.drawable.your_image); //change image
((TextView)item.findViewById(R.id.text1)).setTextColor(Color.RED); //text1 is your cusotm listview item's text id
adapter.notifyDataSetChanged();?
}
I assume you use TextView , To change his text color, first you need to get him, when you create your Item, add id to TextView
with xml
<TextView
android:id="#+id/myId"...
Or if you use java
textView.setId(R.id.myId)
and in your code :
((TextView)listView.getChildAt(i).findViewById(R.id.myId)).setTextColor(ContextCompat.getColor(context, R.color.hint));
If you want to set the Item Background with your Drawble Image you can use
.setBackground(getResources().getDrawable(R.drawable.yourDrawble));
Make one method in your Adapter class to update text color and create one flag in Adapter that is initially false ,Use below method to do this
boolean isChangeColor = false;
String colorCode = "#FFFFFF";
private void updateTextColor(boolean isChangeColor , String colorCode) {
this.isChangeColor=isChangeColor;
this.colorCode=colorCode;
notifyDataSetChanged();
}
And in getView()
if(isChangeColor) {
textView.setTextColor(Color.parseColor(colorCode));
} else {
colorCode = "#FFFFFF";
textView.setTextColor(Color.parseColor(colorCode));
}
I have an Activity that looks like this - the length of the list view is dynamic and can change;
Now, I have declared and initialized checkboxes based on the length of the array.
I need to save the states of these boxes when the user clicks on "Save". How do I achieve this? I wrote the following code, but I get no input, i.e. even though the checkboxes are initialized, I don't think the activity knows which checkbox declaration is for which checkbox on the activity. Please help - thanks!
cbs = new CheckBox[length];
for (int i=0;i<length;i++){
cbs[i] = new CheckBox(ThisActivity.this);
}
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoOnBtnClick(v);
}
});
}
public void DoOnBtnClick (View v) {
for(int i = 0; i < cbs.length; i++){
if(cbs[i].isChecked()){
selectedCheckboxes.add(toInt(cbs[i].getTag()));
Log.e("GET TAG",Integer.toString(toInt(cbs[i].getTag())));
}
}
}
you can use sharedPreferences to store and retrieve checkbox state data
Initialize variables first:
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Now in your onCreate() after all checkbox are initialized use setOnCheckedChangeListener
Now you can load data from sharedpreferences using this:
public void Load_checklist() {
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
for(int i = 0; i < cbs.length; i++){
if (shared.getString(Integer.toString(i), "").equals("1")) {
cbs[i].setChecked(true);
}else{
cbs[i].setChecked(false);
}
}
}
finally your onCreate method should look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_name);
int array_length=jArray.length(); //checkbox size
//layout where you want to dynamically add checkboxes
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.lyout);
Load_checklist();
for(int c=0; c<jArray.length();c++){
CheckBox chk=new CheckBox(this);
chk.setId(c++);
chk.setText("Click to add values");
chk.setTextColor(Color.GRAY);
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
String s="x"+buttonView.getId();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
switch(buttonView.getId()){
case 1: // do something on 1st checkbox
if (isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Integer.toString(c), "1");
editor.commit();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Integer.toString(c), "0");
editor.commit();
}
break;
case 2: //do something on 2nd checkbox
break;
//And SO ON for all checkboes
}
}
});
linearLayout.addView(chk);
}
}
N.B: If SetId(Int) is not working then you can use setTag(int) instead.
If a CheckBox's Tag should represent its index in the list, you should set that tag when you are instantiating them.
for (int i=0;i<length;i++){
cbs[i] = new CheckBox(ThisActivity.this);
cbs[i].setTag(i);
}
I would not recommend this approach if you expect to have a variable amount of checkboxes due to the performance implications. Instead, consider using a RecyclerView with a backing list of model objects representing the state of your checkboxes.
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html
I am new to Android development and I am wondering if there is a way to have some sort of remember me function where it allows a user to have an option whether to save the current state of radio buttons.... a bit like a remember me function on a login apart from using a set of radio buttons instead....any help will be appreciated!
Here is my code:
#Override
/*
* Holding the data for the radio buttons from the xml file
*/
RadioGroup gender = (RadioGroup) findViewById(R.id.question1);
gender.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answer1A:
ans1 = 1;
break;
case R.id.answer1B:
ans1 = 2;
break;
}
}
});
To obtain shared preferences, use the following method In your Code:
SharedPreferences _prefs = this.getSharedPreferences(
"values_to_remember", Context.MODE_PRIVATE);
To read preferences:
int ansA = "ans1";
int value = _prefs.getInt(ansA, 1(default value));
To edit and save preferences
_edit().putInt(ansA , 1).apply();
private RadioButton button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences=getSharedPreferences("check", MODE_PRIVATE);
button=(RadioButton)findViewById(R.id.question1);
button.setChecked(preferences.getBoolean("set", false));
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor=preferences.edit();
editor.putBoolean("set", isChecked);
editor.commit();
}
});
}
You will have use a sharedpreference. And store the state of radiobutton in it.