askIT

Query (Android SQLite)

The class DBadapter should have a method for extracting data from a database table. Below is a example. We have a table with the name «notes». This table contains four row with data. To get rows we need to program the method getAllRecordsFromNotes and getRecordFromNotes. The methods can be called on in the class MainActivity.

Struktur for notes

Field Type Key
note_id int Primary key
note_title varchar
note_text text

Data i notes

note_id note_title note_text
1 Shopping list Cola Zero, Crispbread
2 Music ACDC
3 Homework Law page 119-134
4 Homework Road traffic law page 84-99

DBadapter

// Retrive all rows
public Cursor getAllRecordsFromNotes()
{
        return db.query(databaseTableNotes, new String[]{
                "note_id",
                "note_title",
                "note_text"
        }, null, null, null, null, null, null);
}
// Retrive particular rows
public Cursor getRecordFromNotes(long rowId) throws SQLException {
        Cursor mCursor = db.query(databaseTableNotes, new String[] {
                "note_id",
                "note_title",
                "note_text"
        },
        "note_id" + "=" + rowId, null, null, null, null, null);
        if (mCursor != null) {
                mCursor.moveToFirst();
        }
        return mCursor;
}

MainActivity

// Get all notes
Cursor cNote = db.getAllRecordsFromNotes();
displayRecordFromNotes(cNote);

// Get particular note
long noteID = 3;
Cursor cNoteB = db.getRecordFromNotes(noteID);
displayRecordFromNotes(cNoteB);

Method displayRecordFromNotes in MainActivity

// Print notes table content
private void displayRecordFromNotes(Cursor inpCursor) {
        Toast.makeText(this,
        "Id: " + inpCursor.getString(0) + "\n" +
        "Tittel: " + inpCursor.getString(1) + "\n" +
        "Tekst: " + inpCursor.getString(2),
        Toast.LENGTH_LONG).show();
} // end private void displayRecordFromNotes

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.