samedi 28 mars 2015

Android saving and retrieving an object from a database

I've created an object that I need to save so the user can access the information in it later. I was using other questions, and tutorials to put it into a JSONobject, and then turn that into a string. After that, I would insert it into a table...



JSONObject json = new JSONObject();
json.put("run", run);
String runString = json.toString();
SQLiteDatabase database = openOrCreateDatabase("your runs",MODE_PRIVATE,null);
database.execSQL("CREATE TABLE IF NOT EXISTS Runs(Run BLOB);");
database.execSQL("INSERT INTO Runs VALUES('"+runString+"');");


To retrieve it I use this code...



cursor = database.rawQuery("Select * from Runs",null);
cursor.moveToFirst();
runArray = new Run[cursor.getCount()];
while(cursor.moveToNext()){
try {
object = new JSONObject(String.valueOf(cursor.getBlob(0)));
run = (Run) object.opt("run");
runArray[count] = run;
count ++;
} catch (JSONException e) {
e.printStackTrace();
}
}


This seems to work, but when I try to get a Run from the runArray, and get the name of the run it causes a null pointer exception. The runArray has a length of one, which should be correct because I only created one Run. Is this the proper way to retrieve the Runs, or should I be going about this a different way?


Aucun commentaire:

Enregistrer un commentaire