簡體   English   中英

SQLite數據庫可在模擬器上運行,但不能在設備上運行

[英]SQLite database works on emulator but not on device

我在Android應用程序中使用sqlite數據庫。 我正在android中的databases文件夾中預先創建數據庫。 數據庫已創建,並且可以在仿真器中正常運行,但是當我在手機中運行相同的代碼時,會出錯。

這是有關如何在databases文件夾中預創建數據庫的代碼。

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SavingData.mainActivity = this;

    try {
        String destPath = "/data/data/" + getPackageName() + "/databases";
        File f = new File(destPath);
        if (!f.exists()) {
            f.mkdirs();
            f.createNewFile();
            // ---copy the db from the assets folder into
            // the databases folder---
            CopyDB(getBaseContext().getAssets().open("exercisedatedb"),
                    new FileOutputStream(destPath + "/ExerciseDateDB"));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public void CopyDB(InputStream inputStream, OutputStream outputStream)
        throws IOException {
    // ---copy 1K bytes at a time---
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    inputStream.close();
    outputStream.close();
}
  }

這是我得到的錯誤:

04-01 12:51:12.503: E/SQLiteLog(26823): (1) no such column: date
04-01 12:51:12.503: D/AndroidRuntime(26823): Shutting down VM
04-01 12:51:12.503: W/dalvikvm(26823): threadid=1: thread exiting with uncaught exception (group=0x40f722a0)
04-01 12:51:12.508: E/AndroidRuntime(26823): FATAL EXCEPTION: main
04-01 12:51:12.508: E/AndroidRuntime(26823): android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT id, date FROM dates
04-01 12:51:12.508: E/AndroidRuntime(26823):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-01 12:51:12.508: E/AndroidRuntime(26823):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1013)
04-01 12:51:12.508: E/AndroidRuntime(26823):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:624)

這是我將數據插入數據庫的方法:

public void insertDate(String date) {
    // TODO Auto-generated method stub
    db.open();
    long id = db.insertDate(date);
    db.close();
}

這是我的DBAdapter類:

public class DBAdapter {
static final String KEY_ROWID = "id";
static final String KEY_DATE = "date";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "ExerciseDateDB";
static final String DATABASE_TABLE = "dates";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table dates (id integer primary key autoincrement, "
        + "date text not null);";
final Context context;
DatabaseHelper DBHelper;
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);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    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 contacts");
        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 Date into the database---
public long insertDate(String date) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_DATE, date);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// ---deletes a particular date---
public boolean deleteDate(long rowId) {
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

// ---retrieves all the score---
public Cursor getAllDate() {
    return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_DATE}, null, null, null, null, null);
}

// ---retrieves a particular score---
public Cursor getDate(long rowId) throws SQLException {
    Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
            KEY_ROWID, KEY_DATE}, KEY_ROWID + "= " + rowId + "",
            null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

// ---updates a score---
public boolean updateDate(long rowId, String date) {
    ContentValues args = new ContentValues();
    args.put(KEY_DATE, date);
    return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}

這是我的數據庫解決方案。 它全部包含在一個類中。

太稱呼它的語法是...

DatabaseManager mDatabase = DatabaseManager.getInstance();

