2016-08-25 14 views
0

私は簡単なノートブックアプリケーションを作っています。ノートブックには画像が添付されています。私は写真をうまく撮ることができ、写真が撮影された後、メモ内の画像ビューに正しく表示されます。メモが保存されると、写真へのパスがデータベースに保存されます。パスは正しく保存されます。次に、ユーザーがメモを開くと、データベース内のパスが正しく見つかる - しかし、私はイメージビューに読み込むことができません。むしろ、イメージビューは白くなります。画像を保存するフォルダを手作業で調べると、画像が電話やSDカードに保存されていないことがわかります。保存方法はわかりません。私はインターネットとStackOverflowの全面を見てきましたが、解決策を見いだせませんでした。Android - ファイルパスから画像を表示できません/画像をデバイスに保存できません

public void onIcTakePhotoClick(View icon) { 
    File imageFile = null; 
    Intent takePictureIntent; 

    try { 
     imageFile = ImageHelper.createImageFile(this); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    if (imageFile != null) { 
     mImagePath = imageFile.getAbsolutePath(); 
     //mImagePath = ImageHelper.getImagePath(imageFile); 
     takePictureIntent = ImageHelper.dispatchTakePictureIntent(this, imageFile); 
     startActivityForResult(takePictureIntent, ImageHelper.REQUEST_IMAGE_CAPTURE); 
    } else { 
     // error message 
    } 
} 

上記の全ての(パス、ファイルを作成し、その意図は)うまく動作:

public static File createImageFile(Context context) throws IOException { 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); 
    File image = File.createTempFile(
      imageFileName, /* prefix */ 
      ".jpg",   /* suffix */ 
      storageDir  /* directory */ 
    ); 

    return image; 
} 

public static Intent dispatchTakePictureIntent(Context context, File photoFile) { 
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    // Ensure that there's a camera activity to handle the intent 
    if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) { 
     // Continue only if the File was successfully created 
     Uri photoURI = FileProvider.getUriForFile(context, 
       "com.bergdahl.notebook.fileprovider", 
       photoFile); 
     //takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
     takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); 
     return takePictureIntent; 
    } 
    return null; 
} 

ファイルパスはこのように見える終わる:「/ストレージ//0 /アンドロイドをエミュレート/data/com.myname.notebook/files/Pictures/JPEG_20160824_213643_135920553.jpg "次は結果を得る:

public static void handleCameraPhoto(Activity context, ImageView imageView, String imagePath) { 
    if (imagePath != null) { 
     ImageHelper.setPic(imagePath, imageView); 
     ImageHelper.galleryAddPic(context, imagePath); 
    } 
} 

public static void setPic(String imagePath, ImageView imageView) { 

    /* There isn't enough memory to open up more than a couple camera photos */ 
    /* So pre-scale the target bitmap into which the file is decoded */ 

    /* Get the size of the ImageView */ 
    int targetW = imageView.getWidth(); 
    int targetH = imageView.getHeight(); 

    /* Get the size of the image */ 
    BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
    bmOptions.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(imagePath, bmOptions); 
    int photoW = bmOptions.outWidth; 
    int photoH = bmOptions.outHeight; 

    /* Figure out which way needs to be reduced less */ 
    int scaleFactor = 1; 
    if ((targetW > 0) || (targetH > 0)) { 
     scaleFactor = Math.min(photoW/targetW, photoH/targetH); 
    } 

    /* Set bitmap options to scale the image decode target */ 
    bmOptions.inJustDecodeBounds = false; 
    bmOptions.inSampleSize = scaleFactor; 
    bmOptions.inPurgeable = true; 

    /* Decode the JPEG file into a Bitmap */ 
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions); 

    /* Associate the Bitmap to the ImageView */ 
    imageView.setImageBitmap(bitmap); 
    imageView.setVisibility(View.VISIBLE); 
} 

public static void galleryAddPic(Activity context, String imagePath) { 
    Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE"); 
    File f = new File(imagePath); 
    Uri contentUri = Uri.fromFile(f); 
    mediaScanIntent.setData(contentUri); 
    context.sendBroadcast(mediaScanIntent); 
} 

そして最後に、ノート後で開放のためのコード:

if (mNote.getFilePath() != null) { 
     mImagePath = mNote.getFilePath(); 
     //ImageHelper.handleCameraPhoto(this, imageView, mNote.getFilePath()); 

     //File file = new File(mImagePath); 
     //imageView.setImageDrawable(Drawable.createFromPath(mImagePath)); 

     //Uri uri = Uri.parse("file:" + mNote.getFilePath()); 
     //imageView.setImageURI(uri); 
    } 
