我用java创建了一个mySQL数据库,我想做的是让类只有一个'getData()'方法中的'Cursor c'变量实例。这样一来,无论何时getData()
调用该方法,游标都可以从上次停止的地方继续读取数据库,而不是从头开始。
我尝试从方法中取出“Cursor c”并将其设为静态,但随后会导致其他问题。
你能告诉我如何正确地做到这一点吗?
public class SQLClass {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "IncomeName";
public static final String KEY_AMOUNT = "IncomeAmount";
private static String DATABASE_NAME = "MoneyTracker";
private static String DATABASE_TABLE = "IncomeTable";
private static int DATABASE_VERSION = 1;
private DbHelper ourHelper;
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
}//end DbHelper constructor
@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_AMOUNT + " TEXT NOT NULL);");
}//end onCreate method
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("DROP IF EXISTS " + DATABASE_NAME);
onCreate(db);
}//end onUpgrade method
}//end class DbHelper
public SQLClass (Context c){
ourContext = c;
}//end constructor SQLClass
public SQLClass open()throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}//end method open
public void close(){
ourHelper.close();
}//end method close
public long createEntry(String name, String amount) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_AMOUNT, amount);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String[] getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_AMOUNT};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String[] result = new String[]{"","",""};
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iAmount = c.getColumnIndex(KEY_AMOUNT);
c.moveToNext();
result[0] = c.getString(iRow);
result[1] = c.getString(iName);
result[2] = c.getString(iAmount);
return result;
}//end method getData
}//end class SQLClass