3

I'm doing an Android app which can get data from a web service & load it into spinner. I need to maintain the selected data state of the spinner while I go to some screen & come back. For example, if I'm getting data from the web service as 1.apple 2.orange 3.grapes & loading it into the spinner, then I select orange. When I go to some other screen & come back, the selected spinner data should be orange. But it again loads data from the server into the spinner. Can anybody help me to resolve this?

My code:

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //... if (Constants.SPINNER != null ) { spinner.setSelection( Constants.SPINNER); } else { //WebCall here for getting data } //... spinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int arg2, long arg3) { Constants.SPINNER = spinner.getSelectedItemPosition(); 

In Constant class:

public static Integer SPINNER=""; 
0

3 Answers 3

2

You can follow the below procedure:

You need to save state of your spinner so this would be helpful to you.

1.) Apply this after creating spinner object

sectionNameSpinner.setSelection(getPersistedItem()); 

2.) Create these methods according to you to save the state of your spinner selected item

private int getPersistedItem() { String keyName = makePersistedItemKeyName(); return PreferenceManager.getDefaultSharedPreferences(this).getInt(keyName, 0); } protected void setPersistedItem(int position) { String keyName = makePersistedItemKeyName(); PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(keyName, position).commit(); } private String makePersistedItemKeyName() { return currentUserName + "_your_key"; } 

3.) Set its state as the spinner selection changed:

sectionNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View view, int position, long itemId) { setPersistedItem(position); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); 
Sign up to request clarification or add additional context in comments.

Comments

0

When you "go to some other screen" you should do so via a new activity. Then, after you finish that new activity, the spinner selection activity will resume and the selection state will be as it was prior to starting the second activity.

Comments

0
  • Make sure you are not hitting the webservice in OnResume() of your activity.
  • Make sure you are not finishing the current activity by calling finish() before proceeding to the next activity.
  • And check whether data available or not before web hit (here you can avoid unnecessary web hits)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.