vendredi 29 janvier 2016

Android SQLiteAssetHelper

I am using the Android SQLiteAssetHelper to load a populated .db file into my android app. However using the following code it doesn't actually make the database.

public class DataBaseHelper extends SQLiteAssetHelper {

private static final String DATABASE_NAME = "quiz.db";
private static final int DATABASE_VERSION = 1;

public DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}


public Question getRandQuestion(String category){

    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String sqlTables = category;

    qb.setTables(sqlTables);
    Cursor c=db.rawQuery("SELECT * FROM " + category + " ORDER BY RANDOM() LIMIT 1", null);
    Question question = new Question(Integer.parseInt(c.getString(0)), c.getString(1),
            c.getString(2), Uri.parse(c.getString(3)));
    return question;
}

}

I keep getting the following error

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.database.sqlite.SQLiteDatabase.getVersion()' on a null object reference

I call the DataBaseHelper constructor within another class like so:

Play Class:

    private DataBaseHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    db=new DataBaseHelper(this);

I then access the getRandQuestion method within DataBaseHelper but i get the error stated above when trying to open a readable database.

Any idea on what is going wrong?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire