簡體   English   中英

Android讀寫臨時文件

[英]Android read-write temporary Files

嗨,我已創建此方法來執行以下操作:

-it采用位圖

- 創建臨時文件

- 壓縮位圖並將其放入臨時文件中

- 打開臨時文件

-read bytes >>>問題在我的代碼中

- 在sqlite db中保存這些字節

-retrieve來自sqlite db的字節

- 將這些字節再次設置為圖像位圖

我知道我知道完全無用,但這是我發現做我想做的事情的唯一方法,那就是:

- 壓縮位圖

- 將它保存到sqlite數據庫

所以這是代碼。 該程序只是在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());
    } 

}

我怎么能解決這個問題? 謝謝

我猜你有一個NullPointerException,它似乎是正常的,因為你調用read時你的緩沖區是null。

您必須使用預期大小實例化緩沖區。

嘗試以這種方式初始化字節數組:

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

希望能幫助到你

Jokahero

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM