SQLite存取图片

//向数据库中插入数据信息

 public long inserUser(User user) {
        // 获得SQLiteDatebase进行数据库操作
        db = dbHelper.getWritableDatabase();
        // 参数绑定对象
        values = new ContentValues();

        values.put(DBInfo.Table.USER_ID, user.getUser_id());
        values.put(DBInfo.Table.USER_NAME, user.getUser_name());
        values.put(DBInfo.Table.TOKEN, user.getToken());
        values.put(DBInfo.Table.TOKEN_SECRET, user.getToken_secret());
        values.put(DBInfo.Table.DESCRIPTION, user.getDescription());

//图片向SQLite数据库中进行插入的时候进行的转换操作  userHead 变量类型  Drawable

        // 将图片类型的数据进行存储的时候,需要进行转换才能存储到BLOB类型中
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 为了实现数据存储,需要将数据类型进行转换
        BitmapDrawable newHead = (BitmapDrawable) user.getUser_head();
        // 将数据进行压缩成PNG编码数据,存储质量100%
        newHead.getBitmap().compress(CompressFormat.PNG, 100, os);
        // 存储图片类型数据
        values.put(DBInfo.Table.USER_HEAD, os.toByteArray());
        // 进行插入操作,返回行号
        long rowId = db.insert(DBInfo.Table.USER_TABLE, DBInfo.Table.USER_NAME,
                values);
        // 释放资源
        db.close();

        return rowId;
    }

//从数据库中读取所有用户信息
  public List<User> findAllUsers() {
        db = dbHelper.getReadableDatabase();
        List<User> userList = null;
        User user = null;
        Cursor cursor = db.query(DBInfo.Table.USER_TABLE, columns, null, null,
                null, null, null);

        if (cursor != null && cursor.getCount() > 0) {
            userList = new ArrayList<User>(cursor.getCount());
            while (cursor.moveToNext()) {
                user = new User();

                user.setId(cursor.getLong(cursor
                        .getColumnIndex(DBInfo.Table._ID)));
                user.setUser_id(cursor.getString(cursor
                        .getColumnIndex(DBInfo.Table.USER_ID)));
                user.setUser_name(cursor.getString(cursor
                        .getColumnIndex(DBInfo.Table.USER_NAME)));
                user.setToken(cursor.getString(cursor
                        .getColumnIndex(DBInfo.Table.TOKEN)));
                user.setToken_secret(cursor.getString(cursor
                        .getColumnIndex(DBInfo.Table.TOKEN_SECRET)));
                user.setDescription(cursor.getString(cursor
                        .getColumnIndex(DBInfo.Table.DESCRIPTION)));
//从数据库中对数据进行读取

                byte[] byteHead = cursor.getBlob(cursor
                        .getColumnIndex(DBInfo.Table.USER_HEAD));

                ByteArrayInputStream is = new ByteArrayInputStream(byteHead);
                Drawable userHead = Drawable.createFromStream(is, "image");
                user.setUser_head(userHead);

                userList.add(user);
            }
        }
        cursor.close();
        db.close();

        return userList;
    }
}
//程序中获取ImageView对象

 private  ImageView user_head;

你可能感兴趣的:(数据库,sqlite,user,table,null,存储)