tetris11 tetris11 - 22 days ago 6
SQL Question

Android SQLite: Data keeps appearing in the WRONG table. Inserting badly

I have two Tables:
One for storing HTML locations (Tutorials), and one for storing primitive data (Performance)

My problem is that when I try to retrieve Performance data from the Performance table I get 0 entries, and when I retrieve Tutorial data from the Tutorials table I get both the performance and tutorial entries!

Clearly I'm inserting the data into the wrong table, but I don't see where in my code I'm doing it:

public class DBAdapter {
public static final String KEY_ROWID = "_id"; //unique identifier
public static final String KEY_CHAPTER = "chapter"; //title text
public static final String KEY_LOCATION = "path"; //where it's stored
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "tutorDB";
private static final String Table_Tutorials = "Tutorials";

private static final String Table_Performance = "Performance"; //For storing quiz results
public static final String KEY_PID = "id";
public static final String KEY_PERCENT = "Correct"; //Percentage correct
public static final String KEY_DATE = "Date"; //Date the quiz was taken.



public static int DATABASE_VERSION = 23; //Tutorial Table is dropped and rebuilt when this increases

private static final String DATABASE_CREATE_TUTORIALS =
"create table "+Table_Tutorials+" ("+KEY_ROWID+" integer primary key autoincrement, "
+KEY_CHAPTER+" text not null, "+KEY_LOCATION+" text not null);";

private static final String DATABASE_CREATE_PERFORMANCE =
"create table "+Table_Performance+" ("+KEY_PID+" integer primary key autoincrement, "
+KEY_DATE+" text not null, "+KEY_PERCENT+" text not null);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE_TUTORIALS); //Creates Tutorial table
db.execSQL(DATABASE_CREATE_PERFORMANCE); //Creates Performance table
} catch (SQLException e) {
e.printStackTrace();
}
}

@Override //Called when version changes
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Tutorials");
db.execSQL("DROP TABLE IF EXISTS Performance"); //Performance data should NOT dropped!
onCreate(db);
}
}

//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}

//---closes the database---
public void close()
{
DBHelper.close();
}

//---insert a Tutorial into the database---
public long insertTut(String chapt, String path)
{
ContentValues nv = new ContentValues(); //new vals
nv.put(KEY_CHAPTER, chapt);
nv.put(KEY_LOCATION, path);
return db.insert(Table_Tutorials, null, nv);
}

//---insert a Performance stat into the database---
public long insertPerf(String percent, String date)
{
ContentValues nv = new ContentValues(); //new vals
nv.put(KEY_DATE, date);
nv.put(KEY_PERCENT, percent);
return db.insert(Table_Performance, null, nv);
}

//---retrieves all the Tutorials---
public Cursor getAllTuts()
{
return db.query(Table_Tutorials, new String[] {KEY_ROWID, KEY_CHAPTER, KEY_LOCATION}, null, null, null, null, null);
}

//---retrieves all the Performance stats---
public Cursor getAllPerfs()
{
return db.query(Table_Performance, new String[] {KEY_PID, KEY_DATE, KEY_PERCENT}, null, null, null, null, null);
}



//---retrieves a particular Tutorial---
public Cursor getTut(long rowId) throws SQLException
{
Cursor mc =
db.query(true, Table_Tutorials, new String[] {KEY_ROWID, KEY_CHAPTER, KEY_LOCATION}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mc != null) {
mc.moveToFirst();
}
return mc;
}
}


I then have another class called
Generate
with the following methods:

public static void databaseFn(String args){
if(args.equals("initialise")){
Log.v("DB:","openinig...");
try {
String destPath = "/data/data/" + Welcome.packageName + "/databases/tutorDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(Welcome.context.getAssets().open("tutorDB"), new FileOutputStream(destPath));
//Welcome context is always instantiated when Activity starts, so never null
}
} catch (FileNotFoundException e) {
Log.v("DB:","DB file not there - creating new");
} catch (IOException e) {
Log.v("DB:","Problems with IO");
}
db = new DBAdapter(Welcome.context);
Log.v("DB:","Opened");

}
else if(args.equals("getAllTuts")){
ArrayList<String> titles = new ArrayList<String>();
db.open();
Cursor c = db.getAllTuts();
if(c.getCount()==0) Toast.makeText(Welcome.context, "EMPTY", Toast.LENGTH_LONG).show();
else if (c.moveToFirst()){
do {
titles.add(c.getString(1));
} while (c.moveToNext());
}
Contents.list = titles;
db.close();
}
else if(args.equals("getAllPerfs")){
Log.v("DB:","Getting Perfs");
ArrayList<String[]> datePercent = new ArrayList<String[]>();
db.open();
Cursor c = db.getAllPerfs();
if(c.getCount()==0) Toast.makeText(Welcome.context, "No Performance Data", Toast.LENGTH_LONG).show();
else if (c.moveToFirst()){
do { //Retrieves Date --- Percent Correct
datePercent.add(new String[]{c.getString(1),c.getString(2)});
} while (c.moveToNext());
}
GeneratePerformanceStats.perfList = datePercent;
db.close();
}

else if(args.equals("populate")){
Log.v("DB:","Populating....");
db.open();
for(int i=0; i< tutorData.size(); i++){
String title = tutorData.get(i);
db.insertTut(title, "file://"+FileOps.directory.getAbsolutePath()+"/"+title+".html");
}
db.close();
Log.v("DB:","Populated.");
}

else if(args.equals("insertPerf")){
db.open();
Log.v("Adding:",getDate()+" "+String.valueOf(ExercisePage.res));
db.insertTut(getDate(), String.valueOf(ExercisePage.res));
db.close();
Log.v("DB:","Performance Added");
}

else if(args.startsWith("retrieve")){
Log.v("DB:","retrieving....");
String [] arguments = args.split(" ");
db.open();
int index = 0;
try{
index = Integer.parseInt(arguments[1]);
} catch (NumberFormatException n){
Log.v("DB:", "Invalid Chapter Index");
}
Cursor c = db.getTut(index);
if (c.moveToFirst()){
Download.pageToLoad=c.getString(2);
Log.v("Page:","Loading... "+Download.pageToLoad);
}
else Toast.makeText(Welcome.context, "No contact found", Toast.LENGTH_LONG).show();
db.close();
Log.v("DB:","retrieved");
}
else{
Log.v("DB:", "Invalid call");
}


Can anyone see where I've made a mistake when it comes to inserting data into the right table?

Answer

The issue is here:

else if(args.equals("insertPerf")){ 
    db.open();
    Log.v("Adding:",getDate()+" "+String.valueOf(ExercisePage.res));
    db.insertTut(getDate(), String.valueOf(ExercisePage.res));
    db.close();
    Log.v("DB:","Performance Added");
}

WRONG:

db.insertTut();

CORRECT:

db.insertPerf();

Comments