gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:24:16 25 4
gpt4 key购买 nike

我遇到了一个我已经解决的问题,但我仍然想知道为什么解决方案解决了它。经过几次调试后,我编写了一个具有 sqlite 数据库的 android 应用程序数据库中的 oncreate 方法没有被调用(即使之前一切正常)在我将数据库版本号从 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. 请注意,我的设备已获得 root 权限,因此在将数据插入数据库后
更改 777 数据库文件的权限,以便我可以将其从手机中拉出以查看
里面有什么(即查询是否通过)
2. 抛出的错误是“android.database.sqlite.SQLiteException: no such
table: user ”


任何答案都将获得巧克力曲奇... =)

最佳答案

为什么我升级了版本号后,清除了所有应用程序相关数据却没有用?

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

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

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

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


可以创建开发人员选项或任何您喜欢的东西,只是为了将数据库从您的应用程序进程拉到 SD 卡,以用于没有开启Root的设备。

将数据库文件从应用程序进程路径复制到 SD 卡,用于没有开启Root的设备。

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

关于android - android 上常规 sqlite 操作的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23586119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com