android上常规sqlite操作的奇怪行为

时间:2014-05-10 20:45:32

标签: android sqlite android-sqlite

我遇到了一个问题,我已经解决但我仍然想知道为什么 解决方案解决了它。 我编写了一个Android应用程序,在我调试它几次后有一个sqlite数据库 db中的oncreate方法没有被调用(即使之前一切正常) 我将db版本号从1更改为2后,一切正常 即使我通过应用程序管理器卸载了应用程序,也删除了缓存 本地数据库信息。 我的问题如下 - 本地数据库数据是否保存在其他地方? 如果它没有 - 为什么它只在我升级版本号后才起作用 甚至在我删除所有应用相关数据时都没有?

/**
 * A class to handle sqlite reads/writes of user related data to be collected
 */
public class UserDataManager extends SQLiteOpenHelper {

    // Class Variables
    private final String TAG = UserDataManager.class.getSimpleName();

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    public static final String DATABASE_NAME = "tmc";

    // Tables
    private static final String TABLE_USER = "user";

    // Tables and table columns names
    private String CREATE_USER_TABLE;
    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_MAIL = "email";
    private static final String COLUMN_USER_ACTIVE = "user_active";
    private static final String COLUMN_USER_NAME = "name";
    private static final String COLUMN_USER_PASSWORD = "password";
    private static final String COLUMN_USER_PHONE_NUMBER = "phone_number";

    /**
     * Class constructor
     * 
     * @param context
     *            The context to run in
     */
    public UserDataManager(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_USER + " ("
                + COLUMN_USER_ID + " INTEGER PRIMARY KEY NOT NULL, "
                + COLUMN_USER_MAIL + " VARCHAR(64) NOT NULL, "
                + COLUMN_USER_NAME + " VARCHAR(64) NOT NULL, "
                + COLUMN_USER_PASSWORD + " VARCHAR(64) NOT NULL, "
                + COLUMN_USER_PHONE_NUMBER + " VARCHAR(64) NOT NULL, "
                + COLUMN_USER_ACTIVE + " INT NOT NULL);";

        // create the tables
        db.execSQL(CREATE_USER_TABLE);
    }

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

        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

