sark9012
sark9012

Reputation: 5727

Getting an SQLite working within Android and accessing data

I am trying to get an SQLite database to work in Android and have a few questions!

I have put the following in the onCreate method of my database class, which extends SQLiteOpenHelper.

db.execSQL("CREATE TABLE IF NOT EXISTS `challenge` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `date` TEXT )");

I then have the following method.

public void addChallenge(){

    SQLiteDatabase db = this.getWritableDatabase();

    Date cDate = new Date();
    String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);

    ContentValues values = new ContentValues();
    values.put("date", fDate);

    db.insert("challenge", null, values);

}

And the following would grab the challenge added above back.

public int getChallengeId(){

    SQLiteDatabase db = this.getWritableDatabase();

    Date cDate = new Date();
    String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);

    String countQuery = "SELECT id FROM challenge WHERE date = " + fDate;

    Cursor cursor = db.rawQuery(countQuery, null);

    int challenge_id = 0;

    if(cursor.moveToFirst()){
        challenge_id = cursor.getInt(0);
    }

    return challenge_id;

}

My issue is that the challenge ID is returning as 0.

So I have a few questions.

The code I use to access the above methods is as follows

Database db_add = new Database(context);
db_add.addChallenge();
db_add.close();

Database db_get = new Database(context);
challenge_id = db_get.getChallengeId();
db_get.close();

Any ideas? Thanks.

Upvotes: 0

Views: 25

Answers (1)

CL.
CL.

Reputation: 180020

The SQL query is not correct.

2015-02-23 tells the database that you want to subtract the numbers 2 and 23 from the number 2015.

Strings must be 'quoted'. However, you should avoid such formatting problem by using parameters:

String countQuery = "SELECT id FROM challenge WHERE date = ?";
Cursor cursor = db.rawQuery(countQuery, new String[]{ fDate });

Upvotes: 2

Related Questions