【发布时间】:2017-02-25 12:12:46
【问题描述】:
这就是问题所在。在我的第二堂课中,我正在尝试加载 SharedPreferences。下面我还将包括我的第一堂课。
//set label for journal questions
public TextView journalQuestionLabel;
public int counter = 0;
SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
//TODO: Send saved preferences here
preferences = getSharedPreferences("grammarOption", MODE_PRIVATE);
int selection = preferences.getInt("grammarOption", -1);
Log.d("in onCreate", "preferences = " + selection);
}
当我测试它时,我的调试日志总是打印 -1。它不会加载我的共享首选项。我究竟做错了什么?
我已经尝试过这里和每个教程的其他答案,但它们不起作用。这是我设置和保存微调器首选项的代码。我已经检查过了,它正在工作。
private void setupSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
final ArrayAdapter grammarSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_grammar_options,
android.R.layout.simple_spinner_dropdown_item);
// Specify dropdown layout style - simple list view with 1 item per line
grammarSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//Apply the adapter to the spinner
grammarChoiceSpinner.setAdapter(grammarSpinnerAdapter);
//Create shared preferences to store the spinner selection
SharedPreferences preferences = getApplicationContext().getSharedPreferences
("Selection", MODE_PRIVATE);
editor = preferences.edit();
// Create the intent to save the position
grammarChoiceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//receive the string of the option and store it
int grammarOptionPosition = grammarChoiceSpinner.getSelectedItemPosition();
//put the string in the editor
editor.putInt("grammarOption", grammarOptionPosition);
editor.commit();
//make a toast so the user knows if it's not "select"
if (grammarOptionPosition != 0) {
Toast.makeText(getApplicationContext(), "Choice saved.",
Toast.LENGTH_SHORT).show();
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
@Override
public void onNothingSelected(AdapterView<?> parent) {
mGrammar = 0;
}
});
}
这里在onCreate()中调用
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
//find the spinner to read user input
grammarChoiceSpinner = (Spinner) findViewById(R.id.spinner);
setupSpinner();
【问题讨论】:
标签: android sharedpreferences spinner