        // Create tables again
        onCreate(db);
    }

    /**
     * Adding a user to the database
     * 
     * @param userId
     *            The created user id
     * @param userName
     *            The user name
     * @param userEmail
     *            The user email
     * @param userPassword
     *            The user password
     * @param userPhoneNumber
     *            The user phone number
     * @param isActive
     *            Set to 1 if the user is active 0 otherwise
     * @return True if the user added successfully false otherwise
     */
    public boolean AddUser(int userId, String userName, String userEmail,
            String userPassword, String userPhoneNumber, boolean isActive) {

        // method variables
        long rowId;
        boolean pass = false;
        int active = isActive ? 1 : 0;
        SQLiteDatabase db = null;
        ContentValues row = null;

        // try to add the user to the db
        try {
            row = new ContentValues();
            db = this.getWritableDatabase();
            db.delete(TABLE_USER, null, null);
            row.put(COLUMN_USER_ID, userId);
            row.put(COLUMN_USER_NAME, userName);
            row.put(COLUMN_USER_MAIL, userEmail);
            row.put(COLUMN_USER_PASSWORD, userPassword);
            row.put(COLUMN_USER_CAR_NUMBER, userPhoneNumber);
            row.put(COLUMN_USER_ACTIVE, active);
            rowId = db.insert(TABLE_USER, null, row);
            if (rowId > -1) {
                pass = true;
            }
        } catch (SQLException exception) {
            Log.e(TAG, exception.getMessage());
        } finally {
            if (db != null) {
                // close database connection
                db.close();
            }
        }
        return pass;
    }

    /**
     * Get the current registered user
     * 
     * @return The id of the column of the registered user
     */
    public int GetRegisteredUserId() {

        // method variables
        int columnIndex = -1;
        int userId = -1;
        SQLiteDatabase db = null;
        Cursor cursor = null;

        // try to get the user from the database
        try {
            db = this.getReadableDatabase();
            cursor = db.query(TABLE_USER, new String[] { COLUMN_USER_ID },
                    null, null, null, null, null);
            if (cursor != null) {
                boolean moved = cursor.moveToFirst();
                if (moved) {
                    columnIndex = cursor.getColumnIndex(COLUMN_USER_ID);
                    if (columnIndex > -1) {
                        userId = cursor.getInt(columnIndex);
                    }
                }
            }
        } catch (SQLException exception) {
            Log.e(TAG, exception.getMessage());
        } finally {
            if (cursor != null)
                // release cursor
                cursor.close();
            if (db != null)
                // close database connection
                db.close();
        }
        return userId;
    }

    /**
     * Get the current user email
     * 
     * @return The id of the column of the registered user
     */
    public String GetRegisteredUserEmail() {

        // method variables
        int columnIndex = -1;
        String userEmail = null;
        SQLiteDatabase db = null;
        Cursor cursor = null;

        // try to get the user from the database
        try {
            db = this.getReadableDatabase();
            cursor = db.query(TABLE_USER, new String[] { COLUMN_USER_MAIL },
                    null, null, null, null, null);
            if (cursor != null) {
                boolean moved = cursor.moveToFirst();
                if (moved) {
                    columnIndex = cursor.getColumnIndex(COLUMN_USER_MAIL);
                    if (columnIndex > -1) {
                        userEmail = cursor.getString(columnIndex);
                    }
                }
            }
        } catch (SQLException exception) {
            Log.e(TAG, exception.getMessage());
        } finally {
            if (cursor != null)
                // release cursor
                cursor.close();
            if (db != null)
                // close database connection
                db.close();
        }
        return userEmail;
    }

    /**
     * Get the current user password
     * 
     * @return The password of the current logged user
     */
    public String GetRegisteredUserPassword() {

        // method variables
        int columnIndex = -1;
        String userPassword = null;
        SQLiteDatabase db = null;
        Cursor cursor = null;

        // try to get the user from the database
        try {
            db = this.getReadableDatabase();
            cursor = db.query(TABLE_USER,
                    new String[] { COLUMN_USER_PASSWORD }, null, null, null,
                    null, null);
            if (cursor != null) {
                boolean moved = cursor.moveToFirst();
                if (moved) {
                    columnIndex = cursor.getColumnIndex(COLUMN_USER_PASSWORD);
                    if (columnIndex > -1) {
                        userPassword = cursor.getString(columnIndex);
                    }
                }
            }
        } catch (SQLException exception) {
            Log.e(TAG, exception.getMessage());
        } finally {
            if (cursor != null)
                // release cursor
                cursor.close();
            if (db != null)
                // close database connection
                db.close();
        }
        return userPassword;
    }

    /**
     * Get number of rows in the user table
     * 
     * @return the number of the rows in the user table (How many users are
     *         saved in the DB)
     */
    public int GetRowCount() {

        // method variables
        int rowsCount = 0;
        SQLiteDatabase db = null;
        Cursor cursor = null;

        // try to get the user from the database
        try {
            db = this.getReadableDatabase();
            cursor = db.query(TABLE_USER, null, null, null, null, null, null);
            if (cursor != null) {
                boolean moved = cursor.moveToFirst();
                if (moved) {
                    do {
                        rowsCount++;
                    } while (cursor.moveToNext());
                }
            }
        } catch (SQLException exception) {
            Log.e(TAG, exception.getMessage());
        } finally {
            if (cursor != null)
                // release cursor
                cursor.close();
            if (db != null)
                // close database connection
                db.close();
        }
        return rowsCount;
    }

    /**
     * Remove a user from the database
     * 
     * @param userId
     *            The user id
     */
    public void LogoutUser() {

        // method variables
        SQLiteDatabase db = null;

        // try to remove a user from the database
        try {
            db = this.getWritableDatabase();
            onUpgrade(db, DATABASE_VERSION, DATABASE_VERSION);
        } catch (SQLException exception) {
            Log.e(TAG, exception.getMessage());
        } finally {
            if (db != null) {
                // close database connection
                db.close();
            }
        }
    }

    /**
     * Set a user to be active or not
     * 
     * @param isActive
     *            1 if the cigarette is active 0 otherwise
     * @return True if the cigarette active field has changed false otherwise
     */
    public boolean SetUserActive(boolean isActive) {
        // method variables
        int rowsAffected;
        int active = isActive ? 1 : 0;
        long userId;
        String userIdString;
        boolean pass = true;
        SQLiteDatabase db = null;
        ContentValues values = null;

        // try to remove a device from the database
        try {
            userId = GetRegisteredUserId();
            if (userId > -1) {
                userIdString = String.valueOf(userId);
                db = this.getWritableDatabase();
                values = new ContentValues();
                values.put(COLUMN_USER_ACTIVE, active);
                rowsAffected = db.update(TABLE_USER, values, COLUMN_USER_ID
                        + " = ?", new String[] { userIdString });
                if (rowsAffected != 1) {
                    pass = false;
                }
            }
        } catch (SQLException exception) {
            Log.e(TAG, exception.getMessage());
        } finally {
            if (db != null) {
                // close database connection
                db.close();
            }
        }
        return pass;
    }
}



