-2

我正在24 小时内为 Sams Android Development学习 Android 开发。我正在实现一个名为 theredone 的游戏,其中包含以下活动:

quizactivity, splashactivity, gameactivity, menuactivity, settingsactivity, helpactivity. splashactivity延伸quizactivityquizactivity延伸Activity

SharedPreferencesquizactivity.java.

package com.androidbook.triviaquiz6;

import android.app.Activity;
import android.content.SharedPreferences;

public class QuizActivity extends Activity {
    public static final String GAME_PREFERENCES = "GamePrefs";

    private SharedPreferences myPrefs; //Syntax error on token ";", { expected after this token -//----------------------------


   myPrefs = Actionactivity.this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
   SharedPreferences.Editor prefsEditor = myPrefs.edit(); 
   prefsEditor.putString("key name", "key valuse"); 
   prefsEditor.commit(); 


   //this one to read data  
    myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); 

    myPrefs.getString("key name", "") ;
}//Syntax error, insert "}" to complete ClassBody -----------------------

你能帮我吗?我不认为这是一个愚蠢的qs

4

2 回答 2

1

您正在引用Actionactivity活动中的QuizActivity活动。Actionactivity 尚未实例化,您正在getSharedPreferences使用它打开一个。

getSharedPreferences 方法属于上下文方法,对于当前活动,您可以引用this实例来调用此getSharedPreferences方法。

如果您不想使用活动的上下文,那么您可以application context通过调用来使用getApplicationContext().

有关偏好的更多信息,您可以参考这里

于 2012-04-21T10:24:00.833 回答
1

您可以使用以下代码作为共享首选项的参考::::并且在您的代码中您没有 oncreate 方法

//Retrive value from SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences(GAME_PREFERENCES , android.content.Context.MODE_WORLD_WRITEABLE);
String value =  preferences.getString(key, null);


//Save value in SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences(GAME_PREFERENCES , android.content.Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.commit();

更新:::

package com.androidbook.triviaquiz6;

import android.app.Activity;
import android.content.SharedPreferences;

public class QuizActivity extends Activity {
    public static final String GAME_PREFERENCES = "GamePrefs";
    private SharedPreferences myPrefs;
    protected void onCreate(Bundle savedInstanceState) {
    ....

    //this one data set in SharedPreferences file

    myPrefs = Actionactivity.this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("ket name", "key valuse");
    prefsEditor.commit();

    }
}
于 2012-04-21T10:05:06.207 回答