How to save Spinner as Shared Preference? - android

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();

Related

How to save background with sharedPreferences

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);
}

how to override getItemPosition in PagerAdapter

I am trying to update position value by overriding getItemPosition() but it is not working. Please help..
Code here -
#Override
public int getItemPosition(Object object) {
super.getItemPosition(object);
SharedPreferences pos = ctx.getSharedPreferences("forposition", MODE_PRIVATE);
int tom = pos.getInt("pos",0);
Log.d("posTom","value : "+tom );
return tom;
}
This is instantiateItem() method :
public Object instantiateItem(#NonNull ViewGroup container, int position) {
inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.swipe,container,false);
ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
SharedPreferences sp = ctx.getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if((sp.getString("array", null)) == null) {
String temp = Arrays.toString(count);
editor.putString("array", temp);
editor.commit();
}
String fetch = sp.getString("array", null);
Log.d("positionlist ","value : "+fetch);
fetch = fetch.substring(1, fetch.length()-1);
String strarray[] =fetch.split(", ") ;
/* SharedPreferences spt= ctx.getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
int post = spt.getInt("pos",1);*/
Log.d("position","value : "+position );
Log.d("posvalue","value : "+strarray[position] );
Log.d("poscondition","value : "+(Integer.parseInt(strarray[position]) == 0) );
if (Integer.parseInt(strarray[position]) == 0) {
BackgroundTask task = new BackgroundTask(this);
task.execute();
imageView.setImageResource(img[position]);
container.addView(v);
strarray = setValue(position, strarray);
String temp1 = Arrays.toString(strarray);
editor.putString("array", temp1);
editor.commit();
} else {
imageView.setImageResource(img[position]);
container.addView(v);
}
SharedPreferences pos = ctx.getSharedPreferences("forposition", MODE_PRIVATE);
SharedPreferences.Editor poseditor = pos.edit();
poseditor.putInt("pos", position);
poseditor.commit();
return v;
}
Please give solution how to update position from instantiateItem() method.

How to save spinner to saved/shared preferences

I am able to save Strings in my saved preferences but having difficulty saving my spinner.
public class Diet extends Activity {
private SharedPreferences sharedPreferences;
Spinner spnCalorieRange;
Here is my onCreate:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String strAge = Integer.toString(age);
String strHeight = Integer.toString(height);
String strWeight = Integer.toString(weight);
name = loadSavedPreference("name");
strAge = loadSavedPreference("strAge");
strHeight = loadSavedPreference("strHeight");
strWeight = loadSavedPreference("strWeight");
etName.setText(name);
etAge.setText(strAge);
etHeight.setText(strHeight);
etWeight.setText(strWeight);
This is my Spinner in my onCreate:
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
}
});
This is in my onCLick behind a button, where I'm saving the strings and spinner
age = (int) Double.parseDouble(etAge.getText().toString());
height = (int) Double.parseDouble(etHeight.getText().toString());
weight = (int) Double.parseDouble(etWeight.getText().toString());
//Save Preferences
String strAge = Integer.toString(age);
String strHeight = Integer.toString(height);
String strWeight = Integer.toString(weight);
name = etName.getText().toString();
savePreference("name",name);
strAge = etAge.getText().toString();
savePreference("strAge",strAge);
strHeight = etHeight.getText().toString();
savePreference("strHeight",strHeight);
strWeight = etWeight.getText().toString();
savePreference("strWeight",strWeight);:
You can't save the actual spinner object to shared prefs, but you can save all of the values that make the spinner work its magic and next time you create the spinner, just apply those values
In your onItemSelected place:
int spinnerPosition = spinner.getSelectedItemPosition();
saveSpinnerPosition(spinnerPosition);
Save method
public void saveSpinnerPosition(int position){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
prefEditor.putInt("spnCalorieRange",position);
prefEditor.apply();
}
Load method
public void loadSpinnerPosition{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int position= sharedPreferences .getInt"spnCalorieRange",-1);
if(spinnerValue > -1)
// set the value of the spinner
spinner.setSelection(position);
}
To put spinners back to position, call loadSpinnerPosition in your onCreate
------------------------------------------------------------------------------------------------------------------------------------
Edit:
because I noticed this post is also your question, u can also do everything at once:
At the top of your activity:
int spinnerPosition;
In your onItemSelected place:
spinnerPosition = spinner.getSelectedItemPosition();
Save method
public void saveMethod(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("Gender", radioSexButton.isChecked());
editor.putBoolean("Male", rdoMale.isChecked());
prefEditor.putInt("spnCalorieRange",spinnerPosition);
prefEditor.apply();
}
Load method
public void loadMethod(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int position= sharedPreferences .getInt"spnCalorieRange",-1);
radioSexButton.setChecked(sharedPreferences.getBoolean("Gender", false));
rdoMale.setChecked(sharedPreferences.getBoolean("Male", false));
if(spinnerValue > -1)
// set the value of the spinner
spinner.setSelection(position);
}
Then call saveMethod() when u want to save all your states, and call loadMethod() when u wanna load all your states
Should help u out

Adding favorite button in list view

