1
How to check if an Android Sqlite table contains data?
1
How to check if an Android Sqlite table contains data?
2
There are two ways to do this:
Using a SELECT COUNT
:
// Obtenha a instância de SQLiteDatabase
SQLiteDatabase db = ...;
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM TABELA", null);
if (cur != null) {
cur.moveToFirst();
if (cur.getInt (0) == 0) {
// Tabela esta vazia, preencha com seus dados iniciais
} else {
// Tabela ja contem dados.
}
}
A recommendation for large tables can be the consultation:
SELECT EXISTS (SELECT 1 FROM TABELA)
In this query the engine can stop when finding the first element, being more performative.
Staying:
// Obtenha a instância de SQLiteDatabase
SQLiteDatabase db = ...;
Cursor cur = db.rawQuery("SELECT EXISTS (SELECT 1 FROM TABELA)", null);
if (cur != null) {
cur.moveToFirst();
if (cur.getInt (0) == 0) {
// Tabela esta vazia, preencha com seus dados iniciais
} else {
// Tabela ja contem dados.
}
}
Or using the DatabaseUtils
:
// Obtenha a instância de SQLiteDatabase
SQLiteDatabase db = ...;
long numOfEntries = DatabaseUtils.queryNumEntries(db, "TABELA");
if(numOfEntries == 0l) {
// Tabela vazia, preencha com seus dados iniciais
} else {
// Tabela ja contem dados.
}
Looking at the source code of DatabaseUtils.queryNumEntries(SQLiteDatabase db, String table)
. They both do the same thing.
Sources:
Browser other questions tagged android sqlite
You are not signed in. Login or sign up in order to post.
because numOfEntries == 0l ? Wouldn’t 0?
– felipe.rce
The return of
queryNumEntries
is the typelong
, I just used the0l
(0long
) to avoid an implicit cast. Silly, you can use the0
hassle-free.– Wakim