Populating listview from sdcard images - android

I would like to add images from my sdcard to my listview. Currently I can choose picture from my sdcard by the button click on my UI. The implementation to choose picture is this:
sendPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mybyte=null;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
}
});
The onActivityResult of this implementation is:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
currImageURI = data.getData();
myvariable=getRealPathFromURI(currImageURI);
try {
mybyte=fileToByteArray(myvariable);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My aim is convert "mybyte", which is a byte[] variable, to an image and put the image on my listview.
Any help is appreciated.

With such an implimentation,transforming byte[] to Bitmap and store Bitmaps in your adapter source list, you will get an OutOfMemmory error. Will be better to store in your ArrayList not the Bitmap but the path to it, you get it from cursor after chosing bitmap from galery, and load the Bitmap in an AsyncTask in the getView method of your CustomAdapter.Google has a good example on how to do a fancy ListView with ImageViews HERE

Related

Retrieving a photo from photo gallery

I have found this code and trying to implement in my application, it open the gallery, let's me select a photo, then the applications stops working and closes.
It's my first time trying to upload an image to mysql, and i'm stuck at the very beginning.
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showFileChooser();
}
});
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Uri filePath = data.getData();
try
{
bitmap = MediaStore.Images.Media.getBitmap(MainActivity.this.getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(bitmap);
}
}
Uri filePath = data.getData();
This will be meaningless for most Uri values.
The best solution to populate an ImageView from a Uri is by using a third-party image loading library, such as Picasso.
If you insist upon doing this yourself, you will need to fork a background thread, use a ContentResolver and openInputStream() to get an InputStream on the content backed by the Uri, use BitmapFactory and decodeStream() to get a Bitmap, then (on the main application thread) update the ImageView with the Bitmap.

android finish sometimes restarting app

I'm working on an app which allows user to choose a picture from gallery and then I start a activity to crop it.
I want to send the cropped image back to calling activity.
Both activities extend AppCompatActivity.
Calling activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// start image crop activity
String dataString = data.getDataString();
Intent intent=new Intent(this, CropPhotoActivity.class);
intent.putExtra("SELECTED_PICTURE_FOR_CROP", dataString);
startActivityForResult(intent, CROP_PICTURE);
}
else if(requestCode == CROP_PICTURE) {
// get cropped bitmap
Bitmap bitmap = (Bitmap) data.getParcelableExtra("CROPPED_IMAGE");
profilePhoto.setImageBitmap(bitmap);
}
}
}
In the crop image activity, I have a button, which on click should return back to calling activity:
Button okButton = (Button)findViewById(R.id.ok_button);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE", cropped_bitmap);
setResult(RESULT_OK, returnIntent);
finish(); // sometimes restarts app
}
});
Sometimes the bitmap gets returned correctly whereas sometimes it does not and the app gets restarted without error. Why is this happening? Does putExtra have anything to do with bitmap size or anything else?
You could try substituting
AppcompatActivity.this.finish()
(where AppcompatActivity is your class name)
for:
finish(); // sometimes restarts app
Or, create a method in the calling Activity:
public static void cropComplete(Activity activity)
{
activity.startActivity(activity, AnotherActivity.class);
activity.finish();
}
Theres's a limit for data length passed as extra in a intent. Try not passing the dataString value; instead you should save the image as a temporary file, pass the path in the intent and then load the image from your calling activity (or you can just save the dataString in a static helper class).
In the crop activity (saving bitmap code from Save bitmap to location):
// Save bitmap
String filename = "tempImage.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
FileOutputStream out = null;
try {
out = new FileOutputStream(dest);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Get image file path
String path = dest.getAbsolutePath();
// Set result with image path
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE_PATH", path);
setResult(RESULT_OK, returnIntent);
finish();
In the caller activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CROP_PICTURE) {
// Get image file path
String imagePath = data.getStringExtra("CROPPED_IMAGE_PATH");
// Load image
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}

Image not getting displayed in ImageView in mobile but working in AVD

