简体   繁体   English

Android在某些设备上“没有这样的表”

[英]Android “no such table” on some devices

I am having problems with external database. 我在使用外部数据库时遇到问题。 The database works fine on around 60% of devices, but for example on Nexus 7 and HTC it throws "no such table" error in logcat. 该数据库可在大约60%的设备上正常运行,但是例如在Nexus 7和HTC上,它在logcat中抛出“无此表”错误。 I am pretty confused what to do with it. 我很困惑该怎么办。 However I AM VERY SURE THAT THE TABLE EXISTS. 但是,我非常确定该表存在。 And it works on my devices at home. 它可以在我家里的设备上使用。

DataBaseHelper Class DataBaseHelper类

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;

    }

} }

And logcat error: 和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

if you have installed older version of your app, when the table is not been presented, just installing the new version won't replace the old database. 如果您已安装旧版本的应用程序,则在未显示该表时,仅安装新版本不会替换旧数据库。 Uninstall the app from the device and install the newer one should work. 从设备上卸载该应用,然后安装较新的应用即可。 Or make implementation of the onUpgrade trigger. 或实现onUpgrade触发器。

EDIT: 编辑:

you might also try to replace this line: 您也可以尝试替换以下行:

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

with this: 有了这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM