SQLite数据库适用于模拟器,但不适用于设备

时间:2014-04-01 10:56:33

标签: java android sqlite

我在我的Android应用程序中使用sqlite数据库。我在android中的数据库文件夹中预创建数据库。数据库已创建并在模拟器中正常工作,但当我在手机中运行相同的代码时,我会收到错误。

以下是有关如何在数据库文件夹中预创建数据库的代码。

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

3 个答案:

答案 0 :(得分: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
    }
}

}

答案 1 :(得分:0)

创建数据库对象:

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

答案 2 :(得分:0)

通过从我的设备卸载应用程序解决了这个问题。