我需要用户选择一家餐馆,有一个非常大的列表,有不同的选择。 然后我需要保存该选项,最好是像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。
答案 0 :(得分:1)
试试这个:
像这样添加SharedPreferences sharedPref = getSharedPreferences("resturantFile",Activity.MODE_PRIVATE)
而不是
SharedPreferences sharedPref = getSharedPreferences("resturantFile",0)
。
例如:保存方式
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();
在另一项活动中检索数据的方法:
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。