Passing Image Captured to FilePathUri - java

I have problem to pass the Captured Image to the FilePathUri where the image will be stored and then uploaded to Firebase. I need to integrate them together cause the FilePathUri is always returning null.
Hope somebody can show me an Example with Code. Thanks
On-Create Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_takephoto);
// Assign FirebaseStorage instance to storageReference.
storageReference = FirebaseStorage.getInstance().getReference();
// Assign FirebaseDatabase instance with root database name.
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
//Assign ID'S to button.
ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
UploadButton = (Button)findViewById(R.id.ButtonUploadImage);
// Assign ID's to EditText.
ImageName = (EditText)findViewById(R.id.ImageNameEditText);
// Assign ID'S to image view.
SelectImage = (ImageView)findViewById(R.id.ShowImageView);
// Assigning Id to ProgressDialog.
progressDialog = new ProgressDialog(PhotoActivity.this);
// Adding click listener to Choose image button.
ChooseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FilePathUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
OnActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// Line 1:
FilePathUri = data.getData();
// Line 2:
Bitmap photo = (Bitmap) data.getExtras().get("data");
SelectImage.setImageBitmap(photo);
ChooseButton.setText("Image Selected");
}
}
Uploading Image Part
// Creating UploadImageFileToFirebaseStorage method to upload image on storage.
public void UploadImageFileToFirebaseStorage() {
// Checking whether FilePathUri Is empty or not.
if (FilePathUri != null) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
// Showing progressDialog.
progressDialog.show();
// Creating second StorageReference.
StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + FilePathUri);
// Adding addOnSuccessListener to second StorageReference.
storageReference2nd.putFile(FilePathUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Getting image name from EditText and store into string variable.
String TempImageName = ImageName.getText().toString().trim();
// Hiding the progressDialog after done uploading.
progressDialog.dismiss();
// Showing toast message after done uploading.
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
#SuppressWarnings("VisibleForTests")
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());
// Getting image upload ID.
String ImageUploadId = databaseReference.push().getKey();
// Adding image upload id s child element into databaseReference.
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
}
})
// If something goes wrong .
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Hiding the progressDialog.
progressDialog.dismiss();
// Showing exception erro message.
Toast.makeText(PhotoActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
// On progress change upload time.
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// Setting progressDialog Title.
progressDialog.setTitle("Image is Uploading...");
}
});
}
else {
Toast.makeText(PhotoActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}

Related

how to upload multiple images firebase

What I want to do is load different images into ImageView and save them in DB.
My current situation has been successful in obtaining images from albums and cameras, but one image appears in two ImageViews at the same time.
If you look at what's stored in DB, the same picture is stored in two child.
I think the way I think is to give image_url differently, but I don't know if this is a normal way or not.
I'd appreciate it if you could let me know.
add
private void addCoordi() {
//3) add data to db
progressDialog.setMessage("Adding Cody...");
progressDialog.show();
String timestamp = ""+System.currentTimeMillis();
if(image_uri == null ){
//upload without image
//setup data to upload
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("codyId",""+timestamp);
hashMap.put("codyTitle",""+coordiTitle);
hashMap.put("codyCategory",""+coordiCategory);
hashMap.put("codyIcon",""); //no image, set empty
hashMap.put("codyIcon2",""); //no image, set empty
hashMap.put("timestamp",""+timestamp);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Cody").child(timestamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
//added to db
progressDialog.dismiss();
Toast.makeText(AdditionCoordiActivity.this,"Cody added...",Toast.LENGTH_SHORT).show();
clearData();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed adding to db
progressDialog.dismiss();
Toast.makeText(AdditionCoordiActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
else{
//upload with image
//first upload image to storage
//name and path of image to be uploaded
String filePathAndName = "cody_images/"+""+timestamp;
StorageReference storageReference = FirebaseStorage.getInstance().getReference(filePathAndName);
storageReference.putFile(image_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uploaded
//get url of uploaded image
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while(!uriTask.isSuccessful());
Uri downloadImageUri = uriTask.getResult();
if(uriTask.isSuccessful()){
//url of image received, upload to db
//setup data to upload
HashMap<String,Object> hashMap = new HashMap<>();
hashMap.put("codyId",""+timestamp);
hashMap.put("codyTitle",""+coordiTitle);
hashMap.put("productCategory",""+coordiCategory);
hashMap.put("codyIcon",""+downloadImageUri); //no image, set empty
hashMap.put("codyIcon2",""+downloadImageUri); //no image, set empty
hashMap.put("timestamp",""+timestamp);
hashMap.put("uid",""+firebaseAuth.getUid());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(firebaseAuth.getUid()).child("Cody").child(timestamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
//added to db
progressDialog.dismiss();
Toast.makeText(AdditionCoordiActivity.this,"Cody added...",Toast.LENGTH_SHORT).show();
clearData();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed adding to db
progressDialog.dismiss();
Toast.makeText(AdditionCoordiActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed adding to image
progressDialog.dismiss();
Toast.makeText(AdditionCoordiActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
onActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == IMAGE_PICK_GALLEY_CODE){
//image picked from galley
//save pick image uri
image_uri = data.getData();
//set image
productIconIvOne.setImageURI(image_uri);
productIconIvTwo.setImageURI(image_uri);
}else if(requestCode == IMAGE_PICK_CAMERA_CODE){
// image picked from camera
productIconIvOne.setImageURI(image_uri);
productIconIvTwo.setImageURI(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}

How to change value of string from onSucces class

Here i read some input which i want to use for creating "Produs" object which i upload it to the firebase storage, then i want to retrieve it to display a list of objects, i have a problem when i want to update the path to the image storage, to retrieve it later.
public class Add extends AppCompatActivity {
DatabaseReference mDatabase;
EditText etNume, etCantitate, etPret;
Button btnSubmit, btnImage;
Uri mImage;
ImageView ivTest;
public static String path="";
StorageReference mStorageRef;
final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
mDatabase = FirebaseDatabase.getInstance().getReference();
etNume = findViewById(R.id.etNume);
etCantitate = findViewById(R.id.etCantitate);
etPret = findViewById(R.id.etPret);
btnSubmit = findViewById(R.id.btnSubmit);
btnImage = findViewById(R.id.btnImage);
ivTest =findViewById(R.id.ivTest);
mStorageRef = FirebaseStorage.getInstance().getReference();
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
startActivityForResult(i, GALLERY_INTENT);
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nume, pret,cantitate;
nume = etNume.getText().toString().trim();
pret = etPret.getText().toString().trim();
cantitate = etCantitate.getText().toString().trim();
if(TextUtils.isEmpty(nume)){
etNume.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(pret)){
etPret.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(cantitate)){
etCantitate.setError("Email is required.");
return;
}
StorageReference file = mStorageRef.child("Produs").child(nume + ".jpg");
file.putFile(mImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
path += taskSnapshot.getMetadata().toString(); /// good path
Toast.makeText(Add.this, path, Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(Add.this, path, Toast.LENGTH_SHORT).show();/// null path
Produs p=new Produs(nume,cantitate,pret,path);
Task task =mDatabase.child("Produs").child(nume).setValue(p);
task.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(Add.this, "Produsul a fost adaugat cu succes", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Add.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK && data != null && data.getData() != null){
mImage = data.getData();
ivTest.setImageURI(mImage);
}
}
}
How to have path changed from the onSuccess method?
Basically i want to change the path after i upload an image to build " Produs " object
Also, this is the good path to the image storage? As taskSnapshot.getdownloadURL() doesn't work for me.
The problem is not where you set and read the path variable, the problem is when you do this. Since the getDownloadURL() method makes a call to the server, its onSuccess may run much later than you think.
If you're seeing the wrong value for path, it's very likely that the onSuccess that sets it hasn't run yet. The easiest way to verify that is by either setting breakpoints on the read and write and running in a debugger, or by adding some logging and checking the order of that in your logcat.
The solution for this type of problem is always the same: any code that needs the download URL, needs to either be inside onSuccess, be called from there, or be synchronized in some other way.
So in your case, move the `` into the onSuccess:
StorageReference file = mStorageRef.child("Produs").child(nume + ".jpg");
file.putFile(mImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
path += taskSnapshot.getMetadata().toString(); /// good path
Toast.makeText(Add.this, path, Toast.LENGTH_SHORT).show();
Toast.makeText(Add.this, path, Toast.LENGTH_SHORT).show();
Produs p=new Produs(nume,cantitate,pret,path);
Task task =mDatabase.child("Produs").child(nume).setValue(p);
task.addOnSuccessListener(new OnSuccessListener() {
...
});
task.addOnFailureListener(new OnFailureListener() {
...
});
}
});
For more on this, see:
How to store download image url in realtime database firebase android
How to store Url into ArrayList from Firebase Storage?
Can someone help me with logic of the firebase on success listener
getContactsFromFirebase() method return an empty list
Setting Singleton property value in Firebase Listener
Not all of these are directly about Cloud Storage for Firebase, but the explanation applies here as well.

How to Retrieve videos from Firebase in app?

I want to add videos in firebase storage and retrieve all upload videos in-app through recycler view with card view.
Please give some reference or source code for this.
I am trying this for uploading video in firebase it is successfully uploaded but I am unable to retrieve it.
Thanks in advance.
public class VideoUplod extends AppCompatActivity
{
private static final int RC_PDF_PICKER = 2;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPDFStorageReference;
public static final int RC_SIGN_IN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_uplod);
VideoView videoView =(VideoView)findViewById(R.id.image);
//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
//specify the location of media file
Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.mp4");
//Setting MediaController and URI, then starting the videoView
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
mFirebaseStorage =FirebaseStorage.getInstance();
mChatPDFStorageReference = mFirebaseStorage.getReference().child("Video");
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PDF_PICKER);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
//for photo storage check
} else if (requestCode == RC_PDF_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPDFStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
#SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box so that the user can send it to the database
}
});
}
}
}
I'd take a look at:
Zero to App (video, source)
How to get an array with all pictures?
Firebase SDK for Cloud Storage docs
From the docs, it's pretty simple to download a file:
StorageReference videoRef = storageRef.child("videos/myvideo.mp4");
final long ONE_MEGABYTE = 1024 * 1024;
videoRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Transform bytes to a video, play
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

Firebase Storage - Prevent Overwriting of Files

I am allowing users to take pictures and store them to Firebase. Below is my code that contains the intent to load the camera application, save the image, and then upload to the Firebase storage. The problem I am having is each subsequent upload to the Firebase Storage is overriding the previous upload, meaning I have 1 file in storage that keeps being overridden. I want to keep adding multiple files:
private void createAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_image_dialog_title);
builder.setItems(new CharSequence[]
{getResources().getString(R.string.add_image_web), getResources().getString(R.string.add_image_camera), getResources().getString(R.string.add_image_gallery)},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
Intent toImageSearch = new Intent(CreateActivity.this, NewImageActivity.class);
startActivityForResult(toImageSearch, USE_WEB);
break;
case 1:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getApplication().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, TAKE_PICTURE);
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.camera_error), Toast.LENGTH_LONG).show();
}
break;
case 2:
Toast.makeText(getApplicationContext(), "clicked 2", Toast.LENGTH_LONG).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "clicked 3", Toast.LENGTH_LONG).show();
break;
}
}
}
);
builder.create().
show();
}
OnActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case USE_WEB:
if (resultCode == CreateActivity.RESULT_OK) {
resultImageURL = data.getStringExtra("result");
mAddImageButton.setVisibility(View.INVISIBLE);
Picasso.with(getApplicationContext())
.load(resultImageURL)
.into(mImagePreview);
}
if (resultCode == CreateActivity.RESULT_CANCELED) {
//Write your code if there's no result
}
case TAKE_PICTURE:
if (resultCode == CreateActivity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImagePreview.setImageBitmap(imageBitmap);
encodeBitmapAndSaveToFirebase(imageBitmap);
}
}
}
Save to Firebase:
private void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mPollImageStorage.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "Error Loading Photo", Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
mAddImageButton.setVisibility(View.INVISIBLE);
resultImageURL = downloadUrl.toString();
Picasso.with(getApplicationContext())
.load(resultImageURL)
.into(mImagePreview);
}
});
}
You need to use a separate location or separate file name for each upload.
You can create a custom location like this:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://myfirebaseproject.appspot.com");
StorageReference fileRef =
storageRef.child(channelId)
.child(String.valueOf(message.getSender()))
.child(String.valueOf(message.getTimestamp()));
UploadTask uploadTask = fileRef.putFile(message.getAttachmentUri());
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
sendMessage(channelId, message.getMessageText(), taskSnapshot.getStorage().toString(), message.getAttachmentType(), callback);
}
});
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
callback.onError(e.toString());
}
});
You can see we are adding custom locations to our base storage reference so that we don't overwrite existing items.
The location that you store your image is determined by what mPollImageStorage is referencing. If mPollingStorage always references the same place, ie, in your onCreate you do something like:
StorageReference mPollingStorage = storageRef.child("polling.jpg");
Then it will keep overriding camerapic.jpg. If you don't want to override it, you could set the image name to something like the time the image was taken or generate a UUID as per this stackoverflow post : Store files with unique/random names

