简体   繁体   中英

Taking user selection in a spinner, storing it in sharedPreferences, and using it in another activity

I need the user to choose a restaurant, got a pretty large list with different selections. I then need to save that choice, preferably in something like sharedPreferences. And use it in another activity to display some data from an excel document.

currently my code looks like this:

in onCreate:

resturantSpinner = (Spinner) findViewById(R.id.resturantSpinner);
     // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.resturant_arrays, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
   // Apply the adapter to the spinner
    resturantSpinner.setAdapter(adapter);

onItemSelected:

public void onItemSelected(View view) {
      int userChoice = resturantSpinner.getSelectedItemPosition();
      SharedPreferences sharedPref = getSharedPreferences("resturantFile",0);
      SharedPreferences.Editor prefEditor = sharedPref.edit();
      prefEditor.putInt("userChoiceSpinner", userChoice);
      prefEditor.commit();
}

And retrieving the data, in another activity:

resturantTextView = (TextView) findViewById(R.id.resturantChoice);

    Intent intent = getIntent();

    SharedPreferences sharedPref = getSharedPreferences("resturantFile",MODE_PRIVATE);
    int resturantChoice = sharedPref.getInt("userChoiceSpinner",-1);

    resturantTextView.setText("" + resturantChoice);

I just use the textView to see what it saves like, and currently it just shows -1

edit: might as well just add this, userChoice value is 0.

Try this:

Add like this SharedPreferences sharedPref = getSharedPreferences("resturantFile",Activity.MODE_PRIVATE) instead of
SharedPreferences sharedPref = getSharedPreferences("resturantFile",0) .

For example: The way to save

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();

The way to retrieve data in another activity:

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);

If that is not working for you then try this one: Change the default value -1 to 0,

int myIntValue = sp.getInt("your_int_key", 0);

For more information use this question .

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