Search code examples
androidlibgdxpreferences

Android libgdx preferences not working


Probably a stupid question, but what do I have to change to make this code work:

package com.hobogames.WizardsDuel;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;

public class GameData {
    public static String version = "1.0.0";

    public static String data[] = {"version"};
    public static final int VERSION = 0;

    public static Preferences prefs = Gdx.app.getPreferences("WizWars");
    public static boolean played = (!prefs.get().isEmpty());

    public static String getString(int key){
        return prefs.getString(data[key]);
    }

    public static void storePrefs(){
        prefs.putString(getString(VERSION),version);
        prefs.flush();
    }
}

The part in particular that isn't working is that "played" is false every time on an android device. On desktop it's true after the first play.


Solution

  • I suspect you're getting bitten by the static state behaving differently in Android and on your Desktop. Are you sure the VM exits when you exit the app on Android? If you restart your app quickly on Android, the system will reuse the same Dalvik VM for the new Activity. Since the static boolean is already initialized, the initialization isn't re-run. If you remove the static so this stuff gets re-run when GameData is created (presumably instances of it are not being stored in static variables) you should get farther.

    See http://bitiotic.com/blog/2013/05/23/libgdx-and-android-application-lifecycle/