在Android中保存位图时出现NullPointerException

时间:2013-06-01 13:32:04

标签: android bitmap android-image

我有一段代码用于在SD卡中保存位图,但我有一个简单的空指针异常错误...

String sdcardState = android.os.Environment.getExternalStorageState();      
    String destPath = null;
/////////////////////////////////////////////////////////////////////////////////////
int indexSepar=absoluteFilePathSource.lastIndexOf(File.separator);//THIS IS THE ERROR LINE
////////////////////////////////////////////////////////////////////////////////////
    int indexPoint=absoluteFilePathSource.lastIndexOf(".");
    if(indexPoint<=1)
        indexPoint=absoluteFilePathSource.length();
    String fileNameDest=absoluteFilePathSource.substring(indexSepar+1, indexPoint);

    fileNameDest+="_AMNET";
    if (sdcardState.contentEquals(android.os.Environment.MEDIA_MOUNTED))
        destPath = android.os.Environment.getExternalStorageDirectory()
                + File.separator + fileNameDest+".png";

    OutputStream fout = null;
    try {

        Log.v("Path", destPath);
        fout = new FileOutputStream(destPath);          
        destBitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
        if(!IS_ENCODE_IMAGE_CH)
            Media.insertImage(getContentResolver(),destPath, fileNameDest, "AMNET Encoded");
        result=Uri.parse("file://"+destPath);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result)); 
        fout.flush();
        fout.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    destBitmap.recycle();

这是我的日志猫:

06-01 13:20:52.239: E/AndroidRuntime(1340): FATAL EXCEPTION: Thread-112
06-01 13:20:52.239: E/AndroidRuntime(1340): java.lang.NullPointerException
06-01 13:20:52.239: E/AndroidRuntime(1340):     at ir.megadev.amnet.MainActivity.encode(MainActivity.java:844)
    06-01 13:20:52.239: E/AndroidRuntime(1340):     at ir.megadev.amnet.MainActivity.access$2(MainActivity.java:769)
    06-01 13:20:52.239: E/AndroidRuntime(1340):     at ir.megadev.amnet.MainActivity$10$1.run(MainActivity.java:430)
    06-01 13:20:52.239: E/AndroidRuntime(1340):     at java.lang.Thread.run(Thread.java:856)

1 个答案:

答案 0 :(得分:3)

absoluteFilePathSource为空