简体   繁体   中英

Saving data when orientation changes / Write a string by default in Spinner

I have an activity in my app that it makes a search with some criteria and it has some spinner widgets to select them.

My problem is when orientation of my Android device changes, the activity restarts and it loses all criteria selected in Spinners and the results obtained from search.

I have tried save data using onSaveInstanceState(Bundle) and restore in onCreate method, and I get data succesfully but my problem is that I need to put this data in Spinner again when orientation changes and the activity restarts ... I have tested some ways but it was imposible:

1. Put the string saved at first of LinkedList loaded by Adapter: (NOT WORKING)

if (savedInstanceState != null) {
          list.add(0, stSaved); //stSaved is the string saved
}

2. Save the position of the string selected, and using the next Spinner's method: (NOT WORKING)

if (savedInstanceState != null) {
          spinner.setSelection(posSaved, true); //posSaved is the string's position to save
}

3. Another Spinner's method: (NOT WORKING)

if (savedInstanceState != null) {
          spinner.setPrompt(stSaved);
}

Moreover, there are 12 criteria and therefore 12 strings that they could be saved, plus the list with results from search, then, is better to use SharedPreferences than onSaveInstanceState(Bundle) ?

PD1. I save and get correctly data needed, but I can not put in Spinner by default when activity restarts. PD2. I can not use android:configChanges="orientation" because this activity has two fragments (criteria and results) and it is incompatible.

I hope you can help me, thanks so much.

protected void onSaveInstanceState(Bundle bundle) {
  super.onSaveInstanceState(icicle);
  bundle.putInt("selected_pos_spinnerX", spinnerX.getSelectedItemPosition());
}

and to restore values:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

//some code ...
//code to init spinner and load data ...

if(savedInstanceState!=null){
    spinnerX.setSelection(savedInstanceState.getint("selected_pos_spinnerX"));
}

}

regarding search results, you can either store them in local file or app preferences, based on the data structure and results you are dealing with.

you can serialize search results (as json) and store the json string in file, the parse it (if restoring screen) and load it in result view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM