在Libgdx中使用SQLite数据库 [英] Using a SQLite database in Libgdx

查看:113
本文介绍了在Libgdx中使用SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Libgdx的新手,在使用游戏数据库时遇到麻烦.

I'm new in Libgdx and I'm getting trouble on using a database on my game.

我搜索了一个有关如何使用Libgdx使SQLite在Android和桌面应用程序上运行的教程,但没有找到简单的方法.

I searched for a tutorial on how to make SQLite work on both Android and Desktop applications using Libgdx but I didn't found a easy one.

上次在Android中使用数据库时,我创建了一个从SQLiteOpenHelper扩展的类.

The last time I used a database in Android, I created a class that extends from SQLiteOpenHelper.

有没有一种简单的方法可以使用Libgdx做到这一点?或者至少,有人可以指出我的循序渐进教程或类似内容吗?

Is there a simple way to do the same using Libgdx? Or at least, can anyone point me to a step-by-step tutorial or something similar?

编辑

我忘了说我正在寻找可以让我管理诸如SQLiteOpenHelper之类的版本的东西.换句话说,当我更改代码中数据库的版本时,我想在安装apk的Android中重新创建数据库.

I forgot to say that I'm looking for something that let me manage versions like SQLiteOpenHelper. In other words, I want to recreate my database in Android on apk installation, when I change the version of my DB on code.

解决方案

在回答@42n4之后,我设法使用Android应用程序上的SQLiteOpenHelper和桌面应用程序上的JDBC连接到SQLite数据库.

Following @42n4 answer, I managed how to connect to SQLite Database using SQLiteOpenHelper on Android Application and JDBC on Desktop Application.

首先,我为桌面和Android应用程序创建了一个通用类":

First, I created a "common class" for both Desktop and Android Applications:

//General class that needs to be implemented on Android and Desktop Applications
public abstract class DataBase {

    protected static String database_name="recycling_separation";
    protected static DataBase instance = null;
    protected static int version=1;

    //Runs a sql query like "create".
    public abstract void execute(String sql);

    //Identical to execute but returns the number of rows affected (useful for updates)
    public abstract int executeUpdate(String sql);

    //Runs a query and returns an Object with all the results of the query. [Result Interface is defined below]
    public abstract Result query(String sql);

    public void onCreate(){
        //Example of Highscore table code (You should change this for your own DB code creation)
        execute("CREATE TABLE 'highscores' ('_id' INTEGER PRIMARY KEY  NOT NULL , 'name' VARCHAR NOT NULL , 'score' INTEGER NOT NULL );");
        execute("INSERT INTO 'highscores'(name,score) values ('Cris',1234)");
        //Example of query to get DB data of Highscore table
        Result q=query("SELECT * FROM 'highscores'");
        if (!q.isEmpty()){
            q.moveToNext();
            System.out.println("Highscore of "+q.getString(q.getColumnIndex("name"))+": "+q.getString(q.getColumnIndex("score")));
        }
    }

    public void onUpgrade(){
        //Example code (You should change this for your own DB code)
        execute("DROP TABLE IF EXISTS 'highscores';");
        onCreate();
        System.out.println("DB Upgrade maded because I changed DataBase.version on code");
    }

    //Interface to be implemented on both Android and Desktop Applications
    public interface Result{
        public boolean isEmpty();
        public boolean moveToNext();
        public int getColumnIndex(String name);
        public float getFloat(int columnIndex);
        [...]
    }
}

然后,我为桌面应用程序创建了DatabaseDesktop类:

