2017-10-28 113 views
-1

我的问题是,当我点击图片,它显示了保存的信息,但照片不会saved.I还允许使用外部存储WRITE_EXTERNAL_STORAGE保存图像

public void onClick(View v) { 
    if(isExternalStorageWriteable()) { 
     FileOutputStream outputStream; 
     Bitmap bitmap = BitmapFactory.decodeResource(getResources(), 
       R.drawable.img3); 
     File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyImage.png"); 
     try { 
       outputStream = new FileOutputStream(file); 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); 
      outputStream.flush(); 
      outputStream.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Toast.makeText(this,"Pic Created : "+file,Toast.LENGTH_SHORT) 
       .show(); 
    } else { 
      Toast.makeText(this,"SDCard Not is Ready",Toast.LENGTH_SHORT) 
        .show(); } } 
public boolean isExternalStorageWriteable() 
{ 
    String state = Environment.getExternalStorageState(); 
    return Environment.MEDIA_MOUNTED.equals(state); } 

enter image description here

+0

你的'Toast'关于创建的图片是错误的,即使发生错误也会显示出来。检查你的'logcat',可能会打印一些异常。用异常堆栈跟踪更新你的问题 – pleft

回答

1

“我还允许在清单中访问外部存储器WRITE_EXTERNAL_STORAGE”,或者您在运行时询问权限?

我想你只有在Android版本> = 23(6.0)的设备上有这个问题。 您应该检查,如果你有这样做之前在外部存储写的权限,如果你要问权限:

ContextCompat.checkSelfPermission(thisActivity, Manifest.permission. WRITE_EXTERNAL_STORAGE); 

ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); 

https://developer.android.com/training/permissions/requesting.html

如果授予权限检查堆栈跟踪,并张贴在这里,可以肯定的是,“Pic Created”烤面包应该留在块末端的try-catch中,并且在catch块内部,你必须启动一个负面烤面包。