1

我在使用外部数据库时遇到问题。该数据库在大约 60% 的设备上运行良好,但例如在 Nexus 7 和 HTC 上,它会在 logcat 中引发“没有这样的表”错误。我很困惑如何处理它。但是我非常确定该表存在。它可以在我家里的设备上使用。

数据库助手类

public class DataBaseHelper extends SQLiteOpenHelper {

public static final String KEY_ID = "_id";
public static final String KEY_QUOTE = "quote";
public static final String KEY_AUTHOR = "author";
public static final String TABLE_QUOTES = "quotes";
public static final String KEY_FAV = "fav";


private static String DB_PATH = "/data/data/com.radoman.gameofthrones/databases/";

private final Context myContext;



private static String DB_NAME = "database.db";

private SQLiteDatabase myDataBase; 



public DataBaseHelper(Context context) {



    super(context, DB_NAME, null, 11 );
    this.myContext = context;


}   



public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
    }else{

        //By calling this method and empty database will be created into the default system path
           //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();
        this.close();

        try {
            this.getReadableDatabase();
            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

private boolean checkDataBase(){

    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();


}

private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException{

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);


}

@Override
public synchronized void close() {

        if(myDataBase != null)
            myDataBase.close();

        super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

    try {
        createDataBase();
    } catch (IOException e) {
        Log.e("copy_db", "Error copying database");
        e.printStackTrace();
    }

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}



//CRUD

    public void addQuote(Quote quote)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_QUOTE, quote.getQuote());
        values.put(KEY_AUTHOR, quote.getAuthor());

        db.insert(TABLE_QUOTES, null, values);
        db.close();
    }

    public Quote getQuote(int id)
    {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_QUOTES, new String[] {KEY_ID,KEY_QUOTE,KEY_AUTHOR,KEY_FAV}, KEY_ID + "=?", new String[] { String.valueOf(id)}, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Quote quote = new Quote(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2), cursor.getInt(3));

        return quote;
    }

    public List<Quote> getAllQuotes()
    {
            List<Quote> quoteList = new ArrayList<Quote>();
            String selectQuery = "SELECT * FROM " + TABLE_QUOTES;
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            if (cursor.moveToFirst())
            {
                do 
                {
                    Quote quote = new Quote();
                    quote.setID(Integer.parseInt(cursor.getString(0)));
                    quote.setQuote(cursor.getString(1));
                    quote.setAuthor(cursor.getString(2));
                    quoteList.add(quote);
                } while(cursor.moveToNext());
            }
            return quoteList;
    }

    public int ifFav(int id)

    {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_QUOTES, new String[] {KEY_ID,KEY_QUOTE,KEY_AUTHOR,KEY_FAV}, KEY_ID + "=?", new String[] { String.valueOf(id)}, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Quote quote = new Quote(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2), cursor.getInt(3));

        if (quote.getFav() == 1)
        {
            db.close();
            return 1;
        }

        else
        {
            db.close();
            return 0;
        }



    }

    public void addFav(int id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE quotes SET fav=1 WHERE _id=" +id;
        db.execSQL(query);
        db.close();


    }

    public void nullFav(int id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE quotes SET fav=0 WHERE _id=" +id;
        db.execSQL(query);
        db.close();
    }

    public List<HashMap<String, String>> getCharQuote(String character)
    {

        String selectQuery;
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        if(character.equals("All quotes"))
        {
            selectQuery = "SELECT * FROM " + TABLE_QUOTES;
        }
        else if (character.equals("Other characters"))
        {
            selectQuery = "SELECT * FROM "+TABLE_QUOTES+ 
                " WHERE author NOT IN('Syrio Forel','Ned Stark','Daenerys Targaryen'" +
                ",'Margaery Tyrell','Robert Baratheon','Tyrion Lannister','Ser Jorah        Mormont','Bran Stark','Cersei Lannister','Jaime Lannister');";
        }
        else
        {

             selectQuery = "SELECT * FROM " + TABLE_QUOTES+" WHERE author='"+character+"'";
        }
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst())
        {
            do 
            {

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("quote", cursor.getString(2));
                map.put("fav", cursor.getString(0));
                map.put("id",cursor.getString(1));
                fillMaps.add(map);

            } while(cursor.moveToNext());
        }
        return fillMaps;

    }

    public List<HashMap<String, String>> getAllFavQuote()
    {

        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT * FROM " + TABLE_QUOTES+" WHERE fav=1";
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst())
        {
            do 
            {

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("quote", cursor.getString(2));
                map.put("id", cursor.getString(1));
                fillMaps.add(map);

            } while(cursor.moveToNext());
        }
        return fillMaps;

    }

}

和logcat错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.radoman.gameofthrones/com.radoman.gameofthrones.FavQuotesActivity}: android.database.sqlite.SQLiteException: no such table: quotes (code 1): , while compiling: SELECT * FROM quotes WHERE fav=1
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5039)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: no such table: quotes (code 1): , while compiling: SELECT * FROM quotes WHERE fav=1
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
at com.radoman.gameofthrones.DataBaseHelper.getAllFavQuote(DataBaseHelper.java:290)
at com.radoman.gameofthrones.FavQuotesActivity.onCreate(FavQuotesActivity.java:72)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
... 11 more
4

1 回答 1

0

如果您安装了旧版本的应用程序,当表格没有出现时,仅安装新版本不会替换旧数据库。从设备上卸载应用程序并安装较新的应用程序应该可以工作。或者执行onUpgrade触发器。

编辑:

您也可以尝试替换此行:

myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

有了这个:

myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
于 2013-02-06T13:29:52.813 回答