Общие настройки в другой деятельности / классе - PullRequest
0 голосов
/ 29 января 2012

Я написал класс для обработки общих настроек:

import android.preference.PreferenceManager;
import android.util.Log;
import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceHandler {

     Context mContext = null;

        public PreferenceHandler (Context context) {
            mContext = context;
        }

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);

        public void NewGamePrefs(){
             int GameTime=(Integer.parseInt(mContext.getString(R.string.gametime)));
             int Trivianten=(Integer.parseInt(mContext.getString(R.string.trivialocations)));
             SharedPreferences.Editor memory = preferences.edit();
             memory.putInt("GameTime" , GameTime);
             memory.putInt("Score", 0);
             GPSHandler MyGPS=new GPSHandler(mContext);
             memory.putString("StartLocation", MyGPS.getStartLocationID());
             memory.putString("NextLocation", MyGPS.getStartLocationID());
             memory.putString("EndLocation", MyGPS.getEndLocationID());
        commit();
            }

        public String getPreferenceString(String KEY){
            return preferences.getString(KEY, "nodata");
        }

        public int getPreferenceValue(String KEY){
            return preferences.getInt(KEY, -1);
        }

Если я вызываю этот класс из файла занятий:

PreferenceHandler GameMemory = новый PreferenceHandler (это);

GameMemory.NewGamePrefs ();

Я получаю исключение nullpointer, кто-нибудь знает, почему и как это решить?

Большое спасибо!

1 Ответ

3 голосов
/ 29 января 2012

Вы никогда не инициализируете preferences. Измените preferences и ваш конструктор на:

SharedPreferences preferences;

public PreferenceHandler (Context context) {
    mContext = context;
    preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
}
...