开发者社区 问答 正文

尝试将图像插入sqlite数据库API 21

我是android的新手,所以如果这是一个简单的问题,请原谅我,但是我试图在API 21中将图像插入到数据库中,所以我无法使用Files.readAllBytes。我在这里找到了一些将图像转换为数组的代码,但不确定该如何工作,也不确定其返回的内容。然后,我想使用数组并做一个ContentValues.put("Head", (the array) )。提前谢谢大家。

public boolean insertAvatar(Image Head) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    //File head = new File("C:capaa\\src\\main\\res\\drawable\\head2.png");

    File head = new File("C:capaa\\src\\main\\res\\drawable\\head2.png"); 
    try {
        read(head); // calling the convert method on my head file 
    }catch (IOException e){ }
    ContentValues.put("Head",head); // this is the line im not sure about 

    long ins = db.insert("Avatar", null, contentValues);
    return true;
}

//converts to bytes
public byte[] read(File file) throws IOException {
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1) {
            ous.write(buffer, 0, read);
        }
    }finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
        }

        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return ous.toByteArray();
}

展开
收起
Puppet 2019-12-03 17:32:22 755 分享 版权
阿里云 AI 助理回答

在Android中将图像存储到数据库通常涉及几个步骤:读取文件为字节数组,然后将这个字节数组插入数据库。你的代码已经很接近正确了,但有几个地方需要调整:

  1. 调用read方法并处理返回值:你需要将read(head)方法的返回值(即图像的字节数组)赋给一个变量,然后使用这个变量放入ContentValues

  2. 确保捕获异常:虽然你有异常处理结构,但在实际调用read方法时没有真正处理异常。应该在外层调用处也妥善处理可能抛出的异常。

  3. 使用put方法的正确参数类型:当你将字节数组放入ContentValues时,应确保使用正确的键名,并且因为是字节数组,所以使用putBlob方法而不是简单的put

下面是修改后的代码示例:

public boolean insertAvatar(String imagePath) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    try {
        // 调用read方法并获取返回的字节数组
        byte[] imageData = read(new File(imagePath));
        // 使用putBlob方法将字节数组放入ContentValues
        contentValues.put("Head", imageData);
        
        long ins = db.insert("Avatar", null, contentValues);
        return ins != -1; // 检查插入是否成功
    } catch (IOException e) {
        // 处理读取文件或数据库操作中的异常
        Log.e("DatabaseHelper", "Error inserting image: ", e);
        return false;
    }
}

// 保持你的read方法不变
public byte[] read(File file) throws IOException {
    // ... 你的read方法实现 ...
}

这段代码首先尝试读取指定路径的图像文件为字节数组,然后将这个字节数组通过contentValues.putBlob方法存入数据库的"Head"列。同时,它改进了异常处理逻辑,确保在遇到问题时能够适当地记录错误信息并返回失败状态。记得替换imagePath变量为你实际的图像文件路径,并确认数据库表结构中"Head"列被定义为适合存储二进制数据的类型(通常是BLOB)。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答