我需要用户选择一家餐厅,得到了一个相当大的列表,其中有不同的选择。 然后我需要保存该选择,最好保存在共享首选项之类的文件中。并在另一个 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/