【发布时间】:2014-06-10 01:04:46
【问题描述】:
我需要用户选择一家餐厅,得到一个包含不同选择的相当大的列表。 然后我需要保存该选择,最好保存在 sharedPreferences 之类的东西中。并在另一个活动中使用它来显示 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();
}
在另一个活动中检索数据:
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。
【问题讨论】:
-
你能调试一下看看 userChoice 有什么价值吗?
-
userCoice 值为 0..
-
在进行第二个活动之前,您是否在第一个活动的其他任何地方调用 sharedPref.edit() ?调用 .edit() 会重置 sharedPref 编辑器。
标签: java android sharedpreferences android-spinner