How to save background with sharedPreferences - android

hello friends I change the background with a spinner but I can't save the background with shared preferences can you help me? But if I delete the .setBackgroundColor() in position, the instant background won't change, I really don't understand.
the code is all. I cannot save the color code for this SharedPrence. By the way, I'm new to ANDROID.
public class MainActivity extends AppCompatActivity {
ConstraintLayout tasarım;
private SharedPreferences sharedPreferences;
private Spinner spinner;
private ArrayList<String> renkler = new ArrayList<>();
private ArrayAdapter<String> veriAdaptoru;
String color;
tasarım=(ConstraintLayout)findViewById(R.id.tasarım);
spinner = findViewById(R.id.spinner);
renkler.add("beyaz");
renkler.add("mavi");
renkler.add("kırmızı");
renkler.add("yeşil");
veriAdaptoru = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, renkler);
spinner.setAdapter(veriAdaptoru);
sharedPreferences = this.getSharedPreferences("com.example.sondev", MODE_PRIVATE);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SharedPreferences prefs=getSharedPreferences("color",MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
String colorSec="";
if (position==0){
tasarım.setBackgroundColor(Color.WHITE);
colorSec="WHITE";
editor.putString("colour",colorSec);
editor.commit();
}
else if (position==1){
tasarım.setBackgroundColor(Color.BLUE);
colorSec="BLUE";
editor.putString("colour",colorSec);
editor.commit();
}
else if(position==2){
tasarım.setBackgroundColor(Color.RED);
colorSec="RED";
editor.putString("colour",colorSec);
editor.commit();
}else if (position==3){
colorSec="GREEN";
editor.putString("colour",colorSec);
editor.commit();
tasarım.setBackgroundColor(Color.GREEN);
}
else {
colorSec="GREEN";
editor.putString("colour",colorSec);
editor.commit();
tasarım.setBackgroundColor(Color.GREEN);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SharedPreferences prefs=getSharedPreferences("color",MODE_PRIVATE);
color=prefs.getString("colour","WHITE");
if (color.equals("BLUE")){
tasarım.setBackgroundColor(Color.BLUE);
}
else if(color.equals("RED")){
tasarım.setBackgroundColor(Color.RED);
}else{
tasarım.setBackgroundColor(Color.GREEN);
}

Related

get selected save item position from Spinner

I want to store the spinner position. This allows me to restore the spinner when the application is opened.
Currently, my code isn't working. It's saving the data, but when I open the application, the last item I clicked does not open.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
refRoomsNew.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
spinner = (Spinner)findViewById(R.id.spinnerMain);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, RoomsNew);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
String data = snapshot.getValue(String.class);
RoomsNew.add(data);
addListenerOnSpinnerItemSelection();
Integer spinnerNew = prefs.getInt("Spinner", 0);
// Log.d("Spinner", spinnerNew);
if(spinnerNew != null ) {
Log.d("spinnerNew", String.valueOf(spinnerNew));
spinner.setSelection(spinnerNew);
}
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
SharedPreferences.Editor editor = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE).edit();
editor.putInt("Spinner", indexValue);
editor.apply();
}
You have to set the position right after setting the adater. Something like:
spiner.setAdater();
SharedPreferences prefs = getSharedPreferences("...",Context.MODE_PRIVATE);
// If "Spinner" is not set, it will assign 0
Integer initialValue = prefs.getInt("Spinner", 0);
spinner.setSelection(initialValue);
Then, during onItemSelected, you just need to store the value:
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
SharedPreferences.Editor editor = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE).edit();
editor.putInt("Spinner", position);
editor.apply();
}

How manage multichoice list in ListView with toolbar in fragmentActivity