公共類DatabaseManager {

private static DatabaseManager instance;
private final String DB_NAME = "singoff_database";
private final int DB_VERSION = 1;

private final String GAME_TABLE_NAME = "game_table";
private final String GAME_ID = "gameid";
private final String GAME_OPPONENT_ID = "opponent";
private final String GAME_TRACK = "track";
private final String GAME_FILE_PATH = "filepath";
private final String GAME_PICTURE = "picture";
private final String GAME_GUESSES = "guesses";
private final String GAME_DATE = "date";

private SQLiteDatabase mDb;
private Context context;

private DatabaseManager(Context context) {
    this.context = context;
    //create new or open database
    DatabaseHelper helper = new DatabaseHelper(context);
    this.mDb = helper.getWritableDatabase();
}

public synchronized static DatabaseManager getInstance() {
    if (instance == null) {
        Context context = Main.getInstance();
        instance = new DatabaseManager(context);
    }
    return instance;
}

//__________________________________________________________________________________________//
//GAME LIST HANDLING STATEMENTS

public synchronized void addGame(String gID, String oID, String track,
                                 String path, byte[] thumb, String datetime) {

    ContentValues values = new ContentValues();

    values.put(GAME_ID, gID);
    values.put(GAME_OPPONENT_ID, oID);
    values.put(GAME_TRACK, track);
    values.put(GAME_FILE_PATH, path);
    values.put(GAME_PICTURE, thumb);
    values.put(GAME_DATE, datetime);

    mDb.insert(GAME_TABLE_NAME, null, values);
}

public synchronized List<File> getGames() {

    List<File> games = new ArrayList<File>();
    Cursor cursor;

    cursor = mDb.query(
            GAME_TABLE_NAME,
            new String[]{GAME_FILE_PATH},
            null, null, null, null, null);
    cursor.moveToFirst();
    if (!cursor.isAfterLast()) {
        do {
            File file = new File(cursor.getString(0));
            games.add(file);
        } while (cursor.moveToNext());
    }
    cursor.close();

    return games;
}

public synchronized Game getGame(String filepath) {

    Cursor cursor;
    //Game game = null;
    Bitmap picture = null;
    byte[] blob;

    cursor = mDb.query(
            GAME_TABLE_NAME,
            new String[]{
                    GAME_OPPONENT_ID,
                    GAME_FILE_PATH,
                    GAME_PICTURE,
                    GAME_DATE},
            GAME_FILE_PATH + "=?",
            new String[]{filepath},
            null, null, null);

    if (cursor.moveToNext()) {
        blob = cursor.getBlob(2);
        if (blob != null) {
            picture = BitmapFactory.decodeByteArray(blob, 0, blob.length);
        }

        //game = new Game(mContext, new File(filepath), cursor.getString(0), picture);
    }
    return null;
}

public void updateGame(String filepath, gameColumn col,
                       Object object) {
    ContentValues values = new ContentValues();

    switch (col) {

        case GAME_PICTURE:
            Bitmap picture = (Bitmap) object;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            picture.compress(Bitmap.CompressFormat.PNG, 100, out);
            values.put(GAME_PICTURE, out.toByteArray());
            break;
        default:
            return;
    }
    mDb.update(GAME_TABLE_NAME, values, GAME_FILE_PATH + "=?", new String[]{filepath});
}

public synchronized void removeGame(String filepath) {
    mDb.delete(GAME_TABLE_NAME, GAME_FILE_PATH + "=?", new String[]{filepath});
}

public enum gameColumn {
    GAME_TABLE_NAME, GAME_OPPONENT_ID, GAME_FILE_PATH,
    GAME_PICTURE, GAME_DATE
}


//__________________________________________________________________________________________//


//--------------------------------------------------------------------------------------------------
private class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String createGameTableQuery = " CREATE TABLE IF NOT EXISTS "
                + GAME_TABLE_NAME + " ("
                + GAME_ID + " INTEGER, "
                + GAME_OPPONENT_ID + " VARCHAR(20), "
                + GAME_TRACK + " VARCHAR(30), "
                + GAME_FILE_PATH + " VARCHAR(50), "
                + GAME_PICTURE + " BLOB, "
                + GAME_GUESSES + " VARCHAR, "
                + GAME_DATE + " VARCHAR(50)"
                + ");";

        //create game table
        db.execSQL(createGameTableQuery);

    }

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

}

創建一個數據庫對象:

public class Database extends SQLiteOpenHelper {
        private static final String DATABASE_NAME = "Exampe.db";
        private static final int DATABASE_VERSION = 1;
        public static final String ID = "_id";
        public static final String NAME = "name";
        public static final String UUID = "uuid";
        public static final String TABLE_NAME = "Example Something";
        private static final String DATABASE_CREATE = "create table "
        + TABLE_NAME + "( " + ID
        + " integer primary key autoincrement, " + NAME
        + " text not null, " + UUID
        + " text not null);";

        public Database(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(Database.class.getName(), "Upgrading database from version " + oldVersion + "to " + newVersion + ", which will destroy all old data"); 
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
        }
    }

現在你稱之為

        private SQLiteDatabase database;
    private Database dbHelper;
    private String[] allColumns = { Database.ID, Database.NAME};

public String ExampleSaveName(String name) {
        database = dbHelper.getReadableDatabase();

        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("uuid", uuid);

        long insertId = database.insert(Database.TABLE_NAME, null, values);

        Cursor cursor = database.query(Database.TABLE_NAME, allColumns, Database.ID + " = " + insertId, null,null, null, null);
        cursor.moveToFirst(); 

        return cursorToName(cursor);
}
}

通過從我的設備上卸載應用程序可以解決該問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM