I have been trying to select an image from the gallery and then set an imageview on Android by using the following code, but when I select an image, it goes back to the "select an image screen" (i.e. the first screen that comes up after the intent starts) and after about 3 seconds, the screen turns black. What's odd is that no errors are called, and about 1 in every 10 attempts, it actually works. I am running 5.0.1 Lollipop on a Nexus 6, and I have figured out that onActivityResult is not being called whenever the screen goes black. Thanks for any help,
Jacob
Here is my code:
public static int GAN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_funky);
Button a = (Button) findViewById(R.id.button);
ImageView b = (ImageView) findViewById(R.id.imageView5);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GAN);
System.out.println("hello world");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("hello world");
if (requestCode == GAN && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageView5);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
Related
I have a ProfileActivity:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final ImageView exampleImage = (ImageView) this.findViewById(R.id.exampleImageView);
exampleImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// [TODO] Implement application behavior when the user clicks the profile picture
//Toast.makeText(ProfileActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ProfileActivity.this, GalleryActivity.class));
}
});
}
and I have a second activity called 'GalleryActivity'. the concept is to let the user choose a image from the gallery and then use it to replace the original Profile image.
public class GalleryActivity extends AppCompatActivity {
ImageView imageView;
private static final int PICK_IMAGE = 100;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
}
however, when I click on a image of the gallery, instead of taking it as new profile image, it take me back to the original image.
what is happening and how I can solve it?
You can use Github Library it will help you.
Here is the Link.
ImagePicker.Companion.with(this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(1080, 1080)
.start();//Final image resolution will be less than 1080 x 1080(Optional)
On Activity Result.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
selectedFileURI = data.getData();
if (selectedFileURI != null && !Objects.requireNonNull(selectedFileURI.getPath()).isEmpty()) {
btnUpdate.setVisibility(View.GONE);
civUser.setImageURI(selectedFileURI);
Glide.with(context).load(selectedFileURI).into(civUser);
btnUploadDp.setVisibility(View.VISIBLE);
} else {
Functions.showSnackBar(context, "Cannot Get this Image");
}
}
}
}
Refernce Link.
I want to get the image from one activity to another activity. I tried converting the image to byte array in sender activity (PhotoActivity) and decoding the array to form original bitmap image on the receiver side (MainActivity) on the click of button 'btdn' but this isn't working. The image is visible in the sender activity's imageview but it stops when the button is clicked. This is my code:-
PhotoActivity.java
public class PhotoActivity extends Activity {
ImageView vitb;
Button btcm, btdn;
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_IMAGE_SELECT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
vitb = findViewById(R.id.imageView);
btcm = findViewById(R.id.btn_cam);
btdn = findViewById(R.id.btn_back);
btcm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
btdn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable drawable = vitb.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bs);
byte[] byteArray = bs.toByteArray();
Intent nIntent = new Intent();
nIntent.putExtra("PICTURE", byteArray);
setResult(RESULT_OK, nIntent);
finish();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,REQUEST_IMAGE_SELECT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap bmp;
Bundle bundle = data.getExtras();
bmp = (Bitmap)bundle.get("data");
vitb.setImageBitmap(bmp);
}
else if (requestCode == 2) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
cursor.close();
//ImageView imageView = findViewById(R.id.imageView);
vitb.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
}
MainActivity.java
public class MainActivity extends Activity{
private static final int REQUEST_CODE1 = 101;
private static final int REQUEST_CODE2 = 102;
Button btnLoc, btnPic;
Button btnSubmit;
TextView tvLoc;
ImageView image;
String phoneNumber = "9000000000";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSubmit = findViewById(R.id.btnSubmit);
btnLoc = findViewById(R.id.btnLoc);
btnPic = findViewById(R.id.btnPic);
tvLoc = findViewById(R.id.textView3);
image = findViewById(R.id.img);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
SmsManager.getDefault().sendTextMessage(phoneNumber, null, "Hello!", null, null);
}
catch (Exception e) {
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(MainActivity.this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
}
});
btnLoc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,LocActivity.class);
startActivityForResult(intent,REQUEST_CODE1);
}
}
);
btnPic.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,PhotoActivity.class);
startActivityForResult(intent,REQUEST_CODE2);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_CODE1 && data !=null) {
String strMessage = data.getStringExtra("loc");
tvLoc.setText(strMessage);
}
if(requestCode == REQUEST_CODE2 && data !=null) {
Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("PICTURE");
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
image.setImageBitmap(bmp);
}
}
}
}
I have an activity that contains an ImageView for showing user photo.
the user select an image from phone gallery and when he is done the image upload to firebase storage and return to the ImageView.
the problem is: when the user go to another activity (or on back button pressed) and return to UserProfile activity the image is no longer exist inside the ImageView.
how can i load the image when UserProfile activity start?
this is my UserProfile Activity
public class UserProfile extends AppCompatActivity {
private static final int GALLERY_INTENT = 2 ;
private ImageButton userImage;
private Button save_changes;
private EditText user_name;
private StorageReference mStorage;
private Uri mImageUri ,downloadUri;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
mAuth = FirebaseAuth.getInstance();
userImage = (ImageButton) findViewById(R.id.profileImage);
save_changes = (Button) findViewById(R.id.savechanges);
user_name = (EditText) findViewById(R.id.user_name2);
mStorage = FirebaseStorage.getInstance().getReference();
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_INTENT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON).
setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mImageUri = result.getUri();
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
save_changes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = user_name.getText().toString();
StorageReference filepath = mStorage.child("photos").child(mAuth.getCurrentUser().getUid()).child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(UserProfile.this).load(downloadUri).into(userImage);
Toast.makeText(UserProfile.this,"התמונה עלתה בהצלחה",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
I haven't tried this but you can do one thing create a static variable of Bitmap type when the image is selected assign that bitmap variable the value of bitmap from gallery.
And on your onStart of your activity first check if that static bitmap variable is null if not so put the bitmap into your imageView
When you launched another activity from current activity your previous activity gets destroyed. so all the variables and the image which set to the image view also garbage collected.
For that you can save your bitmap inside onSaveInstance()
Overide below method inside your activity
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putParcelable("BitmapImage", bitmap);
}
Write below code inside onCreate() which we can get the saved bitmap
if (savedInstanceState != null) {
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image); // set the bitmap.
}
If you have imagePath we can also save that and get that using same approach.
Hope these help you.
How do I set up multiple buttons to access the camera and save the photo?
I have figured out how to have one button do this task, but cannot figure out how to get multiple buttons to do this.
My Java Code so far:
package com.example.android.phototaker;
public class MainActivity extends AppCompatActivity {
ImageView result;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = (Button)findViewById(R.id.signbutton);
result = (ImageView)findViewById(R.id.imageView);
}
public void dispatchTakePictureIntent(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
result.setImageBitmap(imageBitmap);
}
}
}
By multiple buttons do you mean, different buttons opening up the camera?
If so, you will need to add an onclick listener for those buttons.
I have the same code in 2 Classes of my android-project. I´m just begin to learn java / android, so pls could you give me some tips? Do I have set a new class? Thank you for your help!
Main.java
public class Main extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
Intent uploadActivity = new Intent(Main.this, Upload.class);
uploadActivity.putExtra("picturePath", picturePath);
startActivity(uploadActivity);
cursor.close();
}
}
}
And Upload.java
public class Upload extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Bundle extras = getIntent().getExtras();
String picturePathView = extras.getString("picturePath");
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePathView));
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
}
This is actually what hasanghaforian said, but a little bit more conrect.
Your abstract Activity which enables holds the properties which are the same for Upload and Main could be the following
public abstract class AbstractMediaPickerActivity extends Activity {
protected static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void startMediaPicker() {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
protected abstract void onImagePicked(String picturePath);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
cursor.close();
onImagePicked(picturePath);
}
}
}
Your both other classes are inherited by the AbstractMediaPickerActivity
public class MainActivity extends AbstractMediaPickerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
startMediaPicker();
}
});
}
protected void onImagePicked(String picturePath) {
Intent uploadActivity = new Intent(Main.this, Upload.class);
uploadActivity.putExtra("picturePath", picturePath);
startActivity(uploadActivity);
}
}
public class Upload extends AbstractMediaPickerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Bundle extras = getIntent().getExtras();
String picturePathView = extras.getString("picturePath");
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePathView));
Button btnGallery = (Button) findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
startMediaPicker();
}
});
}
#Override
protected void onImagePicked(String picturePath) {
ImageView imageView = (ImageView) findViewById(R.id.imgView);
findViewById(R.id.imgView).setScrollBarStyle(
View.SCROLLBARS_INSIDE_INSET);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
Create a Class(for example SuperActivity) that extends Activity and add duplicated code to it.Then create Activities A,B that extend SuperActivity.
Sure you can put all the code in one class. I'm not gonna write all the code but you will get the idea how to gain refactoring in your code.
For onClickListner, you can do the following:
#Override
public void onClick(View clickedView) {
int clickedViewId = clickedView.getId();
switch(clickedViewId) {
case R.id.firstItem:
// code when first view is clicked
case R.id.secondItem:
// code when second view is clicked
default:
// optional
}
}
And then setting the same onClickListner for both views.
The same kind of switch statement you can use in onActivityResult method. I hope now you can merge the two classes in one.