我有一个问题,我已经解决但我仍然想知道为什么
解决方案解决了它.
我编写了一个 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);
            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,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);
            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);
            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);
            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);
            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权限,以便我可以从手机中取出它以查看其中的内容(即查询是否通过)
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(),它将通过替换以前的数据库文件再次在应用程序路径下创建具有新结构的数据库.
>使用Application Manager清除缓存数据确实清除了该应用程序的数据库和缓存数据.但sqliteHelper确实检查了新旧的Database_Version.如果新的大于旧的.它调用onUpgrage()后跟onCreate().
>当您打算将数据库与Android应用程序一起使用时,它会在/ data / data / PACKAGE_NAME / databases / tmc下存储应用程序进程安全性.除非您已经拥有已安装的Android设备,否则无法访问数据库文件.

您可以创建开发人员选项或任何您喜欢的内容,以便将数据库从您的应用程序进程拉到SD卡以获取无根设备.

将数据库文件从应用程序进程路径复制到SD卡,以获取无根设备.

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,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上的regualr sqlite操作的奇怪行为的更多相关文章

  1. html5 移动端视频video的android兼容(去除播放控件、全屏)

    这篇文章主要介绍了html5 移动端视频video的android兼容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. 详解前端HTML5几种存储方式的总结

    本篇文章主要介绍了前端HTML5几种存储方式的总结 ,主要包括本地存储localstorage,本地存储sessionstorage,离线缓存(application cache),Web SQL,IndexedDB。有兴趣的可以了解一下。

  3. PhoneGap / iOS上的SQLite数据库 – 超过5mb可能

    我误解了什么吗?Phonegap中的sqlitedbs真的有5mb的限制吗?我正在使用Phonegap1.2和iOS5.解决方法您可以使用带有phonegap插件的原生sqliteDB,您将没有任何限制.在iOS5.1中,Websql被认为是可以随时删除的临时数据…

  4. ios – 备份.sqlite(核心数据)

    我有一个基于核心数据的应用程序,它使用DropBox备份和恢复数据.我备份的方式非常简单.我复制用户的保管箱上的.sqlite文件.现在我的备份和恢复功能正常.问题出在.sqlite文件本身.看来.sqlite文件不完整.我在我的应用程序中输入了大约125个条目并进行了备份.备份出现在我的DropBox中但是当我使用.sqlite资源管理器工具查看内容时,我只看到第117个记录的记录.我尝试更新第

  5. ios – 多个NSPersistentStoreCoordinator实例可以连接到同一个底层SQLite持久性存储吗?

    我读过的关于在多个线程上使用CoreData的所有内容都讨论了使用共享单个NSPersistentStoreCoordinator的多个NSManagedobjectContext实例.这是理解的,我已经使它在一个应用程序中工作,该应用程序在主线程上使用CoreData来支持UI,并且具有可能需要一段时间才能运行的后台获取操作.问题是NSPersistentStoreCoordinator会对基础

  6. ios – 设置DataBase的加密密钥(Sybase Unwired Platform)

    目前,我可以通过执行以下操作为本地数据库设置加密密钥:因此,当我的用户成功登录时,我收到以下错误:我认为正在发生的是,虽然数据库已成功创建,但仍然是加密的.我该如何解密?解决方法实际上这很简单,我每次开始会话时都需要这样做:

  7. ios – 使用SQLite和CoreData进行批量插入

    我有一个使用sqlite作为持久性存储的CoreData模型.在对每条记录进行一些处理之后,我需要插入大量的行.有没有办法将这些命令发送到sqlite我需要加快处理时间,因为它需要几个小时才能完成.任何提示将不胜感激.谢谢解决方法将商店添加到商店协调员时,可以指定编译指示:(改编自PersistentStoreFeatures)我强烈建议您阅读“有效导入数据”.相关文档:NSSQLitePragm

  8. ios – 领域:如何获取数据库的当前大小

    是否有RealmAPI方法使用RealmSwift作为数据存储来获取我的RealmSwift应用程序的当前数据库大小?

  9. ios – 升级到Xcode 7时的SQLITE:Segmentation Fault 11

    我已更新到Xcode7.当我尝试构建时,构建失败并显示“由于信号命令失败:分段错误:11”.我删除了sqlite框架,然后重新加载sqlite(清理项目)并发生同样的错误.同时删除foder/library/developer/xcode在Xcode6上完美运行.有些人可以帮忙错误:0:错误:无法执行命令:分段错误:11:0:错误:swift前端命令因信号失败(使用-v查看调用)解决方法>从以下位

  10. ios – 访问文件属性与访问sqlite记录

    >看到上述结果后,我决定选择attributesOfItemAtPath方法.还有什么我不是考虑传递sqlite?

