简体   繁体   English

Android读写临时文件

[英]Android read-write temporary Files

Hi I have created this method to do the folowing: 嗨,我已创建此方法来执行以下操作:

-it takes a bitmap -it采用位图

-creates temp file - 创建临时文件

-compress bitmap and put it in temp file - 压缩位图并将其放入临时文件中

-open temp file - 打开临时文件

-read bytes >>>problem is here in my code -read bytes >>>问题在我的代码中

-save these bytes in sqlite db - 在sqlite db中保存这些字节

-retrieve bytes from sqlite db -retrieve来自sqlite db的字节

-set those bytes as image bitmap again - 将这些字节再次设置为图像位图

I know I know totally useless but this is the only way I have found to do what I want to achieve which is: 我知道我知道完全无用,但这是我发现做我想做的事情的唯一方法,那就是:

-compress a bitmap - 压缩位图

-save it to sqlite database - 将它保存到sqlite数据库

so here is the code. 所以这是代码。 the program just crashes at in.read(bb): 该程序只是在in.read(bb)崩溃:

private void updateBitmapData() {
    File file = null;

    FileOutputStream stream = null;

    try {
        file = File.createTempFile("image", null, getBaseContext().getFilesDir());
        stream = new FileOutputStream(file);
        System.out.println(thumbnail.getRowBytes());
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 50, stream);

        stream.close();

        FileInputStream in=new FileInputStream(file);

        byte[] bb = null;
        in.read(bb); //crash
        in.close();
        System.out.println("despues compression"+bb.length);

        DBAdapter db=new DBAdapter(getApplicationContext());
        db.insertData(bb);
        Cursor c=db.getLastImage();
        if(c.moveToFirst()){
            bb=c.getBlob(0);
        }
        c.close();
        db.close();
        im.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e("NuevaIncidencia", e.getLocalizedMessage());
        im.setImageBitmap(thumbnail);
    }catch (IOException e1) {
        Log.e("NuevaIncidencia", e1.getLocalizedMessage());
        e1.printStackTrace();
        im.setImageBitmap(thumbnail);
    } catch (Exception e2){
        e2.printStackTrace();
        //Log.e("NuevaIncidencia", e2.getLocalizedMessage());
    } 

}

How could I solve this problem? 我怎么能解决这个问题? thanks 谢谢

I guess you got a NullPointerException, and it seems to be normal because your buffer is null when you call read. 我猜你有一个NullPointerException,它似乎是正常的,因为你调用read时你的缓冲区是null。

You have to instantiate the buffer with the expected size. 您必须使用预期大小实例化缓冲区。

Try initializing your byte array this way: 尝试以这种方式初始化字节数组:

byte[] bb = new byte[file.length()];

Hope it helps 希望能帮助到你

Jokahero Jokahero

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM