简体   繁体   中英

Using SQLite from libGDX on Android

Does anyone have any tips on storing data from libGDX on Android in SQLite. I am very familiar with the techniques used in the Android SDK but I don't have any idea how to call those Android database functions from libGDX. I know that calling the functions from libGDX will make my game unusable on the desktop but I can deal with that.

One approach is always to create an interface in your main project, let's call it NativeFunctions . You then let both your desktop and your Android application/activity implement this interface. On creation of your main project you pass the application/activity along. In your main application you keep a reference to the passed interface and use this to call native functions, which you can implement for desktop and Android separately (not making your game unusable on the desktop, you can use SQLite there as well ;).

Ok, that was complicated, so let's see it in action (defining a function to open an URL):

The interface:

public interface NativeFunctions {
    public void openURL(String url);
}

The main class:

public class MyGame extends Game/ApplicationListener {
    public NativeFunctions mNativeFunctions;

    public MyGame(NativeFunctions nativeFunctions) {
        mNativeFunctions = nativeFunctions;
    }
    // Exemplary function call, of course this doesn't make sense in render() ;)
    public void render() {
        mNativeFunctions.openURL("http://www.example.com");
    }
}

The Android implementation:

public class MyGameActivity extends AndroidApplication implements NativeFunctions {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initialize(new MyGame(this), false);
    }
    public void openURL(String url) {
        Intent viewIntent = new Intent("android.intent.action.VIEW", 
            Uri.parse(url));
        startActivity(viewIntent);  
    }
}

The desktop implementation:

public class MyGameDesktop implements NativeFunctions {
    public static void main(String[] args) {
        MyGameDesktop game = new MyGameDesktop();
        new LwjglApplication(new MyGame(game), "MyGame", 800,
             480, false);
    }
    public void openURL(String url) {
        // Your implementation to open URL on dekstop
    }
}

That's it, your implementation to use SQLite should probably be along the same way. Btw. I think that's also the way to integrate advertisement boxes and to talk to the system in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM