[英]Using a SQLite database in Libgdx
我是Libgdx的新手,我在游戲中使用數據庫時遇到了麻煩。
我搜索了一個關於如何使用Libgdx使SQLite在Android和桌面應用程序上工作的教程,但我找不到一個簡單的教程。
我最后一次在Android中使用數據庫時,創建了一個從SQLiteOpenHelper
擴展的類。
有沒有一種簡單的方法來使用Libgdx做同樣的事情? 或者至少,有人能指點我一步一步的教程或類似的東西嗎?
編輯
我忘了說我正在尋找能夠管理SQLiteOpenHelper
版本的SQLiteOpenHelper
。 換句話說,當我在代碼上更改我的數據庫版本時,我想在apk安裝上在Android中重新創建我的數據庫。
解
在@42n4
回答之后,我設法了如何使用Android應用程序上的SQLiteOpenHelper
和桌面應用程序上的JDBC
連接到SQLite數據庫。
首先,我為桌面和Android應用程序創建了一個“通用類”:
//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
類:
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
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和桌面應用程序的主要類:
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);
}
}
注意:
我做了一個版本管理一樣,在發生在一個SQLiteOpenHelper
使用PRAGMA user_version
。 這樣,我只需要在升級時更改DataBase
類的版本。
我沒有把我在Result
做的所有方法都放在但是,我認為那些更重要的方法更重要。
我寫了一個擴展(稱為gdx-sqlite),它將完成你需要的大部分工作。 可以從此處下載此擴展程序的最新版本。 源代碼和讀我位於: https : //github.com/mrafayaleem/gdx-sqlite
此擴展目前支持Android和桌面平台。 此外,不支持打開位於Android應用程序的assets文件夾中的數據庫。 但是,這是一個待處理的功能,很快就會添加。
按照自述文件中的說明設置項目以進行數據庫處理。 以下是一個示例代碼:
package com.mrafayaleem.gdxsqlitetest;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.sql.Database;
import com.badlogic.gdx.sql.DatabaseCursor;
import com.badlogic.gdx.sql.DatabaseFactory;
import com.badlogic.gdx.sql.SQLiteGdxException;
public class DatabaseTest {
Database dbHandler;
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
private static final String DATABASE_NAME = "comments.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table if not exists "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";
public DatabaseTest() {
Gdx.app.log("DatabaseTest", "creation started");
dbHandler = DatabaseFactory.getNewDatabase(DATABASE_NAME,
DATABASE_VERSION, DATABASE_CREATE, null);
dbHandler.setupDatabase();
try {
dbHandler.openOrCreateDatabase();
dbHandler.execSQL(DATABASE_CREATE);
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
Gdx.app.log("DatabaseTest", "created successfully");
try {
dbHandler
.execSQL("INSERT INTO comments ('comment') VALUES ('This is a test comment')");
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
DatabaseCursor cursor = null;
try {
cursor = dbHandler.rawQuery("SELECT * FROM comments");
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
while (cursor.next()) {
Gdx.app.log("FromDb", String.valueOf(cursor.getString(1)));
}
try {
dbHandler.closeDatabase();
} catch (SQLiteGdxException e) {
e.printStackTrace();
}
dbHandler = null;
Gdx.app.log("DatabaseTest", "dispose");
}
}
http://marakana.com/techtv/android_bootcamp_screencast_series.html第4部分,第1部分:Android Bootcamp - statusData,用於libgdx: http : //code.google.com/p/libgdx-users/wiki/SQLite
編輯:我應該提到關於Udacity的兩個關於libgdx游戲的新課程: https : //github.com/udacity/ud405
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.