2016-10-20 8 views
0

nullのオブジェクトです。ユーザーは写真を撮る必要があり、次にこれがFirebase Storageに送信されます。しかし、onActivityResultではsthが間違っています。OnActivityResult:ウリとのgetDataは、キャプチャ時に私がウリのオブジェクトに問題がある写真

私は(あまりにもhttps://developer.android.com/training/camera/photobasics.html、StackOverflowの)話題をたくさん読んで、何もこのコードで動作しません。

エラーがある:以下はNULLオブジェクト参照に

を仮想メソッド 'java.lang.Stringでandroid.net.Uri.getLastPathSegmentを()' 起動する

試みコードです。 URIが同様にヌルであるよう

mUploadBtn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 

     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     if (intent.resolveActivity(getPackageManager()) != null) { 

      startActivityForResult(intent, CAMERA_REQUEST_CODE); 
       } 
      } 
     }); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 


     if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) { 

      mProgress.setMessage("Uploading Image..."); 
      mProgress.show(); 

      Uri uri = data.getData(); 

      StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment()); 


      filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
       @Override 
       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 

        mProgress.dismiss(); 

        Uri downloadUri = taskSnapshot.getDownloadUrl(); 

        Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView); 

        Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show(); 
       } 
      }); 

     } 
    } 
} 

Iがチェックされるように、onActivityResultのデータ(意図)は、NULLと等しいです。

だから、どのように私はこのような課題を解決し、それを使用可能にすることができますか?ビットマップを使用して写真にアクセスする必要がありますか?

誰かが私はこの状況を解決するのに役立つだろうか?

よろしく

答えて

0

は常にあなたのファイルを作成し、

File photoFile = null;  

mUploadBtn.setOnClickListener(new View.OnClickListener() { 
@Override 
public void onClick(View v) { 

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    if (intent.resolveActivity(getPackageManager()) != null) { 

     try { 
      photoFile = createImageFile(); 
     } catch (IOException ex) { 
      // Error occurred while creating the File 
      ex.printStackTrace(); 
     } 
     // Continue only if the File was successfully created 
     if (photoFile != null) { 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
        Uri.fromFile(photoFile)); 
      startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE); 
      } 
     } 
    }); 
} 

private File createImageFile() throws IOException { 
    // Create an image mSelectedFile name 
    String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date()); 
    String imageFileName = "IMG_" + timeStamp; 
    File storageDir = Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_PICTURES); 
    File file = File.createTempFile(
      imageFileName, /* prefix */ 
      ".jpg",   /* suffix */ 
      storageDir  /* directory */ 
    ); 


    return file; 
} 

次に、このファイル「で、photoFile」を使用し、onActivityResultに、必要に応じてそれを使用し、次のようにパスを使用して撮影した画像を保存します。

0

ので、私はonActivityResultは以下の呼び出されたときに私がチェックすることができ、すべてが私のコードで確認することを確認しました前に、私は同じ問題に直面しました。

私は、この処理後の画像

File photoFile; 
    URI uri; 

    mUploadBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
         if (takePhotoIntent.resolveActivity(getPackageManager()) != null) 
         { 
          try 
          { 
           photoFile = Create_ImageFile(); 
          } 
          catch (Exception e) 
          { 
           Log.e("file", e.toString()); 
          } 
          if (photoFile != null) 
          { 
           takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile())); 
          } 
         } 


     startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE); 
       } 
      }); 
     } 



    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) 
    { 
     super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

     switch (requestCode) { 

      case CAMERA_REQUEST_CODE: 

       if (resultCode == Activity.RESULT_OK) 
       { 
        try 
        { 
         Uri selectedImageURI = null; 
         ByteArrayOutputStream bos; 
         Bitmap bitmap = null; 
         int orientation; 
         ExifInterface exif = null; 
         FileOutputStream fos = null; 

         bos = new ByteArrayOutputStream(); 
         try 
         { 
    uri=imageReturnedIntent.getData(); 
          selectedImageURI = imageReturnedIntent.getData(); 
          bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI)); 
          exif = new ExifInterface(GetRealPathFromURI(selectedImageURI)); 
          fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI)); 
         } 
         catch (Exception e) 
         { 
          e.printStackTrace(); 
         } 


         if(bitmap==null) 
         { 
uri=Uri.fromFile(photoFile.getAbsoluteFile())); 
          bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath()); 
          exif = new ExifInterface(photoFile.getAbsolutePath()); 
          fos = new FileOutputStream(photoFile.getAbsolutePath()); 
         } 

         if(bitmap==null) 
         { 
          String imagePath = getPathGalleryImage(imageReturnedIntent); 
          bitmap = BitmapFactory.decodeFile(imagePath); 
          exif = new ExifInterface(imagePath); 
          fos = new FileOutputStream(imagePath); 
         } 


         Log.e("PhotoFile",photoFile.getAbsolutePath()); 


         // Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data"); 
         //bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false); 


         orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); 

         Log.e("ExifInteface .........", "rotation ="+orientation); 

         //exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90); 

         Log.e("orientation", "" + orientation); 
         Matrix m = new Matrix(); 

         if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) { 
          m.postRotate(180); 
          //m.postScale((float) bm.getWidth(), (float) bm.getHeight()); 
          // if(m.preRotate(90)){ 
          Log.e("in orientation", "" + orientation); 
          bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true); 

         } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) { 
          m.postRotate(90); 
          Log.e("in orientation", "" + orientation); 
          bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true); 

         } 
         else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) 
         { 
          m.postRotate(270); 
          Log.e("in orientation", "" + orientation); 
          bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true); 
         } 
         else 
         { 
          m.postRotate(0); 
          Log.e("in orientation", "" + orientation); 
          bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true); 
         } 

         //CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this); 

         bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); 
         userProfileIMG.setImageBitmap(bitmap); 

StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment()); 


        } 
        catch (Exception e) 
        { 
         e.printStackTrace(); 
        } 
       } 
       break; 
     } 

    } 


    private String getPathGalleryImage(Intent imageURI) 
    { 
     Uri selectedImage = imageURI.getData(); 
     String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

     Cursor cursor = getContentResolver().query(selectedImage, 
       filePathColumn, null, null, null); 
     cursor.moveToFirst(); 

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     String imagePath = cursor.getString(columnIndex); 
     cursor.close(); 

     return imagePath; 
    } 


    /** 
    * When image is returned we get its real path 
    **/ 
    private String GetRealPathFromURI(Uri contentURI) 
    { 
     String result; 
     Cursor cursor = getContentResolver().query(contentURI, null, null, null, null); 
     if (cursor == null) { 
      // Source is Dropbox or other similar local file path 
      result = contentURI.getPath(); 
     } else { 
      cursor.moveToFirst(); 
      int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
      result = cursor.getString(idx); 
      cursor.close(); 
     } 
     return result; 
    } 


    private File Create_ImageFile() throws IOException 
    { 

     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); 
     String imageFileName = "JPEG_" + timeStamp; 
     File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES); 
     File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName); 
     return image; 
    } 

をキャプチャするために、この意図を使う最初に私はいつも私が望むようにそれを使用するビットマップを持つ終わりました。

+0

はコメントありがとうございました。しかし、 "photoFile"とは何ですか?これをImageViewに置き換えると、ライブラリに「getAbsolutePath」が存在しないため、正常に動作しません。そして、 "ACTIVITY_SELECT_PICTURE"私は "ケース1:"に置き換えました。 – gryzek

+0

ありがとうございます。エミュレータでは、この写真は表示されていますが、実際のデバイスでは表示されません。しかし、あなたのコードで、撮影した写真をファイヤーベースのストレージに送ることで、私は以前の投稿から私の行を実装することができましたか? StorageReference filepath = mStorage.child( "Photos")。子(ur​​i.getLastPathSegment()); – gryzek

+0

@gryzek私は自分のコードを編集して、必要なものを追加しました。 –

0

のためにあなたがcameraIntentに設定されているパスに撮影した画像を得ることができます撮影した画像の後

Intent cameraIntent = new Intent(
       android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
this.startActivityForResult(cameraIntent, 101); 

を使用して撮影画像の実際の画像あらかじめ定義されたパスを取得します。あらかじめ定義されたパスを設定したくない場合は、インテントデータをチェックしてください。

if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) { 
       try { 

        path_mm = "Onsuccess_resultcode"; 
        generateNoteOnSD("photo34.txt", path_mm); 
        Bitmap photo = null; 
        if (data == null) { 
        //get Bitmap here. 
        } 
       else { 
        Uri u1 = data.getData(); 
        //get uri and find actual path on that uri. 
        } 
        }catch(Exception ex) 
        {}} 
0

私は私の質問を考え出しました。 これは現在動作しています。

private ProgressDialog mProgress; 
    private Button mUploadBtn; 
    private ImageView mImageView; 
    Uri picUri; 
    private StorageReference mStorage; 

    private static final int CAMERA_REQUEST_CODE = 1; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     mStorage = FirebaseStorage.getInstance().getReference(); 

     mUploadBtn = (Button) findViewById(R.id.uploadBtn); 
     mImageView = (ImageView) findViewById(R.id.imageView); 

     mProgress = new ProgressDialog(this); 

     mUploadBtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 

       File file=getOutputMediaFile(1); 
       picUri = Uri.fromFile(file); // create 
       i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file 

       startActivityForResult(i, CAMERA_REQUEST_CODE); 
      } 
     }); 
    } 

    /** Create a File for saving an image */ 
    private File getOutputMediaFile(int type){ 
     File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
       Environment.DIRECTORY_PICTURES), "MyApplication"); 

     /**Create the storage directory if it does not exist*/ 
     if (! mediaStorageDir.exists()){ 
      if (! mediaStorageDir.mkdirs()){ 
       return null; 
      } 
     } 

     /**Create a media file name*/ 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
     File mediaFile; 
     if (type == 1){ 
      mediaFile = new File(mediaStorageDir.getPath() + File.separator + 
        "IMG_"+ timeStamp + ".png"); 
     } else { 
      return null; 
     } 

     return mediaFile; 
    } 


    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 


     if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) { 

      mProgress.setMessage("Uploading Image..."); 
      mProgress.show(); 


      Uri uri = picUri; 

      StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment()); 


      filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
       @Override 
       public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 

        mProgress.dismiss(); 

        Uri downloadUri = taskSnapshot.getDownloadUrl(); 

        Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView); 

        Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show(); 
       } 
      }); 
     } 
    } 
関連する問題