代码之家  ›  专栏  ›  技术社区  ›  Ragunath Jawahar cephus

保留不同版本软件的持久信息

  •  2
  • Ragunath Jawahar cephus  · 技术社区  · 14 年前

    我计划写一个软件的免费版本和完整版本。我希望由软件的免费版本存储的信息也可以由完整版本访问(我不想使用内容提供商)。我还想确保软件更新时这些数据不会丢失。我如何做到这一点?

    1 回复  |  直到 14 年前
        1
  •  2
  •   Pentium10    14 年前

    您需要为您的sqlite助手实现一种智能的onUpgrade方法。

    您应该随时准备新的表创建查询,并将其用于升级和传输任何现有数据。注意:onUpgrade方法只对sqlite助手对象运行一次,您需要处理其中的所有表。

    所以建议升级:

    • 开始移动
    • 使用运行表创建 if not exists (我们正在进行升级,因此表可能还不存在,它将失败并删除)
    • List<String> columns = DBUtils.GetColumns(db, TableName);
    • ALTER table " + TableName + " RENAME TO 'temp_" + TableName )
    • 创建新表(最新的表创建模式)
    • columns.retainAll(DBUtils.GetColumns(db, TableName)); )
    • 还原数据( String cols = StringUtils.join(columns, ","); db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s from temp_%s", TableName, cols, cols, TableName)); )
    • DROP table 'temp_" + TableName )

    (这不会处理表降级,如果重命名列,则不会传输现有数据,因为列名不匹配)。

    public static List<String> GetColumns(SQLiteDatabase db, String tableName) {
        List<String> ar = null;
        Cursor c = null;
        try {
            c = db.rawQuery("select * from " + tableName + " limit 1", null);
            if (c != null) {
                ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));
            }
        } catch (Exception e) {
            Log.v(tableName, e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (c != null)
                c.close();
        }
        return ar;
    }
    
    public static String join(List<String> list, String delim) {
        StringBuilder buf = new StringBuilder();
        int num = list.size();
        for (int i = 0; i < num; i++) {
            if (i != 0)
                buf.append(delim);
            buf.append((String) list.get(i));
        }
        return buf.toString();
    }