Pass a single boolean from an Android App to a libgdx game

Posted by Doug Henning on Game Development See other posts from Game Development or by Doug Henning
Published on 2012-08-01T00:15:26Z Indexed on 2012/08/31 9:51 UTC
Read the original article Hit count: 930

Filed under:
|

I'm writing an Android application that needs to pass a single boolean into an Android game that I am also writing. The idea is that the user does something in the App which will affect how the game operates.

This is tricky with LIBGDX since I need to get the bool value into the Java files of the game, but of course, you can't call Android specific things from within LIBGDX's main Java files. I tried using an intent but of course the same problem persists. I can get the boolean into the MainActivity.Java of the android output of the game, but can't pass it along any further since the android output and the main java files don't know about each other. I have seen a few tutorials that explain how to use set up an interface in the LIBGDX java files that can call android things. This seems like wild overkill for what I want to do.

I've been trying to use Android's Shared Preferences with LIBGDX's Gdx.app.getPreferences, but I can't make it work.

Anyhelp would be MUCH appreciated.

I've set up two hello world applications. One is a standard Android app, with a single button that is supposed to write "true" into the shared preferences. The other is a standard LIBGDX hello world that is supposed to do nothing but check that bool when launched and if true display one image to the screen, if false, display a different one.

Here's the relevant bit of the Android code:

import android.preference.PreferenceManager;

 public void onClick(View view) {
    if (view == this.boolButton){

        final String PREF_FILE_NAME = "myBool";
        SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_WORLD_WRITEABLE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("myBool", true); 
        editor.commit();        
    }
}

And here's the relevant bit of the code from the LIBGDX main file:

Preferences prefs = Gdx.app.getPreferences("myBool");
    boolean switcher = prefs.getBoolean("myBool");

    if(switcher == true){
        texture = new Texture(Gdx.files.internal("data/worked512.png"));
        prefs.putBoolean("myBool", false);
        }
        else
        {
        texture = new Texture(Gdx.files.internal("data/libgdx.png"));
        }

Everything compiles fine, it just doesn't work. I've spent HOURS googling trying to find a way to pass this single boolean from android into a LIBGDX main and I'm totally stumped.

Thanks for your help.

© Game Development or respective owner

Related posts about android

Related posts about libgdx