I want to manage a list in a listView using onLongClick.
I want to select multiple items and manage (when is selected) adding in the toolbar 1 botton (remove).
I try with this code:
public class FragmentFragment extends Fragment {
private ListView listView;
private List<Schede> list;
private SchedeAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object object= list.get(position);
Toast.makeText(getContext(), object.getName() + "Clicked", Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Object object = list.get(position);
view.setSelected(true);
return false;
}
});
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
return rootView;
}
public void remove(int position){
SharedPreferences pref = getActivity().getSharedPreferences("OBJECTS", Context.MODE_PRIVATE);
list.remove(position);
String listS = new Gson().toJson(list);
SharedPreferences.Editor edit = pref.edit();
edit.putString("OBJECTS", listS);
edit.apply();
adapter.notifyDataSetChanged();
}
public void refresh(){
SharedPreferences pref = getActivity().getSharedPreferences("OBJECTS", Context.MODE_PRIVATE);
String string = pref.getString("OBJECTS", null);
if (string != null){
Type type = new TypeToken<List<Object>>(){}.getType();
list = new Gson().fromJson(string, type);
adapter = new ObjectAdapter(getContext(), list);
listView.setAdapter(adapter);
}
}
#Override
public void onResume(){
super.onResume();
refresh();
}
}
...but don't allow me to select multiple items (I set different background color for selected items in xml).
The rest of code work correctly
Edit: post an example
Resolved: https://stackoverflow.com/a/12598337/6941150
Using in onCreate()...
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
...
}

How to save Spinner as Shared Preference?

I have been able to save Integers and Strings as Shared Preferences but have searched and cannot seem to be able to save a Spinners selected value as a shared preference?
spinner = (Spinner)findViewById(R.id.spnCalorieRange);
adapter = ArrayAdapter.createFromResource(this, R.array.Calorie_Range, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
long item = parent.getItemIdAtPosition(position);
String pos =spinner.getSelectedItem().toString();
//sharedPreferences.edit().putInt("PREF_SPINNER", position).commit();
if (item == 0){
deficitPercentage = .05;
}
else if (item ==1)
{
deficitPercentage = .1;
}
else if (item ==2)
{
deficitPercentage = .15;
}
else if (item ==3)
{
deficitPercentage = .2;
}
else if (item ==4)
{
deficitPercentage = .25;
}
else
{
deficitPercentage = .3;
}
editor.putString("pos", pos);
editor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
Accessing Shared Preferences here in OnCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diet);
spnCalorieRange = (Spinner) findViewById(R.id.spnCalorieRange);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Options", MODE_PRIVATE);
editor=pref.edit();
String strAvgCalIntake = Double.toString(dailyCalorieIntake);
String strGoal = Double.toString(goal);
strAvgCalIntake = loadSavedPreference("strAvgCalIntake");
strGoal = loadSavedPreference("strGoal");
etAverageCalorieIntake.setText(strAvgCalIntake);
etLoseWeight.setText(strGoal);
//mPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
//spinner.setSelection(mPrefs.getInt(PREF_SPINNER, 0));
// int selectedPosition = sharedpreferences.getInt("spinnerSelection", 0);
int selectedPosition = spnCalorieRange.getSelectedItemPosition();
sharedPreferences.getInt("spinnerSelection", selectedPosition);
((Editor) sharedPreferences).commit();
Here is the Button where I'm saving the shared Preferences:
The Strings are saving fine btw.
Button btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strAvgCalIntake = Double.toString(dailyCalorieIntake);
String strGoal = loadSavedPreference("strGoal");
spnCalorieRange = (Spinner) findViewById(R.id.spnCalorieRange);
strAvgCalIntake = etAverageCalorieIntake.getText().toString();
savePreference("strAvgCalIntake",strAvgCalIntake);
strGoal = etLoseWeight.getText().toString();
savePreference("strGoal",strGoal);
SharedPreferences spref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("deficitPercentage_key", Double.toString(deficitPercentage)); //
editor.commit();
If you have validated the deficitPercentage value, (and I hope you did)
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("deficitPercentage_key", Double.toString(deficitPercentage)); //
editor.commit();

How to save checkbox items to SharedPreferences?

I need to save values from the checkbox to shared preferences so that even after exiting, the checked boxes are still checked. Could anyone please show me how to solve this issue?
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.my_list);
adapter = new MyAdapter(this,getModel());
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
TextView label = (TextView) v.getTag(R.id.label);
CheckBox checkbox = (CheckBox) v.getTag(R.id.check);
Toast.makeText(v.getContext(), label.getText().toString() + " " + isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<Model> getModel() {
list.add(new Model("1"));
list.add(new Model("2"));
list.add(new Model("3"));
return list;
}
}
I made this class, use it:
public class SavePreferences {
private final static String MYAPP_PREFERENCES = "MyAppPreferences";
public void savePreferencesData(View view, String KEY, String TEXT) {
SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (TEXT != null && KEY != null) {
editor.putString(KEY, TEXT);
editor.commit();
}
}
private String loadPreferencesData(View view, String KEY){
SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
String data = prefs.getString(KEY, "No Data!");
return data;
}
}
And then:
savePreferencesData(View, "CheckBox1", "true");

