我正在开发一款Android游戏,希望使用SQLite保存高分。到目前为止,我已经为SQL表做了一个单独的类,如下所示:
public class SQLclass {
public final static String KEY_ROWID = "_id";
public final static String KEY_NAME = "person_name";
public final static String KEY_SCORE = "person_score";
private final static String DATABASE_NAME = "Scoredb";
private final static String DATABASE_TABLE = "scoreTable";
private final static int DATABASE_VERSION = 1;
private DbHelper ourScore;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_SCORE + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public SQLclass(Context c)
{
ourContext = c;
}
public SQLclass open() throws SQLException{
ourScore = new DbHelper(ourContext);
ourDatabase = ourScore.getWritableDatabase();
return this;
}
public void close(){
ourScore.close();
}
public long createEntry(String nameString, String scoreString) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, nameString);
cv.put(KEY_SCORE, scoreString);
return ourDatabase.insert(DATABASE_NAME, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_SCORE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int Row = c.getColumnIndex(KEY_ROWID);
int name = c.getColumnIndex(KEY_NAME);
int score = c.getColumnIndex(KEY_SCORE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(Row) + " " + c.getString(name) + " " + c.getString(score) + "\n";
}
return result;
}
然后我实现了在两种不同的活动中写入数据和接收数据的方法。
NameString = Name.getText().toString();
ScoreString = count;
SQLclass entry = new SQLclass(NewScore.this);
entry.open();
entry.createEntry(NameString, ScoreString);
entry.close();
所以我将数据保存在2列中,一列是名称,另一列是得分 检索:
SQLclass info = new SQLclass(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
我觉得我正在做的是正确的,但由于某种原因,数据既没有保存也没有加载。