Android SharedReferences仅获取一个字符串
我试图使用SharedReferences来获取问题是否已回答,但它会获取所有问题(是否已回答)的最后一个问题的状态 有人能帮我弄清楚每个问题的状态吗 以下是我的申请代码:Android SharedReferences仅获取一个字符串,android,sharedpreferences,Android,Sharedpreferences,我试图使用SharedReferences来获取问题是否已回答,但它会获取所有问题(是否已回答)的最后一个问题的状态 有人能帮我弄清楚每个问题的状态吗 以下是我的申请代码: public class Question{ boolean answered; public static int id; String userAnswer; String QuestionP = LogoQuiz.QuestionP; public Question(int i
public class Question{
boolean answered;
public static int id;
String userAnswer;
String QuestionP = LogoQuiz.QuestionP;
public Question(int i, Context context){
SharedPreferences pref = context.getSharedPreferences(QuestionP, context.MODE_PRIVATE);
id = i;
answered = pref.getBoolean("answered"+i, false);
}
}
以及计算有多少个问题:
public class Main extends Activity {
public static ArrayList<Question> ques;
public static final String QuestionP = "QuestionSettings";
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = getSharedPreferences(QuestionP, MODE_PRIVATE);
Editor editor = pref.edit();
-------- activity ----------
-------- activity ----------
ques = new ArrayList<Question>();
for(int i = 0; i < QuestionsA.mPucIds.length; i++)
{
ques.add(new Question(i, Main.this));
CharSequence text = "";
if(pref.getBoolean("FirstRun", true))
{
text = "First Run";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
editor.putBoolean("FirstRun", false);
editor.putBoolean("answered"+i, false);
editor.commit();
}
}
}
}
您已经将id变量声明为static,这就是它获取最后一个值的原因,删除该修饰符,就完成了 编辑好吧,我假设当问题得到回答时,您将从问题实例中获得id实例字段,然后通过该id您可以
editor.putBoolean("answered"+id, true).commit();
首先,把
editor.commit()
在for循环之外。它不需要承诺那么多次。此外,通过放置一个
Log.d("i value", Integer.toString(i));
在问题类中,确保您收到要检查的正确值。代码似乎很好
编辑:
改变
int id = Question.id;
到
静态变量“id”对于问题对象的所有副本都是相同的
我建议阅读Java中的静态变量和方法 对变量使用
静态
修饰符时,无论创建该类的多少实例,该变量的值在所有实例中都将保持不变
因此,请尝试删除id
的static
修饰符,然后使用如下构造函数调用:
int id = new Question(i, Main.this).id;
这样就创建了一个新实例。但是当我删除它时,我得到“无法对非静态字段Question.id进行静态引用”,因为您不能使用Question类引用id实例变量,您希望它的实例显示'Question'(Question.id)。我编辑了我的答案也许会有帮助。如果我删除了“静态”,有没有办法得到它?是,如果您不想获取最后一个值,您必须移除静态修饰符。当我移除静态修饰符时,我无法对非静态字段Question.ids进行静态引用,直到出现相同的问题。我的建议是从首选项记录键,以便您可以检查是否以正确的方式保存它们
int id = new Question(i, Main.this).id
int id = new Question(i, Main.this).id;