how to remove list item or clearing listview using shared preferences?

I have following base adapter custom class, creating listview and items. but i want to remove all items from the list when I click reset button.
My code :
public class Scores extends Activity implements OnClickListener {
public static final String MY_PREFS_NAME = "PrefName";
SharedPreferences pref;
static String[] tempTime = new String[10];
static String[] tempScore = new String[10];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTime.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.mathmatch_score_format, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.time_text);
holder.text2 = (TextView) convertView
.findViewById(R.id.score_text);
/*final ImageView deleteButton = (ImageView)
convertView.findViewById(R.id.score_reset);
deleteButton.setOnClickListener(this);*/
convertView.setTag(holder);
//deleteButton.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(tempTime[position]);
holder.text2.setText(tempScore[position]);
return convertView;
}
static class ViewHolder {
TextView text1;
TextView text2;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mathmatch_score);
setUpViews();
pref = getSharedPreferences(MY_PREFS_NAME, 0);
strTime = pref.getString("high_score_times", "");
intScore = pref.getString("high_score_values", "");
tempTime = strTime.split(",");
tempScore = intScore.split(",");
Comparator<String> comparator = new CustomArrayComparator<String, String>(tempScore, tempTime);
Arrays.sort(tempTime, comparator);
Arrays.sort(tempScore, Collections.reverseOrder());
lv.setAdapter(new EfficientAdapter(this));
}
private void setUpViews() {
lv = (ListView) findViewById(R.id.list);
reset = (ImageView) findViewById(R.id.score_reset);
reset.setOnClickListener(this);
}
#Override
protected void onPause() {
super.onPause();
pref = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = pref.edit();
edit.putString("high_score_times", strTime);
edit.putString("high_score_values", intScore);
edit.commit();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.score_reset:
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setTitle("Reset");
alertbox.setMessage("Are you sure all time ans score are reset?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pref = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = pref.edit();
/*edit.remove("high_score_times");
edit.remove("high_score_values");*/
/*edit.remove(intScore);
edit.remove(strTime);
*/
//edit.clear();
edit.remove(MY_PREFS_NAME);
edit.commit();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
break;
default:
break;
}}}
My reset button is not including on a list.
I have tried this in yes button click event in above code but could not get any update. So what to do?
Thanks in advance.
using your listview instance get the list adapter like
urlist.setAdapter("pass your updated adapter with empty string array");
OR
you can also call notifyDataSetChanged(); to tell the list view that its data set is changed
For a start, your using your adapter wrong. Your adapter should be a wrapper around your data, not a facade used to expose data contained elsewhere in your code.
In your case your using it to access the two variables (very bad form to make these static):
static String[] tempTime = new String[10];
static String[] tempScore = new String[10];
On create your filling these variables from your shared preferences.
Then on your "Yes" your updating your preferences but no matter how much you press the "update" button on your adapter, it's still looking at those variables which haven't been updated.
If you want your "Yes" button to clear your list then you need to change the data which backs the adapter then tell the adapter that it has changed and to redraw itself.
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pref = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = pref.edit();
/**/
edit.remove(MY_PREFS_NAME);
edit.commit();
strTime = pref.getString("high_score_times", "");
intScore = pref.getString("high_score_values", "");
tempTime = strTime.split(",");
tempScore = intScore.split(",");
EfficientAdapter adapter = (EfficientAdapter)lv.getAdapter();
adapter.notifyDataSetChanged();
});
To clear List:
set tempTime and tempScore to empty array
tempTime= new String[0];
adapter.notifyDataSetChanged();
To Add/Remove Data :
Alter data source tempTime and tempScore accordingly and call adapter.notifyDataSetChanged();

Categories

Resources