java.lang.IllegalStateException: getDatabase called recursively - sqlite

I'm trying to save my game configuration indatabase, I used a tutorial in this page: page.
I make this class called configuracion:
public class Configuraciones extends SQLiteOpenHelper {
static final String table_name = "configuraciones";
static final String cod_config = "id";
static final String nom_config = "nombre";
static final String val_config = "valor";
public Configuraciones(Context context) {
super(context, "bdd_cuarenta", null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + table_name + "("
+ cod_config + " INTEGER PRIMARY KEY," + nom_config + " TEXT,"
+ val_config + " TEXT" + ");";
// ESTABLISH NEW DATABASE TABLES IF THEY DON'T ALREADY EXIST IN THE DATABASE
db.execSQL(CREATE_TABLE);
//Ingresa las configuraciones por primera vez
ingresaTablas(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int vieja, int nueva) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + table_name);
onCreate(db);
}
public String consultaConfiguracion(String nombre){
SQLiteDatabase myDB = getReadableDatabase();
String[] mySearch = new String[]{nombre};
Cursor myCursor = myDB.rawQuery("SELECT "+ val_config +" FROM "+ table_name +" WHERE "+ nom_config +"='?'",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(val_config);
String myAnswer = myCursor.getString(index);
myCursor.close();
return myAnswer;
}
public int actualizaConfig(String nombre, String nuevaConfig)
{
SQLiteDatabase myDB = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(val_config, nuevaConfig);
int numRowsAffected = myDB.update(table_name, cv, nom_config+"='?'", new String []{String.valueOf(nombre)});
return numRowsAffected;
}
But when i call one of the methods, for example actualizaConfig, I got the error:
java.lang.IllegalStateException: getDatabase called recursively
In my game activity I called normaly the object like this:
private BoundCamera camera;
private Configuraciones configs;
#Override
public Engine onCreateEngine(EngineOptions pEngineOptions)
{
return new LimitedFPSEngine(pEngineOptions, 60);
}
public EngineOptions onCreateEngineOptions()
{
camera = new BoundCamera(0, 0, 800, 480);
configs = new Configuraciones(this);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), this.camera);
engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return engineOptions;
}
And in GameScene, i call the method like this:
resourcesManager.config.actualizaConfig("diseno_carta", "9");
I dont know why is the problem... :(

Related

I have added a database in my program. Although the build is successful my app is crashing. This is my databasehandler;

I am getting the error as:
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "EXISTSnotes": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTSnotes(idINTEGER PRIMARY KEY,titleTEXT,descriptionTEXT)).
Need help.
public DatabaseHandler(Context context) {
super(context, DatabaseValues.DATABASE_NAME, null, DatabaseValues.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) { db.execSQL(DatabaseValues.TABLE_NOTES_CREATE); }
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DatabaseValues.TABLE_NOTES_DROP);
onCreate(db);
}
public void addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues noteValues = new ContentValues();
noteValues.put(DatabaseValues.NOTES_TITLE, note.getTitle());
noteValues.put(DatabaseValues.NOTES_DESCRIPTION, note.getDescription());
db.insert(DatabaseValues.TABLE_NOTES, null, noteValues);
db.close();
}
public void updateNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues noteValues = new ContentValues();
noteValues.put(DatabaseValues.NOTES_TITLE, note.getTitle());
noteValues.put(DatabaseValues.NOTES_DESCRIPTION, note.getDescription());
db.update(DatabaseValues.TABLE_NOTES, noteValues, DatabaseValues.NOTES_ID + "= ?",
new String[]{String.valueOf(note.getId())});
db.close();
}
public void deleteNote(String id) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery = "DELETE FROM" + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + "id" + "'";
db.execSQL(deleteQuery);
db.close();
}
public List<Note> getAllNotes() {
List<Note> notes = new ArrayList<>();
SQLiteDatabase db=this.getReadableDatabase();
String selectQuery = "SELECT * FROM" + DatabaseValues.TABLE_NOTES;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Note note = new Note();
note.setId(Integer.parseInt(cursor.getString(0)));
note.setTitle(cursor.getString(1));
note.setDescription(cursor.getString(2));
notes.add(note);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return notes;
}
}
The error seems to be clear enough to see what's going on:
while compiling: CREATE TABLE IF NOT EXISTSnotes(idINTEGER PRIMARY KEY,titleTEXT,descriptionTEXT)).
Your query for creating the Db seems to be missing a whitespace between 'EXISTS' and the table name 'note'.
UPDATE
You are actually missing many more whitespace. Format your query like this and make sure all others query you build have the correct whitespacing or they will fail as well.
public static final String TABLE_NOTES_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NOTES + " (" + NOTES_ID + " INTEGER PRIMARY KEY," + NOTES_TITLE + " TEXT," + NOTES_DESCRIPTION + " TEXT)";

