我在Android Studio中使用SharedPreferences时遇到两个错误:
错误:找不到符号变量pref
错误:找不到符号类编辑器
我试图让它保存添加到SharedPreference的问题,然后在它返回活动时检索它。
我主要是从网站上复制我的代码,所以这可能是问题的一部分。
我的代码:
package com.example.sylvie.dogwise;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.content.SharedPreferences;
public class Questions extends AppCompatActivity {
ListView listview;
String[] ListElements = new String[]{
"How much food should I feed my dog?",
"How do I teach my dog to sit?"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
listview = (ListView) findViewById(R.id.QuestionsList);
final List<String> ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
final ArrayAdapter<String> adapter = new ArrayAdapter<String>
(Questions.this, android.R.layout.simple_list_item_1, ListElementsArrayList);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
String newquestion=pref.getString("key_question", null);
ListElementsArrayList.add(newquestion);
adapter.notifyDataSetChanged();
Bundle newQuestion = getIntent().getExtras();
if (newQuestion == null) {
return;
}
final String QuestionName = newQuestion.getString("QuestionName");
ListElementsArrayList.add(QuestionName);
adapter.notifyDataSetChanged();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("key_question", QuestionName);
editor.commit();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(view.getContext(), Question_1.class);
startActivityForResult(myIntent, 0);
}
if (position == 1) {
Intent myIntent = new Intent(view.getContext(), Question_2.class);
startActivityForResult(myIntent, 0 );
}
if (position == 2) {
Intent myIntent = new Intent(view.getContext(), Question_Asked.class);
myIntent.putExtra("QuestionTitle", QuestionName);
startActivityForResult(myIntent, 0);
}
}
});
}
;
public void backHomeOnClick(View view) {
Intent b = new Intent(this, HomeScreen.class);
startActivity(b);
}
public void askAQuestionOnClick(View view) {
Intent i = new Intent(this, AskAQuestion.class);
startActivity(i);
}
;
}
谢谢:)
答案 0 :(得分:1)
你必须正确使用它 -
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
editor.putString("key_question", QUESTION_NAME);
editor.apply();
你需要在pref.getString调用之上移动Shared pref声明,否则它将无法检测到pref。
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
String newquestion=pref.getString("key_question", null);