2

I have a spinner in my android application and the spinner goes to the first item whenever I go to other fragment and come back. All I want is that the spinner should retain the value. Below is how I setup the spinner.

private void setupSpinner(){
    roundSpinnerMap = new HashMap<>();
    roundSpinnerItems = new ArrayList<>();
    //Get the day of the week in order to figure out which rounds and variables are needed.
    Calendar c = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy", Locale.US);
    Date d = null;
    try {
        d = format.parse(mDay);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    c.setTime(d);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
    //If the day is Sunday then dayOfWeek is 7, not 0.
    if(dayOfWeek == 0){
        dayOfWeek = 7;
    }
    for (Models.Round r:rounds) {
        //For each round get the completed and total amount.
        int[] partWhole = models.getCompletedOfTotal(r.getName(), mDay, dayOfWeek, nameText.getText().toString());
        String readable = r.getName() +" (Completed " + partWhole[0] + " of " + partWhole[1] + ")";
        //If there are none to complete, then do not show/add the option.
        if(!readable.contains("of 0")){
            roundSpinnerMap.put(readable, r.getName());
            roundSpinnerItems.add(readable);
        }
    }
    ArrayAdapter<String> roundAdapter = new ArrayAdapter<>(
            getActivity(), R.layout.simple_spinner_item, roundSpinnerItems
    );
    roundAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    roundSpinner.setAdapter(roundAdapter);
    roundSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String readable = roundSpinner.getSelectedItem().toString();
            mRound = roundSpinnerMap.get(readable);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

Below are my onCreate methods:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    models = new ModelsHandler(getActivity());
    if (getArguments() != null) {
        mHome = getArguments().getBoolean(ARG_HOME);
        mUser = getArguments().getString(ARG_USER);
        mFacility = getArguments().getString(ARG_FACILITY);
    }
    calendar = Calendar.getInstance();
    mDay = format.format(calendar.getTime());
    sharedPreferences = getActivity().getSharedPreferences(MainActivity.PREFERENCES, Context.MODE_PRIVATE);
    rounds = models.getAllRounds();
    rise = AnimationUtils.loadAnimation(getActivity(), R.anim.rise_vert);
    sink = AnimationUtils.loadAnimation(getActivity(), R.anim.sink_vert);
    if (mListener == null){
        mListener = (OnFragmentInteractionListener) getActivity();
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_splash, container, false);

    roundsButton = view.findViewById(R.id.roundsButton);
    calendarButton = view.findViewById(R.id.calendarButton);
    contactButton = view.findViewById(R.id.contactButton);
    syncMainButton = view.findViewById(R.id.syncMainButton);
    trendButton = view.findViewById(R.id.trendButton);
    prefSyncButton = view.findViewById(R.id.prefSyncButton);
    startSyncButton = view.findViewById(R.id.startSyncButton);
    contactDevButton = view.findViewById(R.id.contactDevButton);
    contactServiceButton = view.findViewById(R.id.contactServiceButton);
    roundSpinner = view.findViewById(R.id.roundSpinner);
    roundDateText = view.findViewById(R.id.roundDateText);
    errorRoundText = view.findViewById(R.id.roundsErrorText);
    nameText = view.findViewById(R.id.nameText);
    progressBar2 = view.findViewById(R.id.progressBar2);

    errorRoundText.setVisibility(View.GONE);
    nameText.setText(sharedPreferences.getString(MainActivity.USER_SESSION_KEY,""));

    progressBar2.setVisibility(View.GONE);
    roundDateText.setText(format.format(calendar.getTime()));
    roundDateText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchDatePicker();
        }
    });

    contactActionsOpen = false;
    syncActionsOpen = false;
    if(rounds == null || rounds.isEmpty()){
        errorRoundText.setVisibility(View.VISIBLE);
        UtilityPole.initDefaultRounds(models);
        rounds = models.getAllRounds();
        Toast.makeText(getContext(), getResources().getString(R.string.errorRound), Toast.LENGTH_LONG).show();
    }
    setupSpinner();
    initializeAnimationButtons();
    initializeButtonActions();

    return view;
}

I tried using the shared preference but that did not work(Maybe I don't know how to use it correctly as I am new to android.). Any help would be appreciated.

M.Shaikh
  • 250
  • 1
  • 3
  • 14
  • How about storing the last position of the spinner to your sharedpref then retrieve and set the position of your spinner at the end of `setupSpinner` method, make sure all the items already in the adapter before setting the position of your spinner. – glagarto Jul 05 '18 at 14:46
  • Thats what I am trying to do right now @dr3k – M.Shaikh Jul 05 '18 at 14:53

2 Answers2

0

You store it as a static value. Its been a while since I have worked with android api so this will not be too accurate. Just substitute the correct method calls and it would work

//have a private static field variable
private static int spinnerValue = 0;

private void getSpinner()
{
    spinnerValue = spinner.getCurrentValue();
}

private void setSpinner()
{
    soinner.setValue(spinnerValue);
}

This is because the static keyword makes a variable stay throughout all classes, even if the class has been destroyed via garbage collection.

What does the 'static' keyword do in a class?

So this is probably what you're looking for

Matt
  • 60
  • 10
0

I can't comment on your question so i am giving a General Answer

SAVE AND RETRIEVE VALUE IN SPINNER

enter image description here

Step1 - Save the IndexNumber of the saved value in the spinner locally in your application.

Step2 - Retrieve the saved IndexNumber in your onCreate method and use

setSelection method to set value to the spinner.

shyam
  • 1,084
  • 12
  • 20