2017-09-13 71 views
0

我通過使用相機捕獲圖像並希望發送到firebase存儲。但是我錯了3天3。我困在它上面。當我觸發意圖它捕獲圖像,但在onActivityresult它返回請求代碼= 1和結果代碼= -1。這裏是我的代碼如何使用相機捕獲圖像併發送到firebase

捐款活動:

package com.example.manzoorhussain.kindnessapp; 


import android.app.ProgressDialog; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Environment; 
import android.os.Parcelable; 
import android.provider.MediaStore; 
import android.support.annotation.NonNull; 
import android.support.v4.content.FileProvider; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.Toast; 

import com.google.android.gms.tasks.OnFailureListener; 
import com.google.android.gms.tasks.OnSuccessListener; 
import com.google.firebase.storage.FirebaseStorage; 
import com.google.firebase.storage.StorageReference; 
import com.google.firebase.storage.UploadTask; 

import java.io.File; 
import java.io.IOException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class DonationActivity extends AppCompatActivity { 


    private Button mUploadBtn; 
    private ImageView mImageView; 
    private final static int CAMERA_REQUEST_CODE = 1; 
    private StorageReference mstorage; 
    ProgressDialog progressDialog; 
    Uri photoURI; 

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

     mUploadBtn = (Button) findViewById(R.id.upload); 
     mImageView = (ImageView) findViewById(R.id.imageView); 
     progressDialog = new ProgressDialog(this); 
     mstorage = FirebaseStorage.getInstance().getReference(); 
     mUploadBtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       dispatchTakePictureIntent(); 

      } 
     }); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) { 
      Toast.makeText(this, "" + photoURI, Toast.LENGTH_SHORT).show(); 


      progressDialog.setMessage("Uploading..."); 
      progressDialog.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) { 
        Toast.makeText(DonationActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show(); 
        progressDialog.dismiss(); 
       } 
      }).addOnFailureListener(new OnFailureListener() { 
       @Override 
       public void onFailure(@NonNull Exception e) { 
        Toast.makeText(DonationActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show(); 
       } 
      }); 
     } 

    } 

    String mCurrentPhotoPath; 

    private File createImageFile() throws IOException { 
// Create an image file name 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
     String imageFileName = "JPEG_" + timeStamp + "_"; 
     File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); 
     File image = File.createTempFile(
       imageFileName, /* prefix */ 
       ".jpg",   /* suffix */ 
       storageDir  /* directory */ 
     ); 

// Save a file: path for use with ACTION_VIEW intents 
     mCurrentPhotoPath = image.getAbsolutePath(); 
     return image; 
    } 

    private void dispatchTakePictureIntent() { 
     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
// Ensure that there's a camera activity to handle the intent 
     if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
      // Create the File where the photo should go 
      File photoFile = null; 
      try { 
       photoFile = createImageFile(); 
      } catch (IOException ex) { 
       // Error occurred while creating the File... 
      } 
      // Continue only if the File was successfully created 
      if (photoFile != null) { 
       photoURI = FileProvider.getUriForFile(this, 
         "com.example.android.fileprovider", 
         photoFile); 
       //takePictureIntent.setData(photoURI); 
       // takePictureIntent.putExtra("imageUri", photoURI.toString()); 

       takePictureIntent.putExtra("imageUri", photoURI.toString()); 

       // takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); 
       startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE); 
      } 
     } 

    } 

} 

我得到的活性resultCode爲誤差爲零。

回答

0

BTW據我所知,

public static final int RESULT_OK = -1; 
public static final int RESULT_CANCELED = 0; 

只要按下Ctrl + B上RESULT_OK如果您在Windows機器上它被完成** 因此,也許你不知何故取消活動的活動之前。我做了類似的事情。拍攝完視頻/照片後,等待操作系統顯示刻度或其他內容以選擇拍攝的照片。這是我的代碼,如果它有幫助。

試試這個

