Java 在微调器中获取用户选择,将其存储在SharedReferences中,并在其他活动中使用

Java 在微调器中获取用户选择,将其存储在SharedReferences中,并在其他活动中使用,java,android,sharedpreferences,android-spinner,Java,Android,Sharedpreferences,Android Spinner,我需要用户选择一家餐厅,得到了一个有不同选择的相当大的列表。 然后我需要保存这个选择,最好是在类似SharedReferences的地方。并在另一个活动中使用它来显示excel文档中的一些数据 当前我的代码如下所示: 在onCreate中: resturantSpinner = (Spinner) findViewById(R.id.resturantSpinner); // Create an ArrayAdapter using the string array and a def

我需要用户选择一家餐厅,得到了一个有不同选择的相当大的列表。 然后我需要保存这个选择,最好是在类似SharedReferences的地方。并在另一个活动中使用它来显示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);
并在另一个活动中检索数据:

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

    Intent intent = getIntent();

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

    resturantTextView.setText("" + resturantChoice);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);
我只是使用textView查看它的保存方式,目前它只显示-1

编辑:不妨添加此选项,userChoice值为0。

尝试以下操作:

像这样添加
SharedReferences SharedReferences=GetSharedReferences(“resturantFile”,Activity.MODE\u PRIVATE)
而不是
SharedReferences SharedReferences=GetSharedReferences(“resturantFile”,0)

例如:节约的方法

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();
在另一个活动中检索数据的方法:

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

    Intent intent = getIntent();

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

    resturantTextView.setText("" + resturantChoice);
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);

有关更多信息,请使用此

您可以调试并查看userChoice的值是多少吗?userCoice的值是0。在转到第二个活动之前,是否在第一个活动中的任何其他位置调用sharedPref.edit()?调用.edit()将重置sharedPref编辑器。在保存到SharedPreferences之前,是否检查userChoice变量以确保它不是空的?很高兴听到您解决了它。如果这个答案帮助你解决了这个问题,请你将它标记为已接受的答案。