我正在制作一个 android java 游戏。但我有点坚持获取我保存的性别字符串。
在我的 GameGameActivity 类中,我可以接收性别。
public class GameGameActivity extends GameActivity{
SharedPreferences mGameSettings;
public String mGender;
MainGamePanel mGamePanel;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
Log.d("myTag", "View added");
checkGender();
}
private void checkGender(){
if (mGameSettings.contains(GAME_PREFERENCES_GENDER)) {
if(mGameSettings.getInt(GAME_PREFERENCES_GENDER, 0) == 2){
mGender = "Female";
Log.d("myTag","gender: " +mGender );
}else{
mGender = "Male";
Log.d("myTag","gender: " +mGender );
}
}
}
但是所有的魔法都发生在我的 MainGamePanel 中。我想知道里面是什么性别。我尝试了很多方法,但它总是给我一个空指针异常。这是我的 MainGamePanel。(只有几行)
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback{
public MainGamePanel(Context context, AttributeSet attributeSet){
super(context, attributeSet);
background = BitmapFactory.decodeResource(getResources(),R.drawable.bg_game_boy);
getHolder().addCallback(this);
createContent();
thread = new MainThread(getHolder(), this);
setFocusable(true);
}
这是我保存性别等的课程。我可以在其他活动中访问它们,但它们都扩展了这个类:
import android.app.Activity;
public class GameActivity extends Activity{
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_NICKNAME = "Nickname"; // String
public static final String GAME_PREFERENCES_EMAIL = "Email"; // String
public static final String GAME_PREFERENCES_PASSWORD = "Password"; // String
public static final String GAME_PREFERENCES_DOB = "DOB"; // Long
public static final String GAME_PREFERENCES_GENDER = "Gender"; //
public static final String GAME_PREFERENCES_SCORE = "80"; // int
public static final String DEBUG_TAG = "Activity Log";
public static final String TAG = GameActivity.class.getSimpleName();
}
我不知道如何在我的主游戏面板中阅读性别偏好。有人可以告诉我或将我推向正确的方向吗?
谢谢
我在命令之后尝试了这种方式:它说:方法 getSharedPreferences(String, int) 未定义 MainGamePanel 类型
SharedPreferences mGameSettings;
public MainGamePanel(Context context, AttributeSet attributeSet){
super(context, attributeSet);
background = BitmapFactory.decodeResource(getResources(),R.drawable.bg_game_boy);
getHolder().addCallback(this);
createContent();
thread = new MainThread(getHolder(), this);
setFocusable(true);
mGameSettings = getSharedPreferences(mGameActivity.GAME_PREFERENCES, Context.MODE_PRIVATE);
}