Android SQLite:数据不断出现在WRONG表中。插入不好

时间:2012-01-13 17:47:13

标签: android sql sqlite

我有两张桌子: 一个用于存储HTML位置(教程),另一个用于存储原始数据(性能)

我的问题是,当我尝试从Performance表中检索Performance数据时,我得到0个条目,当我从Tutorials表中检索Tutorial数据时,我得到了性能和教程条目!

显然我正在将数据插入到错误的表中,但我没有看到我的代码中的哪个位置正在执行:

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;
    }
}

然后我有另一个名为Generate的类,其中包含以下方法:

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");
    }

在将数据插入正确的表格时,有谁可以看到我犯了错误?

1 个答案:

答案 0 :(得分:1)

问题在于:

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();