get selected save item position from Spinner - android

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

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 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 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

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 remove SharedPreferences from Array

I have problem with removing items from ArrayList. I tried it maybe 100 times but I can't fix it. Saving to list isn't problem but it's very hard to remove for me.
When I remove SharedPrefs key (position) It's good first time but if I first time remove first position it's deleted from list but its still in preferences so when I try to remove first position second time I cant remove it because there is still saved preference with value "" but I need to remove this preference totally that first position have to contain preferences with value on second position not "".
I tried to make some images for better understanding.
Thats before remove 1st position:
And this is after remove 1st position
There is my CustomListAdapter class
public class CustomListAdapterInterests extends ArrayAdapter < String > {
private final Activity context;
private final ArrayList < String > mItemInterest;
public CustomListAdapterInterests(Activity context, ArrayList < String > itemInterest) {
super(context, R.layout.list_item_interests, itemInterest);
this.context = context;
this.mItemInterest = itemInterest;
}
#Override
public int getCount() {
return mItemInterest.size();
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item_interests, null, true);
TextView itemInterestTV = (TextView) rowView.findViewById(R.id.textInterest);
itemInterestTV.setText(mItemInterest.get(position));
return rowView;
}
}
And here is my fragment
public class InterestsFragment extends BaseFragment {
private ArrayList < String > mInterestList;
private static final int MAX_STORED_LINES_INTERESTS = 50;
private FloatingActionButton plusInterestsBTN;
private CustomListAdapterInterests adapterInterests;
private ListView listInterests;
private EditText interestET;
private Button confirmInterestBTN;
public SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_interests, container, false);
plusInterestsBTN = (FloatingActionButton) v.findViewById(R.id.plusInterests);
sharedPreferences = getActivity().getSharedPreferences(Constants.PREFERENCES_INTERESTS, Context.MODE_PRIVATE);
mInterestList = new ArrayList < String > ();
loadInterestFromPreferences(mInterestList);
adapterInterests = new CustomListAdapterInterests(getActivity(), mInterestList);
listInterests = (ListView) v.findViewById(R.id.listViewInterests);
listInterests.setAdapter(adapterInterests);
listInterests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > arg0, View v, int position, long arg3) {
if (sharedPreferences.contains(Constants.INTEREST + position)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}
}
});
listInterests.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {#Override
public boolean onItemLongClick(AdapterView <? > arg0, View arg1,
final int position, long id) {
onShowDialogSetItem(position);
return true;
}
});
plusInterestsBTN.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
onShowDialogAddItem();
}
});
listInterests.setOnScrollListener(new AbsListView.OnScrollListener() {#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = plusInterestsBTN.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationXBy(350);
} else {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationX(btn_initPosY);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
return v;
}
private void loadInterestFromPreferences(ArrayList < String > mInterestList) {
for (int x = 0; x < 5; x++) {
String interests = sharedPreferences.getString(Constants.INTEREST + x, Constants.DEFAULT);
Toast.makeText(getActivity(), interests, Toast.LENGTH_SHORT).show();
if (interests != "") {
mInterestList.add(interests);
}
}
}
private void onShowDialogSetItem(final int position) {
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
final EditText interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
Button confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
TextView title = (TextView) dialogInterest.findViewById(R.id.textView2);
title.setText("Edit Interest");
interestET.setText(mInterestList.get(position));
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("2", "" + position);
String interest = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
mInterestList.set(position, interestET.getText().toString());
Toast.makeText(getActivity(), "Upravené: " + interests, Toast.LENGTH_SHORT).show();
adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
}
private void onShowDialogAddItem() {
if (mInterestList.size() >= MAX_STORED_LINES_INTERESTS) {
return;
}
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = listInterests.getAdapter().getCount();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
Toast.makeText(getActivity(), "Přidané: " + interests, Toast.LENGTH_SHORT).show();
mInterestList.add(interestET.getText().toString());
//adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
adapterInterests.notifyDataSetChanged();
}
}
Thank you for help. Sorry for my English. If do you will help me I can do any material design app icon for you or google play designs. Thank you. If there is few informations please say me.
I think if you save all of your string list to single property of preferences will make it easy to manage.
see this sample:
//for save
StringBuilder sb = new StringBuilder();
for (String interest : mInterestList) {
sb.append(interest).append(",");
}
prefsEditor.putString("MyInterests", sb.toString());
prefsEditor.commit();
//for read
String [] interests= sharedPreferences.getString("MyInterests");
mInterestList = new ArrayList<String>(Arrays.asList(interests));
in every change to your mInterestList just save it again. no need to remove and adding. change your mInterestList and save again in shared preferences.
Looks to me like your adapter runs off of mInterestList .
I don't see you removing the data item from mInterestsList when your remove the Preference?
Rather than checking whether shared preferences contains, see if it is set to null instead or not, that is do,
if (sharedPreferences.getString(Constants.INTEREST + position)!=null) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}

Categories

Resources