0

i Can't Create My DataBase With SqliteOpenHelper.My OnCreate Method Don't Run at all

i have already tried getReadable and getWriteable DataBase Methods but nothing Changes

public class SQLiteHandler extends SQLiteOpenHelper {

    private static SQLiteHandler sInstance;
    private static final String DATABASE_NAME = "telestaDB";
    private static final int DATABASE_VERSION = 1;
    private static final String TAG = "SqliteHelper";

    public SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        getReadableDatabase();
        getWritableDatabase();
        Log.i(TAG, "Constractor create!!");
    }

    public static SQLiteHandler getInstance(Context context) {

        if (sInstance == null) {
            Log.i(TAG, "getInstance: new instance created!!");
            sInstance = new SQLiteHandler(context.getApplicationContext());
        }
        return sInstance;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(ExceptionsModel.CREATE_TABLE);
        sqLiteDatabase.execSQL(DownloadModel.CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    /*
    *
    *     @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(ExceptionsModel.CREATE_TABLE);
        Log.d(TAG, "onCreate: databaseCreated!!");
        db.execSQL(DownloadModel.CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(ExceptionsModel.CREATE_TABLE);
        Log.d(TAG, "onUpgrade: databaseCreated!!");
        db.execSQL(DownloadModel.CREATE_TABLE);
    }

}

nothing happens when i tried to create an object of helper class and try to insert data into that. i use these lines to create db

SQLiteHandler sqliteHelper = SQLiteHandler.getInstance(context);
                    sqliteHelper.getWritableDatabase();

i already seen some other questions about this problem but no one helped!

  • From what I remember the database and tables do not get created until you actually do something with the database, e.g. insert, update. – Ivan Wooll Sep 16 '19 at 15:21
  • Can you clarify what you mean by "Nothing Happens" Do you mean there is not Log output? There are no Database files are created? The `sqliteHelper` returned is `Null`? Have you checked on the device that you don't already have a database file as `onCreate` won't be called it there is already a database file. I also note your Singleton Pattern is not quite right but this should not cause a problem unless you are using it wrong (Your constructor should be private) and `getReadableDatabase();` and `getWritableDatabase();` do nothing; – Andrew Sep 16 '19 at 16:08
  • Open the device file explorer from View/Tool Windows and go to data/data//databases and check there if the database is already created. – forpas Sep 16 '19 at 16:31
  • @Ivan Wooll i insert some data but when i tring to select them nothing returned i mean its not working – Mir.Ebrahim Jafarpour Zonuzi Sep 16 '19 at 16:42
  • @forpas no database created – Mir.Ebrahim Jafarpour Zonuzi Sep 16 '19 at 16:47
  • How is it possible to *insert some data* when there is no database? – forpas Sep 16 '19 at 16:53
  • @Andrew i delete singleton and its return data truly send it as answer.i'll vote it – Mir.Ebrahim Jafarpour Zonuzi Sep 16 '19 at 16:56
  • You need to show more of the code about how you insert the data and how you are trying to select the data because some bits you have shown it also wrong e.g. you are doing nothing with the `sqliteHelper.getWritableDatabase();` return. Should be `SQLiteDatabase db = getWritableDatabase();` And then you actually have to call `db.close();` to write the data to the database. – Andrew Sep 16 '19 at 16:56
  • @forpas its not inserting any data and no error too – Mir.Ebrahim Jafarpour Zonuzi Sep 16 '19 at 17:00
  • 1
    You could also try using Device explorer to copy the database file from your device and then use https://sqlitebrowser.org/ to view/query what actually is on your database file. – Andrew Sep 16 '19 at 17:20
  • @Andrew send your first comment i will select it as correct answer and upvote – Mir.Ebrahim Jafarpour Zonuzi Sep 16 '19 at 17:41

4 Answers4

1

this is the code i have done which works fine for me adjust it as per your need.hope it works for u too!

public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME ="register.db";
public static final String TABLE_NAME ="registeruser";
public static final String COL_1 ="ID";
public static final String COL_2 ="username";
public static final String COL_3 ="password";


public static final String TABLE2_NAME="Student";
public static final String COL_ONE="ID";
public static final String COL_TWO="RegNum";


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    //SQLiteDatabase db=this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY  KEY AUTOINCREMENT, username TEXT, password TEXT)");
    sqLiteDatabase.execSQL("CREATE TABLE Student(ID INTEGER PRIMARY KEY AUTOINCREMENT, RegNum TEXT)");


}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);

    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE2_NAME);
    onCreate(sqLiteDatabase);
}

public long addUser(String user, String password){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("username",user);
    contentValues.put("password",password);
    long res = db.insert("registeruser",null,contentValues);
    db.close();
    return  res;
}

public boolean checkUser(String username, String password){
    String[] columns = { COL_1 };
    SQLiteDatabase db = getReadableDatabase();
    String selection = COL_2 + "=?" + " and " + COL_3 + "=?";
    String[] selectionArgs = { username, password };
    Cursor cursor = db.query(TABLE_NAME,columns,selection,selectionArgs,null,null,null);
    int count = cursor.getCount();
    cursor.close();
    db.close();

    if(count>0)
        return  true;
    else
        return  false;
}



public boolean markAttendance(String regnum ){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(COL_TWO,regnum);
    long result=db.insert(TABLE2_NAME ,null , contentValues);

    if (result==-1)

        return false;

    else

        return true;

}
public Cursor getAllAttendance(){

    SQLiteDatabase db=this.getWritableDatabase();

    Cursor res= db.rawQuery("select * From " + TABLE2_NAME,null );
    return res;

}

}

WiLc0
  • 11
  • 3
1

I also note your Singleton Pattern is not quite right but this should not cause a problem unless you are using it wrong (Your constructor should be private) and getReadableDatabase(); and getWritableDatabase(); do nothing;

An example of a correct Singleton Pattern for SQLite is at Using Singleton design pattern for SQLiteDatabase

Andrew
  • 8,198
  • 2
  • 15
  • 35
0

in oncreate

method you did not create query

change->

https://www.javatpoint.com/android-sqlite-tutorial

0

ok so i found my code issue its from singleton pattern i don't know why but its prevent running my code truly just delete it and its work fine i send my codes here may help some one else

my SQLiteHelper Class Here

public class SQLiteHandler extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "telestaDB";
    private static final int DATABASE_VERSION = 1;
    private static final String TAG = "SqliteHelper";

    private SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        getWritableDatabase();
        getReadableDatabase();
        Log.i(TAG, "Constractor create!!");
    }

    public void addException(ExceptionsModel model) {
        SQLiteDatabase db = getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues values = new ContentValues();
//            values.put(ExceptionsModel.COLUMN_ID, model.getId());
            values.put(ExceptionsModel.USER_NAME, model.getUserName());
            db.insert(ExceptionsModel.TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (Exception e) {
            Log.d(TAG, "Error while trying to add user to database" + e.toString());
        }
    }

    public void deleteException(String model) {
        SQLiteDatabase db = getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete(ExceptionsModel.TABLE_NAME, ExceptionsModel.USER_NAME + "=?", new String[]{model});
        } catch (Exception ignored) {
            Log.d(TAG, "Error while trying to delete user from database");
        } finally {
            db.endTransaction();
        }
    }

    public List<ExceptionsModel> getAllExceptions() {

        List<ExceptionsModel> exceptions = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(ExceptionsModel.SELECT, null);
        try {
            while (cursor.moveToNext()) {
                ExceptionsModel model = new ExceptionsModel();
                /* model.setId(cursor.getInt(cursor.getColumnIndex(ExceptionsModel.COLUMN_ID)));*/
                model.setUserName(cursor.getString(cursor.getColumnIndex(ExceptionsModel.USER_NAME)));
                exceptions.add(model);
            }
        } catch (Exception e) {
            Log.d(TAG, "Error while trying to get exceptions from database" + e.toString());
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return exceptions;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        Log.i(TAG, "getInstance: new instance created!!");
        sqLiteDatabase.execSQL(ExceptionsModel.CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

My Model Class Here

public class ExceptionsModel {

    public static final String TABLE_NAME = "user_exceptions";
    public static final String COLUMN_ID = "id";
    public static final String USER_NAME = "username";
    public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,"
            + USER_NAME + " TEXT"
            + ")";
    public static final String SELECT = String.format("SELECT * FROM %s", TABLE_NAME);

    private int id;
    private String userName;

    public ExceptionsModel() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public ExceptionsModel(int id, String userName) {
        this.id = id;
        this.userName = userName;
    }
}

  • `db.insert(ExceptionsModel.TABLE_NAME, null, values);` Watch out that you might not catch an insertion error as `insert` does not throw any exceptions https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String,%20java.lang.String,%20android.content.ContentValues) Use `insertOrThrow` https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insertOrThrow(java.lang.String,%20java.lang.String,%20android.content.ContentValues) instead – Andrew Sep 16 '19 at 18:07