Then, I created a DatabaseDesktop Class for Desktop Application:

    public class DatabaseDesktop extends DataBase{
    protected Connection db_connection;
    protected Statement stmt;
    protected boolean nodatabase=false;

    public DatabaseDesktop() {
        loadDatabase();
        if (isNewDatabase()){
            onCreate();
            upgradeVersion();
        } else if (isVersionDifferent()){
            onUpgrade();
            upgradeVersion();
        }

    }

    public void execute(String sql){
        try {
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public int executeUpdate(String sql){
        try {
            return stmt.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Result query(String sql) {
        try {
            return new ResultDesktop(stmt.executeQuery(sql));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void loadDatabase(){
        File file = new File (database_name+".db");
        if(!file.exists())
            nodatabase=true;
        try {
            Class.forName("org.sqlite.JDBC");
            db_connection = DriverManager.getConnection("jdbc:sqlite:"+database_name+".db");
            stmt = db_connection.createStatement();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void upgradeVersion() {
        execute("PRAGMA user_version="+version);
    }

    private boolean isNewDatabase() {
        return nodatabase;
    }

    private boolean isVersionDifferent(){
        Result q=query("PRAGMA user_version");
        if (!q.isEmpty())
            return (q.getInt(1)!=version);
        else 
            return true;
    }

    public class ResultDesktop implements Result{

        ResultSet res;
        boolean called_is_empty=false;

        public ResultDesktop(ResultSet res) {
            this.res = res;
        }

        public boolean isEmpty() {
            try {
                if (res.getRow()==0){
                    called_is_empty=true;
                    return !res.next();
                }
                return res.getRow()==0;
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return false;
        }

        public boolean moveToNext() {
            try {
                if (called_is_empty){
                    called_is_empty=false;
                    return true;
                } else
                    return res.next();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return false;
        }

        public int getColumnIndex(String name) {
            try {
                return res.findColumn(name);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return 0;
        }

        public float getFloat(int columnIndex) {
            try {
                return res.getFloat(columnIndex);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return 0;
        }

        [...]

    }

}

和用于Android应用程序的DatabaseAndroid

And a DatabaseAndroid for Android Application

public class DatabaseAndroid extends DataBase{
    protected SQLiteOpenHelper db_connection;
    protected SQLiteDatabase stmt;

    public DatabaseAndroid(Context context) {
        db_connection = new AndroidDB(context, database_name, null, version);
        stmt=db_connection.getWritableDatabase();
    }

    public void execute(String sql){
        stmt.execSQL(sql);
    }

    public int executeUpdate(String sql){
        stmt.execSQL(sql);
        SQLiteStatement tmp = stmt.compileStatement("SELECT CHANGES()");
        return (int) tmp.simpleQueryForLong();
    }

    public Result query(String sql) {
        ResultAndroid result=new ResultAndroid(stmt.rawQuery(sql,null));
        return result;
    }

    class AndroidDB extends SQLiteOpenHelper {

        public AndroidDB(Context context, String name, CursorFactory factory,
                int version) {
            super(context, name, factory, version);
        }

        public void onCreate(SQLiteDatabase db) {
            stmt=db;
            DatabaseAndroid.this.onCreate();
        }

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            stmt=db;
            DatabaseAndroid.this.onUpgrade();
        }

    }

    public class ResultAndroid implements Result{
        Cursor cursor;

        public ResultAndroid(Cursor cursor) {
            this.cursor=cursor;
        }

        public boolean isEmpty() {
            return cursor.getCount()==0;
        }

        public int getColumnIndex(String name) {
            return cursor.getColumnIndex(name);
        }

        public String[] getColumnNames() {
            return cursor.getColumnNames();
        }

        public float getFloat(int columnIndex) {
            return cursor.getFloat(columnIndex);
        }

        [...]

    }

}

最后,我更改了Android和桌面应用程序的主要类:

Finally, I changed the Main Classes of both Android and Desktop Applications:

public class Main extends AndroidApplication {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initialize(new MyGame(new DatabaseAndroid(this.getBaseContext())), false);
    }
}

public class Main {

    public static void main(String[] args) {
        new LwjglApplication(new MyGame(new DatabaseDesktop()), "Example", MyGame.SCREEN_WIDTH, MyGame.SCREEN_HEIGHT,false);
    }

}

请注意:

我使用PRAGMA user_version进行了类似SQLiteOpenHelper中的版本管理.这样,当我需要升级DataBase类的版本时,就可以更改它.

I made a version management like the one that happens in SQLiteOpenHelper using the PRAGMA user_version. This way, I just change the version of the DataBase class when I need to upgrade it.

我没有将我制作的所有方法都放在Result上,但是我认为我认为更重要的那些方法更重要.

I didn't put all the methods that I made on Result but, I put the ones that I think that are more important.that are more important.

推荐答案

http://marakana.com/techtv/android_bootcamp_screencast_series.html 第4类,第1部分:Android Bootcamp-用于libgdx的statusData: http://code .google.com/p/libgdx-users/wiki/SQLite

http://marakana.com/techtv/android_bootcamp_screencast_series.html Class 4, Part 1: Android Bootcamp - statusData, for libgdx: http://code.google.com/p/libgdx-users/wiki/SQLite

我应该提到Udacity上有关libgdx游戏的两门新课程: https://github.com/udacity/ud405

I should mention about two new courses about libgdx games at Udacity: https://github.com/udacity/ud405

https://github.com/udacity/ud406

这篇关于在Libgdx中使用SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