开发者

saving and retrieving a counter in SQLiteDatabase and use it to save a unique filename

开发者 https://www.devze.com 2023-04-11 00:33 出处:网络
I\'m relatively new to Java, and want to use a counter for saving each image taken with a unique id. By saving the counter variable to SQLite, I want to retrieve it again when I restart the app with t

I'm relatively new to Java, and want to use a counter for saving each image taken with a unique id. By saving the counter variable to SQLite, I want to retrieve it again when I restart the app with the same value as when I shut it down. The problem now is that the counter skips numbers ( saving the the filename as 0, 1, 3, 5 etc.). And it restarts from 0 when I exit and start the app again.

OnCreate, write and read in MosidaDb.java

@Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_PHOTOID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                KEY_PHOTOPATH + " TEXT NOT NULL, " +
                KEY_LOCATION + " TEXT, " +
                KEY_AUDIOPATH + " TEXT, " +
                KEY_DESCRIPTION + " TEXT);");

        db.execSQL("CREATE TABLE " + DATABASE_TABLE2 + " (" +
                KEY_PHOTONAME + " INTEGER NOT NULL, " +
                KEY_AUDIONAME + " INTEGER NOT NULL);");

    }


public long dbEntry2(int photoname) {
    ContentValues cv2 = new ContentValues();
    cv2.put(KEY_PHOTONAME, photoname);
    return myDatabase.insert(DATABASE_TABLE2, null, cv2);
}

public int getPhotoid() {

    Cursor c = myDatabase.rawQuery("SELECT * FROM NameTable", null);

    int iQuery = c.getColumnIndex(KEY_PHOTONAME);
    int result = 0;

    for (c.moveToFirst(); !开发者_如何学Goc.isAfterLast(); c.moveToNext()){
        result = result + c.getInt(iQuery);
} 
    return result;

} 

Do you see anything wrong in these methods? The counter variable is passed to dbEntry2, and retrieved by getPhotoid(). Or that is at least what I want it to do. thanks


If in the begining:

database.beginTransaction();

then you must call this before your application exits:

myDatabase.setTransactionSuccessful();
myDatabase.endTransaction();

That should commit your changes.

And also you should always close your cursor, when you are done:

c.close();

I don't know why counter skips, check your database content.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号