[英]Taking user selection in a spinner, storing it in sharedPreferences, and using it in another activity
我需要用戶選擇一家餐館,並獲得了很多不同選擇的清單。 然后,我需要保存該選擇,最好保存在諸如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。
嘗試這個:
像這樣添加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);
有關更多信息,請使用此問題 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.