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
Related
I have created an app that you could share images with them. I have set a notification sound when the sharing process is done. However, if I hit Cancel/Back buttons, the sound still plays.
In my code below, I have set a share button, once you click on it, you can share a bitmap of the image through the basic sharing app of android.
How can I set the sound to ONLY play when the sharing is complete.
Thanks,
Safi
Here's my code:
shareBtn = findViewById(R.id.shareButton);
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(animTranslate);
shareDigitalCard();
}
});
private void shareDigitalCard() {
if (ActivityCompat.checkSelfPermission(MyMenu.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
try {
makeStorageRequest();
} catch (Exception e) {
e.printStackTrace();
}
}else {
Bitmap viewBmp = Bitmap.createBitmap(mPager.getWidth(),
mPager.getHeight(), Bitmap.Config.ARGB_8888);
viewBmp.setDensity(mPager.getResources().getDisplayMetrics().densityDpi);
Canvas canvas = new Canvas(viewBmp);
//mPager.layout(0, 0 , mPager.getLayoutParams().width, mPager.getLayoutParams().height);
mPager.draw(canvas);
path = String.valueOf(saveTempBitmap(viewBmp));
shareImage(path);
}
}
private void shareImage(String file) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
File imageFileToShare = new File(file);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivityForResult(Intent.createChooser(share, "Share Image!"),123);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 123){
if (isSoundEnable) {
MediaPlayer player = null;
if (player == null) {
player = MediaPlayer.create(this, R.raw.success);
final MediaPlayer finalPlayer = player;
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer(finalPlayer);
}
});
}
player.start();
}
} else {
Toast.makeText(this, "An Error Has Occured !", Toast.LENGTH_SHORT).show();
}
}
You cannot get this event. The sharing procedure depends on the other App and you haven't any control or result from it. What you know is just you have send an Intent to a specific App, but what it does it's all up to it.
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();
}
I want to launch the camera once a user opens up my application.
Right now I have this, and it works fine. When the user launches my application, it automatically opens up the camera. However, then the user hits the "back" button after taking an image, it opens up a blank activity.
How do I get it to go back to the camera?
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 0;
// The URI of photo taken with camera
private Uri mUriPhotoTaken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
takePhoto();
}
// Deal with the result of selection of the photos and faces.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri imageUri;
if (data == null || data.getData() == null) {
imageUri = mUriPhotoTaken;
} else {
imageUri = data.getData();
}
Intent intent = new Intent(MainActivity.this, Result.class);
intent.setData(imageUri);
startActivity(intent);
}
}
// Launch the camera to allow the user to take a photo
public void takePhoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null) {
// Save the photo taken to a temporary file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File file = File.createTempFile("IMG_", ".jpg", storageDir);
mUriPhotoTaken = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
Log.d("ERROR", e.getMessage());
}
}
}
}
Try to call takePhoto() method in the onStart() instead of onCreate() and then call the finish() method into the onStop().
Try it.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, ActivityYouWantToOpen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
}
I made a class(ShowPhoto.java) which can make and save a photo. But nothing is happening when I click the "V" in my photo maker. So it makes the photo, but when you verify the photo, the app gives an error. When I press this button, the app should save the photo. Any idea what I forgot to add in my code?
package com.example.photoviewer;
//imports here
public class FotoMaker extends Activity
{
private static final String LOG_TAG = "debugger";
ImageView iv;
// Uri uriOfPicture;
static final int REQUEST_TAKE_PHOTO = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_pic);
iv = (ImageView) findViewById(R.id.imageView);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick (View v){
dispatchTakePictureIntent();
Log.i(LOG_TAG, "test5");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
}
}
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
Log.i(LOG_TAG, "test3");
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + 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 = "file:" + 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();
Log.i(LOG_TAG, "test");
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
Log.i(LOG_TAG, "test1");
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
Log.i(LOG_TAG, "test2");
}
}Log.i(LOG_TAG, "test4");
}
}
LogCat:
11-17 21:12:39.960: E/AndroidRuntime(15260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.keyfinder/com.example.photoviewer.FotoMaker}: java.lang.NullPointerException
11-17 21:12:39.960: E/AndroidRuntime(15260): at com.example.photoviewer.FotoMaker.onActivityResult(FotoMaker.java:61)
I currently have a MainActitivty.java and want to make a PhotoActitivty.java to clean it up and allow for every button or action to have its own class. For some reason my new PhotoActivity class won't open up the camera intent.
I have something like this:
public class MainActivity extends AppCompatActivity {
private Button firstPictureButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
firstPictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), PhotoActivity.class));
}
});
}
}
I started a new class and called it PhotoActivity.java to call this class every time a button for camera intent had been clicked.
What I currently have is:
public class PhotoActivity extends AppCompatActivity implements View.OnClickListener {
private final int REQUEST = 1;
private File image;
private String pathToFile;
private ImageView imageView;
#Override
public void onClick(View view) {
imageView = findViewById(R.id.imageView);
dispatchTakePictureIntent();
}
public void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Make sure there's camera activity to handle the camera intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create an empty File for the soon created File
File photoFile = null;
try {
photoFile = createImageFile();
} catch (Exception e) {
// Error when creating the File
e.printStackTrace();
}
// If File created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.inventorymanager.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST);
}
}
}
public File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save the file's path for use with ACTION_VIEW intents
pathToFile = image.getAbsolutePath();
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}
}
}
The problem with this is that whenever it opens, onClickListener, the camera doesn't open even though my dispatchTakePictureIntent() method is there.