Using SQLite from libGDX on Android

社会主义新天地 提交于 2019-12-18 15:01:03

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9584959/using-sqlite-from-libgdx-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!