vendredi 1 mai 2015

Android Items not getting added to SQLite database

I am using the following code :

    private static SQLiteDatabase myDataBase; //global

public void insertQuestion(Context c,JSONArray jarr,String search) throws JSONException {
            DatabaseWrapper databaseWrapper = new DatabaseWrapper(c);
            Log.e("ERROR2",String.valueOf(isDatabaseOpened()));
            if(isDatabaseOpened())
            {
                myDataBase = databaseWrapper.getWritableDatabase();
                ContentValues values = postToContentValues2(jarr);
                values.put(QuestionORM.COLUMN_SEARCH,search);
                long questionId = myDataBase.insert(QuestionORM.TABLE_NAME, null, values);
                Log.e(TAG, "Inserted new Question with ID: " + questionId);
                myDataBase.close();
            }
        }

    public static boolean isDatabaseOpened() {
        if (myDataBase == null) {
            return false;
        }
        Log.e("OPEN",String.valueOf(myDataBase.isOpen()));
        return myDataBase.isOpen();

    }

My database wrapper class is :

public class DatabaseWrapper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseWrapper";
    private static final String DATABASE_NAME = "MyDatabase.db";
    private static final int DATABASE_VERSION = 1;


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


    public void onCreate(SQLiteDatabase db) {
        Log.e(TAG, "Creating database [" + DATABASE_NAME + " v." + DATABASE_VERSION + "]...");
        db.execSQL(QuestionORM.SQL_CREATE_TABLE);
        db.close();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.e(TAG, "Upgrading database ["+DATABASE_NAME+" v." + oldVersion+"] to ["+DATABASE_NAME+" v." + newVersion+"]...");
        db.execSQL(QuestionORM.SQL_DROP_TABLE);
        onCreate(db);
    }
}

And items are added like this :

    QuestionORM q = new QuestionORM();
q.insertQuestion(MainActivity.this,mJSONArr,url);

After debugging, I found that the log ERROR2 is FALSE. This means that perhaps that if condition is never executed, but I can't understand why or how to fix it. As a result, nothing gets added to the DB, and the Log with TAG is never displayed. What could be the issue here ?

Thanks !

Aucun commentaire:

Enregistrer un commentaire