随机推荐

  1. bluetooth-lowenergy – Altbeacon库无法在Android 5.0上运行

    昨天我在Nexus4上获得了Android5.0的更新,并且altbeacon库停止了检测信标.似乎在监视和测距时,didEnterRegion和didRangeBeaconsInRegion都没有被调用.即使RadiusNetworks的Locate应用程序现在表现不同,一旦检测到信标的值,它们就不再得到更新,并且通常看起来好像信标超出了范围.我注意到的一点是,现在在logcat中出现以下行“B

  2. android – react-native动态更改响应者

    我正在使用react-native进行Android开发.我有一个视图,如果用户长按,我想显示一个可以拖动的动画视图.我可以使用PanResponder实现这一点,它工作正常.但我想要做的是当用户长按时,用户应该能够继续相同的触摸/按下并拖动新显示的Animated.View.如果您熟悉Google云端硬盘应用,则它具有类似的功能.当用户长按列表中的任何项目时,它会显示可拖动的项目.用户可以直接拖

  3. android – 是否有可能通过使用与最初使用的证书不同的证书对其进行签名来发布更新的应用程序

    是否可以通过使用与最初使用的证书不同的证书进行签名来发布Android应用程序的更新?我知道当我们尝试将这样的构建上传到市场时,它通常会给出错误消息.但有没有任何出路,比如将其标记为主要版本,指定市场中的某个地方?解决方法不,你不能这样做.证书是一种工具,可确保您是首次上传应用程序的人.所以总是备份密钥库!

  4. 如何检测Android中是否存在麦克风?

    ..所以我想在让用户访问语音输入功能之前检测麦克风是否存在.如何检测设备上是否有麦克风.谢谢.解决方法AndroidAPI参考:hasSystemFeature

  5. Android – 调用GONE然后VISIBLE使视图显示在错误的位置

    我有两个视图,A和B,视图A在视图B上方.当我以编程方式将视图A设置为GONE时,它将消失,并且它正下方的视图将转到视图A的位置.但是,当我再次将相同的视图设置为VISIBLE时,它会在视图B上显示.我不希望这样.我希望视图B回到原来的位置,这是我认为会发生的事情.我怎样才能做到这一点?编辑–代码}这里是XML:解决方法您可以尝试将两个视图放在RelativeLayout中并相对于彼此设置它们的位置.

  6. android – 获得一首歌的流派

    我如何阅读与歌曲相关的流派?我可以读这首歌,但是如何抓住这首歌的流派,它存放在哪里?解决方法检查此代码:

  7. android – 使用textShadow折叠工具栏

    我有一个折叠工具栏的问题,在展开状态我想在文本下面有一个模糊的阴影,我使用这段代码:用:我可以更改textColor,它可以工作,但阴影不起作用.我为阴影尝试了很多不同的值.是否可以为折叠文本投射阴影?

  8. android – 重用arm共享库

    我已经建立了armarm共享库.我有兴趣重用一个函数.我想调用该函数并获得返回值.有可能做这样的事吗?我没有任何头文件.我试过这个Android.mk,我把libtest.so放在/jni和/libs/armeabi,/lib/armeabi中.此时我的cpp文件编译,但现在是什么?我从objdump知道它的名字编辑:我试图用这个android.mk从hello-jni示例中添加prebuild库:它工作,但libtest.so相同的代码显示以下错误(启动时)libtest.so存在于libhello-j

  9. android – 为NumberPicker捕获键盘’Done’

    我有一个AlertDialog只有一些文本,一个NumberPicker,一个OK和一个取消.(我知道,这个对话框还没有做它应该保留暂停和恢复状态的事情.)我想在软键盘或其他IME上执行“完成”操作来关闭对话框,就像按下了“OK”一样,因为只有一个小部件可以编辑.看起来处理IME“Done”的最佳方法通常是在TextView上使用setonEditorActionListener.但我没有任何Te

  10. android – 想要在调用WebChromeClient#onCreateWindow时知道目标URL

    当我点击一个带有target=“_blank”属性的超链接时,会调用WebChromeClient#onCreateWindow,但我找不到新的窗口将打开的新方法?主页url是我唯一能知道的东西?我想根据目标网址更改应用行为.任何帮助表示赞赏,谢谢!

返回
顶部