I have a listview which has a favorite button for every list item which when clicked should add the list item to another activity called my fav9rites. I am using a Baseadapter for the listview and Sharedpreference for adding favorites.
When I click the favorite button, the list view item is getting added in the my favorites activity but I am facing the following problems:
1)the favorite button when clicked should turn dark indicating that the list item is added to favorites. This happens but when I close the activity and come back again the button reverts back instead of being dark
2)on long press on list item in my favorites activity , the list item should be removed from the favorites but this is not happening.
Hope everyone understand my question
My code
my base adapter
public View getView(final int position, View view, ViewGroup parent)
{
final ViewHolder holder;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.beg_list_item,null);
holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
// holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
holder.favoriteImg = (ImageView) view.findViewById(R.id.favbtn);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
CodeList code = (CodeList) getItem(position);
holder.listHeading.setText(codeList.get(position).getListHeading());
imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
holder.alphabetList);
// holder.listHash.setText(codeList.get(position).getListHashTags());
if (checkFavoriteItem(code)) {
holder.favoriteImg.setImageResource(R.drawable.favorite);
holder.favoriteImg.setTag("yes");
} else {
holder.favoriteImg.setImageResource(R.drawable.unfavorite);
holder.favoriteImg.setTag("no");
}
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
final ImageView favoritesbutton = (ImageView) view.findViewById(R.id.favbtn);
favoritesbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String tag = favoritesbutton.getTag().toString();
if(tag.equalsIgnoreCase("no")){
shrdPrefence.addFavorite(context, codeList.get(position));
Toast.makeText(context, R.string.fav_added, Toast.LENGTH_SHORT).show();
favoritesbutton.setTag("yes");
favoritesbutton.setImageResource(R.drawable.favorite);
}else{
shrdPrefence.removeFavorite(context, codeList.get(position));
favoritesbutton.setTag("no");
favoritesbutton.setImageResource(R.drawable.unfavorite);
Toast.makeText(context, R.string.fav_removed, Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
//Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(CodeList checkCode) {
boolean check = false;
List<CodeList> favorites = shrdPrefence.getFavorites(context);
if (favorites != null) {
for (CodeList code : favorites) {
if (code.equals(checkCode)) {
check = true;
break;
}
}
}
return check;
}
public void add(CodeList code) {
codeList.add(code);
notifyDataSetChanged();
}
public void remove(CodeList code) {
codeList.remove(code);
notifyDataSetChanged();
}
sharedpreference.java
public class SharedPreference
{
public static final String PREFS_NAME = "MY_APP";
public static final String FAVORITES = "code_Favorite";
public SharedPreference(){
super();
}
public void saveFavorites(Context context, List<CodeList> favorites){
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, CodeList code){
List<CodeList> favorites = getFavorites(context);
if(favorites == null)
favorites = new ArrayList<CodeList>();
favorites.add(code);
saveFavorites(context,favorites);
}
public void removeFavorite(Context context, CodeList code) {
ArrayList<CodeList> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(code);
saveFavorites(context, favorites);
}
}
public ArrayList<CodeList> getFavorites(Context context) {
SharedPreferences settings;
List<CodeList> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
CodeList[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CodeList>(favorites);
} else
return null;
return (ArrayList<CodeList>) favorites;
}
}
my favorite..java
public class MyFavActivity extends Activity
{
SharedPreference shrdPrfence;
List<CodeList> favorites;
FinalAdapter fnlAdpter;
Context context = this.context;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fav_layout);
shrdPrfence = new SharedPreference();
favorites = shrdPrfence.getFavorites(MyFavActivity.this);
if(favorites == null){
Dialog dialog = new Dialog(MyFavActivity.this);
dialog.setTitle(R.string.nofav_title);
dialog.show();
}else{
if(favorites.size() == 0){
Dialog dialog = new Dialog(MyFavActivity.this);
dialog.setTitle(R.string.nofav_title);
dialog.show();
}
ListView favList = (ListView) findViewById(R.id.fav_layoutListView);
if(favorites != null){
fnlAdpter = new FinalAdapter(MyFavActivity.this, favorites);
favList.setAdapter(fnlAdpter);
favList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favbtn);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
shrdPrfence.addFavorite(MyFavActivity.this,
favorites.get(position));
Toast.makeText(
MyFavActivity.this,
R.string.fav_added,
Toast.LENGTH_SHORT).show();
button.setTag("yes");
button.setImageResource(R.drawable.favorite);
} else {
shrdPrfence.removeFavorite(MyFavActivity.this,
favorites.get(position));
button.setTag("no");
button.setImageResource(R.drawable.unfavorite);
fnlAdpter.remove(favorites.get(position));
Toast.makeText(
MyFavActivity.this,
R.string.fav_removed,
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
}
}
Actually your saveFavorites() method works fine, becuse you just call gson.toJson() ( convert everything in json format)
You want to get saved data with SharedPreferences and you have used this line to retrieve your data
gson.fromJson(jsonFavorites, CodeList[].class);
you never get your saved data with this line, because you save a list and you want to retrieve an array (!)
If you saved a list you must retrive your data with a list token. And you need this line
gson.fromJson(jsonFavorites,new TypeToken<ArrayList<CodeList>>() {}.getType());
I think this will solve your question. Good luck.

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");

Categories

Resources