java - 在微调器中获取用户选择,将其存储在sharedPreferences中,并在另一个 Activity 中使用它

标签 java android sharedpreferences android-spinner

我需要用户选择一家餐厅,得到了一个相当大的列表,其中有不同的选择。 然后我需要保存该选择,最好保存在共享首选项之类的文件中。并在另一个 Activity 中使用它来显示 Excel 文档中的一些数据。

目前我的代码如下所示:

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

并在另一个 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);

我只是使用textView来查看它保存的内容,目前它只显示-1

编辑:不妨添加这个,userChoice 值为 0。

最佳答案

试试这个:

像这样添加 SharedPreferences sharedPref = getSharedPreferences("resturantFile",Activity.MODE_PRIVATE) 而不是
SharedPreferencessharedPref = getSharedPreferences("resturantFile",0)

例如:保存方式

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

在另一个activity中检索数据的方式:

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

如果这不适合您,请尝试以下方法: 将默认值-1更改为0,

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

有关更多信息,请使用此 question

关于java - 在微调器中获取用户选择,将其存储在sharedPreferences中,并在另一个 Activity 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24131348/

相关文章:

java - 尝试加载资源时 clojure.lang.Compiler 中的 NPE

android - 在 gradle 中添加 kapt androidx room 会导致数据绑定(bind)错误

android - 从我的应用程序启动 android 秒表

php - JSON解析android中共享首选项期间出错

java - toArray(T[] a) 和 toArray() 之间的区别

java - 为什么我的 swagger 不能在 java 中使用 springboot?

java:while循环-在进入花括号之间的语句之前使用分号的语句?

android - onSaveInstanceState 回调如何保存一个 SpannableString

android - 我无法从我的模块引用 SharedPreferences

flutter - 如何在 Flutter 中使用 SharedPreferences 和 Injectable?