/** 
    * Upload a video directly by recording it using camera 
    * You can do image/video whatever you require 
    */ 
    private void recordVideo() { 
     Intent recordVideoIntent = new Intent(); 
     recordVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE); 
     if (recordVideoIntent.resolveActivity(getPackageManager()) != null) { 
      startActivityForResult(recordVideoIntent, UPLOAD_VIDEO_CAMERA); 
     } 
    } 

//使在裝載機的網絡電話或異步任務

getLoaderManager().initLoader(0, null, UploadVideo.this); 

//和你的AsyncTask或裝載機裏面,做這樣的事情。你做了一個函數來重命名你的文件。我猜並不需要。該文件會自動存儲在手機AFAIK中。而關於火力地堡存儲文件的名稱,只是用這樣的

 //Upload the video to storage 
     StorageReference mFirebaseStorageRef = FirebaseStorage.getInstance().getReference(); 

     mFirebaseStorageRef 
       .child(String.valueOf(mCurrentUser.getEmail() + new Date().getTime())) 
       .putFile(videoData). 
       addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
        @Override 
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 

         try { 

          //MAYBE UPDATE IT SOMEPLACE IN DATABASE AS WELL 
          HashMap<String, String> city_Obj = new HashMap<String,String>(); 
          city_Obj.put("VIDEO_URL", downloadUrl); 
          city_Obj.put("VIDEO_NAME", nameOfVideo); 
          city_Obj.put("VIDEO_DESC", descriptionOfVideo); 
          dbRef.child("CITIES").child(spinnerCityName).push().setValue(city_Obj); 


         } catch (Exception e) { 
          e.printStackTrace(); 
          Log.e("DB ERROR", e.getMessage()); 
         } 
0

我的例子希望你能理解它。

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

    if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){ 
     Uri uri = data.getData(); 
     progressDialog.setMessage(UPLOADING); 
     progressDialog.show(); 
     StorageReference filePath = storageRef.child(STORAGE_FOLDER_NAME).child(recipeTitle.getText().toString()); 
     filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
      @Override 
      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
       Toast.makeText(CreateNewRecipeActivity.this, UPLOAD_COMPLETE, Toast.LENGTH_SHORT).show(); 
       progressDialog.dismiss(); 
      } 
     }); 
    } 
} 
+0

先生,我已經做到了這一點,但它仍然在圖像URL拋出異常 –

+0

嘗試調試,看看網址你得到 –

+0

是它的TextView你保存圖像的URI? –

0

我拍攝圖像,就像你在上傳之前將圖像保存到文件系統,但是使用mCurrentPhotoPath加載位圖代替。然後將位圖轉換爲字節並從那裏上傳到Firebase存儲。

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) { 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     byte[] imageBytes = baos.toByteArray(); 
     StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo"); 
     UploadTask uploadTask = reference.putBytes(imageBytes); 
     uploadTask.addOnSuccessListener(new 
     OnSuccessListener<UploadTask.TaskSnapshot>() { 
      @Override 
      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
       Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString()); 
      } 
     }); 
    } else if (resultCode == RESULT_CANCELED) { 
     onCancel(); 
    } 
} 

private File createImageFile() throws IOException { 
    String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
    String filename = String.format("JPEG_%s_", ts); 
    File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES); 
    File image = File.createTempFile(filename, ".jpg", storageDir); 
    mCurrentPhotoPath = image.getAbsolutePath(); 
    return image; 
} 

爲了進一步打破它在我的申請我第一一個的ImageView內顯示所述圖像,然後上傳將其轉換爲byte []這樣時。

Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable().getBitmap(); 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
byte[] imageBytes = baos.toByteArray(); 

然後上傳到Firebase。

StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo"); 
UploadTask uploadTask = reference.putBytes(imageBytes); 
uploadTask.addOnSuccessListener(new 
OnSuccessListener<UploadTask.TaskSnapshot>() { 
      @Override 
      public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
       Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString()); 
      } 
     }); 
相關問題