讨论共享偏好

时间:2012-04-21 10:03:01

标签: android eclipse

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

quizactivitysplashactivitygameactivitymenuactivitysettingsactivityhelpactivitysplashactivity延长quizactivity quizactivity延长Activity

我在SharedPreferences中实施了quizactivity.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 -----------------------
你可以帮帮我吗,我不认为这是一个愚蠢的问题

2 个答案:

答案 0 :(得分: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();

    }
}

答案 1 :(得分:1)

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

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

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

有关偏好的更多信息,请参阅this