I tried creating a new intent to get an image file and on result of the intent i got the image uri and set to the imageView but this worked fine in my AVD and even in Bluestacks but is NOT working in my phone (installed after converting to an apk). Image selection screen appears but then after selecting the image only a blank gets displayed in the imageView.
here's my code for on click the imgView
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select contact Image"),1);
}
});
my on Result from intent method
public void onActivityResult(int reqCode,int resCode,Intent data)
{
super.onActivityResult(reqCode,resCode,data);
if(resCode==RESULT_OK) if (reqCode == 1) {
imgView.setImageURI(data.getData());
imgUri = data.getData();
}
}
Note: My image View is a scaled image view of 100*100 px
try this instead
//this code calls the app or phone to pick an image from the gallery
pick = 0;
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, pick);
and in the activity on result use this
//process image gotten from gallery
if (requestCode == pick && resultCode == getApplicationContext().RESULT_OK) {
Uri imgUri = data.getData();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageView.setImageBitmap(bitmap);
}

Android - Cannot set gallery image to ImageView

I've looked through tons of posts and cannot figure out why I can't get this to work. All I want to do is have the user click a button that opens up the gallery app. Then the user selects a picture which automatically closes out the gallery and goes back to my application where it automatically sets that image to an ImageView.
So far, I have it working all the way up until it goes back to my application. It seems to all be fine but the image never shows up in the ImageView.
Here is the XML code for the ImageView:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal" />
At the beginning of my activity I set the ImageView with this:
ImageView targetImage;
And here is the rest of my code to get the image and set it to my ImageView. There is a button that launches "setGunImage".
public void setGunImage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
targetImage = (ImageView)findViewById(R.id.imageView1);
Uri selectedImageUri = data.getData();
targetImage.setImageURI(selectedImageUri);
}
}
}
I have tested it on both the simulator with the sd card enabled and an image loaded into and also on a real device. Both give the same behavior. It goes through the gallery steps fine but when it goes back to my application there is no image loaded in the ImageView.
I tried changing the data to a bitmap and setting that but it never showed up either. I know it's probably something super simple that I'm just not seeing so hopefully a fresh pair of eyes can point me in the right direction. Thanks.
I think Imran solution should work fine .............. and you can also try this way
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
InputStream stream = null;
if( resultCode==RESULT_OK)
{
if(requestCode==SELECT_PICTURE)
{
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
targetImage = (ImageView)findViewById(R.id.imageView1);
targetImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
from link
you are passing URI in setImageURI so fist get path of image using MediaStore.Images.Media.DATA and URI then pass path of image in setImageURI.
try this way:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( resultCode==RESULT_OK)
{
if(requestCode==SELECT_PICTURE)
{
targetImage = (ImageView)findViewById(R.id.imageView1);
Uri selectedImageUri = data.getData();
String selectedImagePath=getPath(selectedImageUri);
targetImage.setImageURI(selectedImageUri);
}
}
}
private 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);
}

Save Image to web server (byte array)

I want to upload an image to server in the form of Byte array.. Here I am using surface view and 'Take Picture' button, when user click a take picture button, then
TakePicture.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(null, null, callback);
}
});
and pictureCallback is:
PictureCallback callback = new PictureCallback(){
public void onPictureTaken(**byte[] data**, Camera camera) {
// TODO Auto-generated method stub
try {
//async task for storing the photo
Log.i("Picture Taken.", "Picture Taken.");
new SavePhotoTask(CameraPreviewActivity.this, data).execute();
} catch (final Exception e) {
//some exceptionhandling
Log.i("Save Photo exception",e.getMessage());
}
}};
Now here I am using this byte array 'data'
and I want to send this image in the form of byte[] to web server..
What should I do for this??
convert byte array to base64
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
also see this link
1)Send camera intent
public void onCameraClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile = FileUtil.newFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
2)get file path when the picture will be ready, read bytes from file and send bytes to a server.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK){
if (resultCode == RESULT_OK) {
final String path = imageFile.getAbsolutePath();
// get file from path and send bytes to server
}
}
}

Categories

Resources