I have just started in developing in Android. So far I am learning stuff. I am stuck with this problem. In my onCreate method, i have a button to select an image in the device and the onActivityResult to get the image and display the image in an ImageView
After researching and looking for answers in the internet, someone advice that I am missing the onSaveInstanceState. so I created it. Here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button)findViewById(R.id.buttonLoadPicture);
targetImage = (ImageView) findViewById(R.id.imgView);
buttonLoadImage.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMG);
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putParcelable("BitmapImage", bitmap);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image);
}
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK){
Uri targetUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(targetUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
this.bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
After building and running the code, selecting image and displaying it in ImageView works fine. When i change the orientation, image selected is still displayed. However when i rotate back again, the image displayed is gone.
Where am i doing wrong. Any advice and help is appreciated.
Are you storing 'bitmap' correctly? Here you are storing it to a local variable:
Bitmap bitmap;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
And here you are using a field:
savedInstanceState.putParcelable("BitmapImage", bitmap);
Looks like the field isn't being set so the onSaveInstanceState is storing a null value. Try removing Bitmap bitmap; or change bitmap = BitmapFactory... to this.bitmap = BitmapFactory.
EDIT:
Also try storing bitmap here:
image = savedInstanceState.getParcelable("BitmapImage");
targetImage.setImageBitmap(image);
By changing it to:
image = savedInstanceState.getParcelable("BitmapImage");
this.bitmap = image;
targetImage.setImageBitmap(this.bitmap);
I'm not sure what image is though as you haven't include the delcaration in the post.
Related
I have two activities in one i have a button and in second i have a ImageView, Now i want if i click on first activity's button then i go to gallery and pick an image when i select an image then it will automatically set in second activity's ImageView, My code is working when i set image in same acticity's imageView but i want set the image in second activity's ImageView. Please tell me what code i need to write in SecondActivity, My first Activity is(Select_Image):-
public class Select_Image extends Activity {
Button button;
public static final int PICK_FROM_GALLERY = 100;
Bitmap bitmap;
String imagePath = " ";
Uri uri;
ImageView image;
String path = " ";
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.select_image);
button = (Button)findViewById(R.id.select_btn);
image = (ImageView)findViewById(R.id.edit_image_id); //This is second Activity's ImageView id.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryIntent();
}
});
}
public void galleryIntent(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == MainActivity.RESULT_OK) {
if (requestCode == PICK_FROM_GALLERY){
}
onSelectFromGalleryResult(data);
}
}
public void onSelectFromGalleryResult(Intent data){
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
}
catch (Exception e) {
e.printStackTrace();
}
}
uri = getImageUri(this, bitmap);
imagePath = getRealPathFromUri(uri);
image.setImageBitmap(bitmap);
}
private String getRealPathFromUri(Uri uri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = this.getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String ss = cursor.getString(column_index);
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private Uri getImageUri(Select_Image select_image, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Toast.makeText(select_image, "Image uploaded Successfully", Toast.LENGTH_LONG).show();
path = MediaStore.Images.Media.insertImage(select_image.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
}
Second Activity(MainActivity)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
In your onActivityResult, you got the result which is used by your current activity. If an image is selected you got your result on onActivityResult.Here, you can pass this imageUrl in your second activity and open image in your second activity. If you have still any doubt you can ask me.
To sum up, you want to interact with Activity A, start a task then receive the result in Activity B, it's impossible. But you can get the same behavior by 2 options:
Start Activity B on Activity A's button clicked. In Activity B's onCreate, start the image selector and get the result from there.
Start the image selector in A's button clicked, get the result and then pass the result to B using startActivity Intent.
Prefer the first option because it makes the code cleaner, Activity B does its own job and Activity A doesn't need to know about it. Moreover, you save some performance when serialize/deserialize the param from A to B, make the activity transition smoother
I'm aware that there are several other questions on this topic but none of the solutions worked for me. I have added permissions in my manifest. I am able to open the gallery pick a photo and return to the application but the imageView does not change. The app is doing some processing and I am not getting any errors. I have tried also tried to scale the image before inserting it into my imageview with no luck.
Here is my code:
public class UserDetailsFragment extends Fragment {
private Context context;
private ImageView imageView;
private Bitmap uploadedImage;
public static final int RESULT_IMAGE = 0;
public UserDetailsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_user_details, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
imageView = (ImageView) getView().findViewById(R.id.profile_picture);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_IMAGE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
try {
InputStream in = new URL(filePath).openStream();
uploadedImage = BitmapFactory.decodeStream(in);
imageView.setImageBitmap(uploadedImage);
}catch (Exception ex){
}
}
}
}
Here is my imageView:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="-160dp"
android:layout_gravity="center"
android:layout_below="#+id/imageView"
android:src="#drawable/user_details_icon"
android:id="#+id/profile_picture" />
EDIT
I tried to use Picasso instead but still no luck:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Picasso.with(context)
.load(MediaStore.Images.Media.DATA)
.resize(10, 10)
.centerCrop()
.into(imageView);
}
In Your previous code, the problem is in the following lines:
InputStream in = new URL(filePath).openStream();
uploadedImage = BitmapFactory.decodeStream(in);
these lines are creating exception because that is responsible for downloading image from server and covert it into Bitmap. As you are picking image from local storage, the path of image is something like following
/storage/emulated/0/DCIM/Camera/IMG_20170209_183830841.jpg
when you pass it in new URL() as a parameter, it creates following exception
java.net.MalformedURLException: Protocol not found
In your case first of all you need to add READ_EXTERNAL_STORAGE permission in your manifest file and in onActivityResult(), you have to replace
InputStream in = new URL(filePath).openStream();
uploadedImage = BitmapFactory.decodeStream(in);
with
File image = new File(filePath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap, imageView.getWidth(), imageView.getHeight(), true);
Note: In case of marshmallow, don't forget to add security permission in your code.
I tried to use Picasso instead but still no luck:
That is because you are not using the correct Uri. You are using a Uri that points to the entire collection of scanned media.
If you read the documentation for ACTION_PICK, it has:
Output: The URI of the item that was picked.
Here, the Uri in question is obtained by calling getData() on the Intent delivered to onActivityResult().
So, replace .load(MediaStore.Images.Media.DATA) with .load(data.getData()).
Also, most likely, you need to increase the size of the image, as a 10px x 10px image is going to be rather small.
An imageview is not being updated with a photo taken in a camera activity on my Samsung 4S phone app. I save the Uri of the photo in a saveinstancestate and the photo is there on the camera but it does not update the imageview. Below is the code.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bitmap image1;
if(requestCode == RESULT_CROP_IMAGE)
{
Bundle extras = data.getExtras();
image1 = extras.getParcelable("data");
}
else {
if (requestCode == RESULT_LOAD_IMAGE) {
selectedImage = imageUri; // this gets the photo just taken
} else
selectedImage = data.getData(); // this gets an existing photo and it works
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
image1 = BitmapFactory.decodeFile(picturePath);
}
displayphoto = Bitmap.createScaledBitmap(image1, newWidth, newHeight, true);
ImageView imageView = (ImageView) findViewById(R.id.myImage);
imageView.setEnabled(true);
imageView.setImageBitmap(displayphoto);
Button cropPhoto = (Button)findViewById(R.id.cropPhoto);
cropPhoto.setVisibility(View.VISIBLE);
Not only is the imageView not showing the image, the cropPhoto button does not appear either. In debug mode I can see that the instructions are being executed and I examined the dimensions of the returned photo which are correct but nothing shows up. However, if I get an existing photo from my camera, everything works so I know it has something to do with losing global variables. I know that the instancestate has to be retrieved for certain objects when taking a photo and I do that in the code below so I know my imageUri is returned properly.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelable("myURI", imageUri);
savedInstanceState.putString("myPath", mCurrentPhotoPath);
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
imageUri = savedInstanceState.getParcelable("myURI");
mCurrentPhotoPath = savedInstanceState.getString("myPath");
}
So what is missing here? Why does not my image or my button show up? Does it have something to do with losing global variables when taking a photo? Also, I should mention that every once in awhile it works and the image appears. I don't understand why it normally doesn't appear.
I want to attach imageView to send through Android mail services. This is how i get image from Gallery in Activity A:
public class Activity A extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_gallery);
private static int RESULT_LOAD_IMAGE = 1;
Button viewcards=(Button)findViewById(R.id.viewcards);
viewcards.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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);
cursor.close();
Intent newdata = new Intent(SavedCards.this, Cardd.class);
newdata.putExtra("picture_path", picturePath);
startActivity(newdata);
}
}}
Transfer image to another class and and put imageView in Activity B:
public class Activity B extends Activity {
private ImageView cardimage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carddd);
String temp = getIntent().getStringExtra("picture_path");
cardimage = (ImageView) findViewById(R.id.cardimage);
cardimage.setImageBitmap(BitmapFactory.decodeFile(temp));
and in Activity B, i want to attach this image into e-mail by onClick.
txtsend=(TextView) findViewById(R.id.txtsend);
txtsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
As a reference, how image can attach e-mail is here, but this is to pick from gallery.
How to do this by taken image which is already set on imageView. Thank you.
In your code you setup image to ImageView from file in Activity B. And you know path to this picture file. When you send email just attach this file.
Uri uri = Uri.parse("file://" + attachmentFile);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
You can use ImageView's getDrawable method see this http://developer.android.com/reference/android/widget/ImageView.html#getDrawable()
So something like,
Bitmap imgViewBmp = ((BitmapDrawable)cardImage.getDrawable()).getBitmap();
Should work.
PS: I would suggest you to first check the api reference docs for any class you want to use. Chances of finding what you are looking for is quite high. Next best thing would be to actually google what you want to solve, if that doesn't work then "rephrase" you words and try again. The chances that you will find your solution are doubled (if not more) with the latter!
I want to delete/remove or clear image from imageView every time when user again click to set another image to the imageView. i am getting OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=7239KB, Allocated=2769KB, Bitmap Size=8748KB)
here is my code:
ImageView imageView;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
Bitmap yourSelectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
imageView = (ImageView) findViewById(R.id.imageView);
((ImageView) findViewById(R.id.imageView))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
goToGallery();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
/*Toast.makeText(getBaseContext(), "" + selectedImagePath, 1000)
.show();
*///editText2.setText(selectedImagePath);
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory
.decodeFile(selectedImagePath);
// put bitmapimage in your imageview
imageView.setImageBitmap(yourSelectedImage);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void goToGallery()
{
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
}
Setting a resource to 0 did not work for me. The following did work though:
imageView.setImageBitmap(null);
use the special resource Id '0'. It is not a valid res id, hence the image is blanked.
image.setImageDrawable(null);
will clear the image in the imageview.
When you set another image to the current ImageView the previous one is no longer used for the ImageView. Hence, no need to do extra work.
viewToUse.setImageResource(android.R.color.transparent);
I think using setImageResource with a color identifier will give you crashing issues on Android 2.2.1, make sure to test it.
edit_countflag.setBackgroundColor(0);