how to refer to a non-declared variables in setResultConverter

I'd like to re-use a dialog class for data manipulation. The data will be retrieved from database. It depends on which table the class retrieve the data from, the size of the table columns is not fixed, so I can't declare column variables. After users update data, I would like to convert the input data using setResultConverter but do not know how to refer to the variable, since the program generates TextFields dynamically. Please help. Here is the the code.
public class AddDialog {
private Dialog<DBtable> dialog = new Dialog<DBtable>();
private ButtonType saveBtn;
//database variables
private Connection connect; // = null;
private String dbTblName;
//gridpane content variables
private GridPane contentPane = new GridPane();
private HashMap<String, TextField> fieldMap =
new HashMap<String, TextField>();
private ArrayList<String> dataList = new ArrayList<String>();
public AddDialog (String title, String header, String dbTable) {
this.dbTblName = dbTable;
dialog.setTitle(title);
dialog.setHeaderText(header);
saveBtn = new ButtonType("Save", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(saveBtn,
ButtonType.CANCEL);
dialog.getDialogPane().setContent(getLayout(dbTable));
Optional<DBtable> result = dialog.showAndWait();
result.ifPresent(data -> {
System.out.println(" data="+data+" 0="+data.getID()+
" 1="+data.getField1());
});
} // constructor ends
public GridPane getLayout(String dbTable) {
String sql = "select column_name, description ";
sql += "from syscolumn_description ";
sql += "where table_name = \'" + dbTable + "\'";
String fieldLabel, fieldCol;
ResultSet ds = null;
// retrieve meta data from database
connect = DBConnect.getConnect(connect);
try {
Statement labelStmnt = connect.createStatement();
ds = labelStmnt.executeQuery(sql);
int row = 0;
while (ds.next()) {
row += 2;
//label....column=0 row=row+2;
fieldLabel = ds.getString("DESCRIPTION");
contentPane.add(new Text(fieldLabel), 0, row);
//textField...column=1 row=row+2;
contentPane.add(new TextField(), 1, row);
fieldCol = ds.getString("COLUMN_NAME");
fieldMap.put(fieldCol, new TextField());
} // while result set loop ends
} catch (Exception e) {
e.printStackTrace();
} finally {
try {if(ds != null) ds.close();} catch (Exception e) {};
}
// convert result
dialog.setResultConverter(dialogButton -> {
if (dialogButton == saveBtn) {
int i=0;
for (Map.Entry<String, TextField> e : fieldMap.entrySet()) {
dataList.add(e.getValue().getText());
i++;
System.out.println("col="+e.getKey()+
" data="+e.getValue().getText());
} // map loop end
return new DBtable(dataList, i);
}
return null;
});
return contentPane;
} //getLayout ends
} // AddDialog ends

Error connecting to databasehandler

I have a error regarding database as shown below:
E/CursorWindow(386): Bad request for field slot 0,-1. numRows = 1, numColumns = 63
here's my piece of code:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_IMAGE = "image";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_IMAGE + " BLOB,"
+ KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE,contact.getImageId());
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Methods getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,KEY_IMAGE,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Methods contact = new Methods(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))),
cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE)),cursor.getString(cursor.getColumnIndex(KEY_NAME)), cursor.getString(cursor.getColumnIndex(KEY_PH_NO)));
// return contact
cursor.close();
return contact;
}
// Getting All Contacts
public List<Methods> getAllContacts() {
List<Methods> contactList = new ArrayList<Methods>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Methods contact = new Methods();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setImageId(cursor.getBlob(1));
contact.setName(cursor.getString(2));
contact.setPhoneNumber(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
/*// Updating single contact
public int updateContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}*/
// Deleting single contact
public void deleteContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
Log.v("deleteContact", "Deleted row is: "+String.valueOf(contact.getID()));
}
void deleteAll(Methods contact)
{
SQLiteDatabase db= this.getWritableDatabase();
db.delete(TABLE_CONTACTS, null, null);
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
It would help to have more information here (a stack trace perhaps?). However it seems you're not providing an "id" when adding a contact. Consider making this column auto incrementing instead.
Last, if this is an Android question, your primary key column should be auto incrementing and should be called "_id", else make sure that this is given as a column name in any cursor returned from a query. Also check that your database has a table called "android_metadata" too.

How to Select and return value from sqlite?

I've created database and inserted the values to the tables. Now I'm trying to select a data but I'm getting following error:
I've pasted my entire SQLHelper class code. Please can anyone let me know where I'm doing mistake?
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "MyDB.db";
// Table Names
private static final String TABLE_USERS = "Users";
private static final String TABLE_SCORES = "Scores";
private static final String TABLE_SYNCSTATUS = "SyncStatus";
// Common column names
private static final String KEY_ID = "id";
private static final String KEY_CREATED_AT = "created_at";
// USERS Table - column names
private static final String KEY_USERID = "userID";
private static final String KEY_USERNAME = "userName";
private static final String KEY_USERPSWD = "userPswd";
private static final String KEY_FIRSTNAME = "firstName";
private static final String KEY_LASTNAME = "lastName";
// SCORES Table - column names
private static final String KEY_USER_ID = "userID";
private static final String KEY_GAME_ID = "gameID";
private static final String KEY_SCORES = "scores";
// SYNCSTATUS Table - column names
private static final String KEY_STATRDATE = "startDate";
private static final String KEY_ENDDATE = "endDate";
private static final String KEY_STATUS = "status";
// Table Create Statements
// USERS table create statement
private static final String CREATE_TABLE_USERS = "CREATE TABLE IF NOT EXISTS "
+ TABLE_USERS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID
+ " TEXT," + KEY_USERNAME + " INTEGER," + KEY_USERPSWD + " TEXT,"
+ KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT,"
+ KEY_CREATED_AT + " DATETIME" + ")";
// Scores table create statement
private static final String CREATE_TABLE_SCORES = "CREATE TABLE IF NOT EXISTS "
+ TABLE_SCORES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USER_ID
+ " INTEGER," + KEY_GAME_ID + " INTEGER," + KEY_SCORES + " INTEGER,"
+ KEY_CREATED_AT + " DATETIME" + ")";
// Sync table create statement
private static final String CREATE_TABLE_SYNCSTATUS = "CREATE TABLE IF NOT EXISTS "
+ TABLE_SYNCSTATUS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_STATRDATE + " DATETIME," + KEY_ENDDATE + " DATETIME," + KEY_STATUS + " INTEGER,"
+ KEY_CREATED_AT + " DATETIME" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_SCORES);
db.execSQL(CREATE_TABLE_SYNCSTATUS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SYNCSTATUS);
// create new tables
onCreate(db);
}
public int validateUserLogin(String uname, String pswd)
{
SQLiteDatabase db = this.getReadableDatabase();
String[] whereArgs = new String[]{uname, pswd};
String query = "SELECT "+KEY_USERID+" FROM "+TABLE_USERS+" WHERE "+KEY_USERNAME+" = ? AND "+KEY_USERPSWD+" = ?";
try{
Cursor cur= db.rawQuery(query, whereArgs);
//Boolean b = cur.moveToFirst();
if (cur.moveToFirst() == true)
{
return cur.getInt(cur.getColumnIndex(KEY_USERID));
}
else
return -1;
}catch(Exception e){
return -1;
}
}
public void insertValues(UsersCredential uc){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(KEY_USERID, uc.getUserID());
cv.put(KEY_USERNAME, uc.getUserName());
cv.put(KEY_USERPSWD, uc.getUserPassword());
cv.put(KEY_FIRSTNAME, uc.getUserFirstName());
cv.put(KEY_LASTNAME, uc.getUserLastName());
cv.put(KEY_CREATED_AT, getDateTime());
db.insert(TABLE_USERS, null, cv);
}
public void deleteRecords() {
SQLiteDatabase db= this.getWritableDatabase();
db.execSQL("delete from Users");
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
I'm getting the Exception in validateUserLogin(String uname, String pswd) method, What is wrong in my code?
Your query does not return any data.
You must check the return value of moveToFirst before you can try to access the data.

Nullpointer exception while Creating records and inserting values in database- also using SQL-cipher

Cipher for my database , i am trying to insert the record values but i am getting nullpointer exception while creating the record and inserting the values, below is my Databasehelper code
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String KEY_ROWID = "_id";
public static final String KEY_CODE = "code";
public static final String KEY_NAME = "name";
public static final String KEY_CONTINENT = "continent";
public static final String KEY_REGION = "region";
public static final String KEY_AREA = "area";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
String password = "foo123";
private static final String DATABASE_NAME = "salesreports";
private static final String SQLITE_TABLE = "salesandreports";
private static final String SQLITE_TABLE1 = "salescharts";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_CODE + " INTEGER," +
KEY_NAME + " INTEGER," +
KEY_CONTINENT + " INTEGER," +
KEY_REGION + " INTEGER," +
KEY_AREA + " INTEGER" +
")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
public long createsalesCountry(String code, String name,
String continent, String region,String area) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CODE, code);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_CONTINENT, continent);
initialValues.put(KEY_REGION, region);
initialValues.put(KEY_AREA, area);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public boolean deleteAllCountries() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCountriesByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION,KEY_AREA},
null, null, null, null, null,null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION,KEY_AREA},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCountries() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION,KEY_AREA},
null, null, null, null, null,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertsalesvalues() {
createCountry("1","1","1","1","1");}}
and below is my activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutToDisplayChart=(LinearLayout)findViewById(R.id.relative_layout1);
SQLiteDatabase.loadLibs(this);
String password = "foo123";
dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase(password);
//dbHelper.insertsalesvalues();
dbHelper.insertSomeCountries();
Intent achartIntent = new aChart_Example().execute(MainActivity.this,LayoutToDisplayChart);
Below is my trace
Caused by: java.lang.NullPointerException
09-17 11:02:01.500: E/AndroidRuntime(27757): at com.example.mychartapp.DatabaseHelper.createsalesCountry(DatabaseHelper.java:113)
09-17 11:02:01.500: E/AndroidRuntime(27757): at com.example.mychartapp.DatabaseHelper.insertsalesvalues(DatabaseHelper.java:198)
09-17 11:02:01.500: E/AndroidRuntime(27757): at com.example.mychartapp.MainActivity.onCreate(MainActivity.java:26)
Adding this line solved my problem **SQLiteDatabase mDb = this.getWritableDatabase(password);**
public long createsalesCountry(String code, String name,
String continent, String region,String area) {
**SQLiteDatabase mDb = this.getWritableDatabase(password);**
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CODE, code);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_CONTINENT, continent);
initialValues.put(KEY_REGION, region);
initialValues.put(KEY_AREA, area);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public void insertSalesvalues() {
**SQLiteDatabase mDb = this.getWritableDatabase(password);**
createCountry("1","1","1","1","1");
}
First thing you have to do is, check where you have your database file, whether in your assets, or /data/data/your package name/your_application_name. If it is in your assets, you have to copy it to your /data/data/your package name/ folder. Then, after copying your DB file, save that DB file to your PC, check the structure of the database file, the data present in it(if any). You are telling that, you could not insert or retrieve any data right? By checking your database file in this way, you can understand your mistake in the back-end. But, to my knowledge, I did not find any mistake in your code.

Resources