私はAndroidのチーム( https://developer.android.com/training/camera/photobasics.html)によって作成されたメソッドを使用している

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) { 
     case ImageHelper.REQUEST_IMAGE_CAPTURE: { 
      if (resultCode == RESULT_OK) { 
       ImageHelper.handleCameraPhoto(this, imageView, mImagePath); 
      } 
      break; 
     } 
    } 
} 

マニフェストでは、外部ストレージへの書き込み権限を指定しました。繰り返しますが、デバイスに取り込んだイメージを保存する方法を理解する助けが必要です。次回にユーザーがメモを開くときにイメージビューに読み込むことができます。ヘルプのために事前にありがとう!

編集:私はimage.createNewFile()メソッドを試しましたが、結果は悲しいことに同じです。論理テストは真です。

public static File createImageFile(Context context) throws IOException { 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); 

    /* 
    File image = File.createTempFile(
      imageFileName, 
      ".jpg", 
      storageDir 
    ); 
    */ 

    File image = new File(storageDir, imageFileName + ".jpg"); 

    if (!image.exists()) { 
     try { 
      boolean test = image.createNewFile(); 
      Log.d("createImageFile", test + ""); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    return image; 
} 

EDIT again:イメージが正しくエミュレータに表示されるようになりましたが、実際のデバイスでは機能しません。エミュレータ6.0、私のデバイス6.0.1を実行します。私のデバイスは許可を与えており、外部ストレージを持っています。私はディレクトリを変更しようとしていましたが、成功しませんでした。

+0

のAndroidデバイスのバージョンを使用を追加しますか? –

+0

一時ファイルの代わりに通常のファイルを作成します。 –

+0

Android 6.0.1を実行している端末でテストしています。私はファイル作成には全く新しいので、通常のファイルを作成する方法はわかりません。どのように私が1つを作成するかの例を私に提供できますか? – LGW

答えて

0

は、Android 6で

mImagePath = "file:" + imageFile.getAbsolutePath(); 
+0

返信いただきありがとうございます!残念ながら、私はすでにこれを試しましたが、それは違いはありません。 – LGW

+0

No prob :) ImageHelper.dispatchTakePictureIntentにimageFileの代わりにmImagePathを渡そうとしましたか?ファイルそのものの代わりにファイルパスを渡します。 – Aaron

0

mImagePath = imageFile.getAbsolutePath(); 

を交換してください、あなたはあなたのマニフェストでそれを宣言した場合でも、インストール後に、読み取り/書き込み権限を持っていません。

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

をクエリを実行せずにアプリのアプリの設定メニューにアクセス権を与えることができ、テストの目的のために:あなたは、実行時に最初にそれを聞いています。

+0

返信いただきありがとうございます!これは後で非常に便利ですが、私はすでに自分のデバイスに手動で適切な権限を与えているので、残念ながらこれは問題ではありません。 – LGW

0

許可ランタイムを追加します。

if (Build.VERSION.SDK_INT >= 23) 
    { 
     if (checkPermission()) 
     { 
      // Code for above or equal 23 API Oriented Device 
      // Create a common Method for both 
    ///take camera caputure code 

     } else { 
      requestPermission(); 
     } 
    } 
    else 
    { 

     // Code for Below 23 API Oriented Device 
     // Create a common Method for both 
    } 

のcheckPermission()requestPermission()

private boolean checkPermission() { 
    int result = ContextCompat.checkSelfPermission(Your_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE); 
    if (result == PackageManager.PERMISSION_GRANTED) { 
     return true; 
    } else { 
     return false; 
    } 
} 

private void requestPermission() { 

    if (ActivityCompat.shouldShowRequestPermissionRationale(Your_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { 
     Toast.makeText(Your_Activity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show(); 
    } else { 
     ActivityCompat.requestPermissions(Your_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); 
    } 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case PERMISSION_REQUEST_CODE: 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       Log.e("value", "Permission Granted, Now you can use local drive ."); 
      } else { 
       Log.e("value", "Permission Denied, You cannot use local drive ."); 
      } 
      break; 
    } 
} 
+0

お返事ありがとうございました!これは後で非常に便利ですが、私はすでに自分のデバイスに手動で適切な権限を与えているので、残念ながらこれは問題ではありません。 – LGW

+0

ImageHelperを提供できますか? –

+0

ああ、私のImageHelperクラスのすべての単一のメソッドは元の質問にあります:)そこにリストされていない唯一のものはあまり興味のない基本的なリクエストコード(public static final int REQUEST_IMAGE_CAPTURE = 0;)です。 – LGW

関連する問題