2017-07-12 13 views
-4

私のアンドロイドアプリケーションの外部ディレクトリに画像を保存できませんでした。私は自分自身を練習し、同じ問題を探しましたが、何も私を助けませんでした。 私がしたいのは、そのイメージを持つダイアログを表示し、それを保存し、保存した場合に表示するオプションをユーザに与えることです。 しかし、それは常にout.flush()でnullポインタ例外をキャッチします。マシュマロとアッパーで ロリポップでうまく動作します。 権限が追加されました:外部ディレクトリに画像を保存できませんでした

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

コードはわかりやすく表示されます。どんな助けも高く評価されます。

private void display_image(String url, String title) { 

     Dialog dialog = new Dialog(MainActivity.this); 
     dialog.setContentView(R.layout.dialog_display_images); 
     dialog.setTitle(title); 

     WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); 
     layoutParams.copyFrom(dialog.getWindow().getAttributes()); 

     layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; 
     layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; 

     dialog.show(); 
     dialog.getWindow().setAttributes(layoutParams); 

     ImageView iv = (ImageView)dialog.findViewById(R.id.image_here); 
     final InputStream in; 
     Bitmap img=null; 
     final Bitmap imgcpy; 

     try { 
      in = getAssets().open(url); 
      img = BitmapFactory.decodeStream(in); 
      iv.setImageBitmap(img); 

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

     imgcpy = img; 

     final FloatingActionButton save = (FloatingActionButton)dialog.findViewById(R.id.fab_save); 
     save.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       final String filePath = Environment.getExternalStorageDirectory().toString(); 
       File dir = new File(filePath + "/app_images"); 
       dir.mkdirs(); 
       Random generate = new Random(); 
       int n = 10000; 
       n = generate.nextInt(n); 
       String fName = "Image-" + n + ".jpg"; 

       final File file = new File(dir, fName); 
       if (file.exists()) { 
        file.delete(); 
       } 
       try { 
        FileOutputStream out = new FileOutputStream(file); 
        imgcpy.compress(Bitmap.CompressFormat.JPEG, 90, out); 
        out.flush(); 
        out.close(); 
        new AlertDialog.Builder(MainActivity.this) 
          .setTitle("Image Saved Successfully") 
          .setIcon(R.drawable.ic_save) 
          .setMessage("Image saved at: " + file.getAbsolutePath()) 
          .setNeutralButton("OK", new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, int which) { 
            dialog.dismiss(); 
           } 
          }) 
          .setPositiveButton("Open", new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, int which) { 
            Toast.makeText(getApplicationContext(), "Opening...", Toast.LENGTH_SHORT).show(); 
            Intent intent = new Intent(Intent.ACTION_VIEW); 
            intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "image/*"); 
            startActivity(intent); 
           } 
          }) 
          .create().show(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
        Toast.makeText(MainActivity.this, "Could not save image", Toast.LENGTH_SHORT).show(); 
       } catch (NullPointerException e) { 
        Toast.makeText(MainActivity.this, "Could not save image", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }); 
    } 

答えて

0

APIレベル6.0または実行時のアクセス許可が必要以上:

if (ContextCompat.checkSelfPermission(context, 
     android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
    ActivityCompat.requestPermissions(MainActivity.this, 
      new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE); 
} 

そして、あなたの活動でこのメソッドオーバーライドする:マシュマロ、あなたが許可をチェックする必要があり、その上のAPIで

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    switch (requestCode) { 
     case Constant.REQUEST_CODE_ASK_PERMISSIONS: 
      if (grantResults!=null) { 
       if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        //Call ur save method here 
       } else { 
        Toast.makeText(this, "Please enable write permission from ,Toast.LENGTH_SHORT).show(); 

       } 
      } 
      break; 
     default: 
      super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    } 
} 
0

を実行時間

要求許可

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

onRequestPermissionsResult

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case 1: { 

      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       // permission was granted, yay! Do the save image stuff 

      } else { 
       // permission denied, boo! Disable the 

       Toast.makeText(this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show(); 
      } 
      return; 
     } 
    } 
} 
save.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        if(permissionisnotgranted){ 
         ActivityCompat.requestPermissions(mActivity, 
         new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
         1); 
       } 
       else 
        { 
        //do stuff for save image 
        } 
       } 
    }); 
0

ディレクトリおよびイメージファイルを作成するには、このメソッドを使用して結果を取得:

private File createImageFile() throws IOException { 

    // Create an image file name 
    Random generate = new Random(); 
    int n = 10000; 
    n = generate.nextInt(n); 

    String nValue = String.valueOf(n); 
    String fName = "Image-" + n; 


    String filePath = Environment.getExternalStorageDirectory().toString(); 
    File dir = new File(filePath + "/app_images"); 

    if (!dir.exists()) { 
     dir.mkdirs(); 
    } 

    File image = File.createTempFile(
      fName,   /* prefix */ 
      ".jpg",   /* suffix */ 
      dir    /* directory */ 
    ); 

    // Save a file: path for use with ACTION_VIEW intents 
    mCurrentPhotoPath = image.getAbsolutePath(); 
    Log.e("mCurrentPhotoPath", mCurrentPhotoPath + " ++++"); //Prints you the image file path 
    return image; 
} 

そして、あなたが好きな場所、このような上記のメソッドを呼び出す:

try { 
    //photoFile = createImageFile(); 
    File photoFile = createImageFile(); 
} catch (IOException ex) { 
    // Error occurred while creating the File 
    ex.printStackTrace(); 
    Log.e("IO_EX", ex + ""); 
} 

そして、マニフェストに以下のパーミッションを与えます:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

すべて最高です!

関連する問題