备注 -
1.请注意我的设备已植根,因此将数据插入数据库后我更改了777的db文件的权限,这样我就可以从手机上取下它了它是什么(即查询是否通过)
2.抛出的错误是" android.database.sqlite.SQLiteException:没有这样的表:user"


巧克力饼干将被授予任何答案... =)

4 个答案:

答案 0 :(得分:2)

Why did it worked only after I upgraded the version number not even when I erased all the app related data?

  • 您开始使用getReadableDatabase()getWriteableDatabase()或任何其他SQLiteHelper类代码时。第一个方法调用是onCreate(SQLiteDatabase db),它在您的应用程序数据库路径下创建数据库 /data/data/PACKAGE_NAME/databases/tmc(在您的情况下)。

  • 如果您在SQliteHelper中修改数据库结构,则调用的第一个方法是onUpgrage(),它会检查Database_Version是否被修改。如果是,则执行onUpgrade()一系列DROP TABLE IF EXIST后跟onCreate(),再次通过替换以前的数据库文件,在应用程序路径下创建具有新结构的数据库。

  • 使用Application Manager清除缓存数据确实清除了该应用程序的数据库和缓存数据。但SQLiteHelper确实检查了Database_Version的新旧版本。如果新的大于旧的。它会调用onUpgrage(),然后调用onCreate()

  • 当您打算将数据库与Android应用程序一起使用时,它会在/data/data/PACKAGE_NAME/databases/tmc下存储应用程序进程安全性。无法访问数据库文件,除非您已经拥有已安装的Android设备。


可以创建Developer Options或任何您喜欢的内容,只需将数据库从您的应用程序进程拉到SD卡,以获取无根设备。

Copy database file from application process path to SD Card for unrooted devices.

try {
       File sd = Environment.getExternalStorageDirectory();
       File data = Environment.getDataDirectory();
        if (sd.canWrite()) {
        String currentDBPath = "/data/data/" + getPackageName() + "/databases/ZnameDB"; //Your DATABASE_NAME
        String backupDBPath = "ZnameDB_Dev.db"; //DATABASE_COPY_NAME UNDER SDCARD
        File currentDB = new File(currentDBPath);
        File backupDB = new File(sd, backupDBPath);
        if (currentDB.exists()) {
        FileChannel src = new FileInputStream(currentDB).getChannel();
        FileChannel dst = new FileOutputStream(backupDB).getChannel();
        dst.transferFrom(src, 0, src.size());
        src.close();
        dst.close();
        Toast.makeText(SettingsActivity.this, "Database Transfered!", Toast.LENGTH_SHORT).show();
          }
         }
     } catch (Exception e) {
        Log.e(TAG, e.toString());
    }

答案 1 :(得分:1)

回答您的第一个问题,所有数据仅存储在YOUR_PACKAGE / databases / DATABASE.db下。

如果您通过应用程序管理器删除应用程序,则删除所有数据,只需打包。如果卸载应用程序,则清除所有内容,包括包文件夹。即使您将应用安装位置设置为外部SD卡,数据库也会在内部存储。

来自文档:

  

.apk文件保存在外部存储上,但是所有私有用户   数据,数据库,优化的.dex文件和提取的本机代码   保存在内部设备内存中。

SQLiteOpenHelper逻辑很简单:

  • 检查数据库是否存在,如果没有创建新数据库
  • 检索数据库版本,初始值为0,这就是为什么在您的应用程序中,DB版本的最小值为1,至少调用onCreate()方法一次
  • 如果version等于0,则调用onCreate()或
  • 如果版本与您的代码onUpgrade()或onDowngrade()提供的版本不同,则称为

因此,无论何时升级您的方案,都必须增加版本号,因此没有争论,以便让您的应用正常运行。

现在,在你的具体情况下,我只能猜测。我会说删除你的软件包并不是完全成功的,并且留下了一些数据,特别是如果你提到你对DB文件进行了一些手动修改。也许它与您的设备上运行的Android版本有关,但您没有提到它是哪一个。

这就是全部。我希望我的回答令人满意。

答案 2 :(得分:0)

你能执行PRAGMA user_version;在你的adb中获取db版本?根据SQLiteOpenHelper的源代码,SQLite.getVersion()等于SQLiteOpenHelper.mNewVersion,因此不会调用onCreate()方法。当您在db文件上chmod 777时,user_version也将被修改。

答案 3 :(得分:0)

假设在卸载应用程序时未删除数据库,这似乎是合理的。数据库存储在此DDMS/data/data/PACKAGE_NAME/databases/YOUR_DB_FILE。如果您的手机已植根,则只能看到此信息。 如果我错了,请检查这个假设是否正确并纠正我。 感谢