making submit button clickable and not clickable

im trying to have my apps submit button not clickable until the user takes a picture. so initially the button will be not clickable and then when the person takes a picture the submit button becomes clickable so they can move on. problem is i cant get it to work properly. as of right now the submit button is not clickable (which is what i want) when it first loads. but if i hit the camera button then press the back button the submit button becomes visible(i want it to be unclickable). how can i correct this so that it doesnt show the submit button during this situation? o far i have tried to set not clickable in the oncreate method , and i set to clickable when the image file is made in the photobutton. which didnt work.
public class TreeQuestionsActivity extends AppCompatActivity {
Button btnSubmit;
Button btnPhoto;
ProgressBar progress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tree_questions_list);
btnSubmit = (Button) findViewById(R.id.enter_button);
btnPhoto = (Button) findViewById(R.id.photo_button);
btnSubmit.setEnabled(false);
}
private void setupButton() {
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selection();
if (mCurrentPhotoPath == null) {
Toast.makeText(getApplicationContext(), "Please submit a picture of the tree before you move on",
Toast.LENGTH_LONG).show();
} else if (f == false) {
showProgress(true);
new UploadTreeTask().execute(); //adds tree and then adds the dailyUpdate -> Goes to bird list activity
//new DbInsertTask().execute();
} else {
showProgress(true);
treeID = tree.getId();
new UploadDailyTask().execute();
}
}
});
btnPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//startActivityForResult(takePictureIntent, ACTIVITY_START_CAMERA);
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
// Error occurred while creating the File
Log.i(Constants.TAG, "IO Exception");
e.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
btnSubmit.setEnabled(true);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "TREE_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
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();
Log.d(Constants.TAG, mCurrentPhotoPath);
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ACTIVITY_START_CAMERA:
if (requestCode == ACTIVITY_START_CAMERA && resultCode == RESULT_OK & null != data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
//to generate random file name
String fileName = "tempimg.jpg";
try {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//captured image set in imageview
imageView.setImageBitmap(photo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
move this line
btnSubmit.setEnabled(true);
to onActivityResult() method after this line
imageView.setImageBitmap(photo);
your code looks fine but i think it would look better if you just played with the visibility of the button:
btnSubmit.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
and you have to to add :
btnSubmit.setEnabled(true);
into your onActivityResult() method

Categories

Resources