Restrict selecting file above some size in Android Studio - java

I a beginner in android, I want to select an image or a video file. But I want to restrict the selected file size, let's assume the restriction size is 5MB. Above 5MB I want to not allow the user to select the file.
How can I do it?
Any help would be appreciated.
Button OnClick:
btnSelectFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, 21);
}
});
OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 21 && resultCode == RESULT_OK) {
// Get the Uri of the selected file
uri = data.getData();
uriString = uri.toString();
myFile = new File(uriString);
path = myFile.getAbsolutePath();
displayName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
Log.e("TAG","Size: "+Long.toString(cursor.getLong(sizeIndex)));
textFileSelected.setText(displayName);
fileName = textFileSelected.getText().toString();
Toast.makeText(this, "File Selected: " + fileName, Toast.LENGTH_SHORT).show();
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
textFileSelected.setText(displayName);
fileName = textFileSelected.getText().toString();
Toast.makeText(this, "File Selected: " + fileName, Toast.LENGTH_SHORT).show();
}
}
}

Related

How to get the image name when user upload the image from gallery and display them in textView?

I'm trying to retrieve the actual image name of the image selected by user in gallery(Ex. IMG_2020).
I tried using getAbsolutePath() and getName() but these 2 methods display something like "image$3A75" instead of the actual image file name.
Other than that, I also tried using some cursor method which I don't know really how it works, but it still doesn't work or maybe it's because I do not know how to use it.
Any help please?
This is my onActivityResult() method
fileName is the textView I want to place my imageName
bitMap object is not used yet because I'm following a tutorial online and I'm halfway copying, I think it will be used later in the tutorial
public class createCharity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
Button uploadButton;
Button createCharityButton;
TextView charityTitle;
TextView fileName;
TextView charityDescription;
Uri charityImage;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_charity);
uploadButton = findViewById(R.id.uploadButton);
charityTitle = findViewById(R.id.charityTitle);
fileName = findViewById(R.id.fileName);
charityDescription = findViewById(R.id.charityDescription);
createCharityButton = findViewById(R.id.createCharityButton);
mStorageRef = FirebaseStorage.getInstance().getReference("charityUploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("charityUploads");
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
System.out.println("----------------------c1");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
charityImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), charityImage);
File file = new File(String.valueOf(charityImage));
System.out.println("Image name: " + file.getName());
fileName.setText(file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Something like:
String projection [] = {
MediaStore.Images.Media.DATA
, MediaStore.Images.Media.DISPLAY_NAME
, MediaStore.Images.Media.SIZE};
Cursor cursor = getContentResolver().query(data.getData(), projection, null, null, null);
if ( cursor==null)
{
Toast.makeText(context, "cursor==null\n\ncould not query content resolver for\n\n" + path, Toast.LENGTH_LONG).show();
return;
}
cursor.moveToFirst();
String data = cursor.getString(0);
String displayName = cursor.getString(1);
String size = cursor.getString(2);
Toast.makeText(context, "getContentResolver().openInputStream() ok\n\n" + path
+ "\n\nDISPLAY_NAME: " + displayName
+ "\nDATA: " + data
+ "\nSIZE: " + size
, Toast.LENGTH_LONG).show();
cursor.close();
DATA not available on Android Q+.

How to crop two different images in the same activity with different parameters in Android?

I am using this Crop library by SoundCloud. Selecting one imageview, slecting image, cropping and showing the result in the imageview works fine. But now I am trying to do it with two different imageviews with different specifications. I am not getting any errors nor am I seeing any results. Here's what I have tried:
//My click listeners
regCoverPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
});
regUserProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
});
//Handling the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK) {
beginCropProfile(data.getData());
}else if(requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK){
beginCropCover(data.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(requestCode, resultCode, data);
}
}
private void beginCropProfile(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).withAspect(ASPECT_X, ASPECT_Y).start(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
private void beginCropCover(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
private void handleCrop(int requestCode, int resultCode, Intent result) {
if (requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK) {
regCoverPhoto.setImageURI(Crop.getOutput(result));
mCoverPhotoUri = Crop.getOutput(result);
uploadCoverToStorage();
Log.d(TAG,"ResultCover: " + Crop.getOutput(result).toString());
}else if(requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK){
regUserProfile.setImageURI(Crop.getOutput(result));
mProfilePhotoUri = Crop.getOutput(result);
uploadProfileToStorage();
Log.d(TAG,"ResultProfile: " + Crop.getOutput(result).toString());
} else if (resultCode == Crop.RESULT_ERROR) {
Snackbar.make(getView(), Crop.getError(result).getMessage(), Snackbar.LENGTH_LONG).show();
}
}
I haven't used this library particularly, but custom request codes seem to be the problem.
Use different request codes for picking and cropping (total of 4 request codes) as you will need to handle them differently, and update onActivityResult(), handleCrop() to reflect that.
See https://gist.github.com/vibinr/fcf54c5e7ab63b9184432cc44c9a1494
List item
Here is a complete code of the images selection to crop and uploading to server using rest client with retrofit library Here few variables are used extra as for my use please ignore them
Also i'm using these library inside gradel
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
compile 'com.squareup.retrofit:retrofit:1.6.1'
And inside Mainfrest i have specifed this as <activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:screenOrientation="portrait" />
side2Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_side_2";
image_number_5 = "image_side_2";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_back";
image_number_6 = "image_back";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
if (image_name.equals("image_front")) {
image.setImageURI(result.getUri());
} else if (image_name.equals("image_top")) {
topImage.setImageURI(result.getUri());
} else if (image_name.equals("image_bottom")) {
bottomImage.setImageURI(result.getUri());
} else if (image_name.equals("image_side_1")) {
side1Image.setImageURI(result.getUri());
} else if (image_name.equals("image_side_2")) {
side2Image.setImageURI(result.getUri());
} else if (image_name.equals("image_back")) {
backImage.setImageURI(result.getUri());
}
cropped = result.getUri();
File path = getExternalCacheDir();
new File(String.valueOf(path)).mkdir();
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name22 = dateFormat.format(new Date());
// String helloWorld = cropped.toString();
// String hhhh=helloWorld.substring(helloWorld.indexOf(":")+1,helloWorld.indexOf("/"));
// String name="snehal_go";
savedFileDestination = new File(imagePath, name22 + ".jpg");
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("Webmirchi..", Context.MODE_PRIVATE);
String ALLOWED_CHARACTERS = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789qwertyuiopasdfghjklzxcvbnm";
Random generator = new Random();
randomStringBuilder = new StringBuilder();
int randomLength = 10;
for (int i = 0; i < randomLength; i++) {
randomStringBuilder.append(ALLOWED_CHARACTERS.charAt(generator.nextInt(ALLOWED_CHARACTERS.length())));
}
// Create imageDir
mypath = new File(directory, sessionMail + "-" + ProductId + ".jpg");
FileOutputStream fos = null;
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropped);
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
Log.i("File", mypath.toString());
if (image_name.equals("image_front")) {
uploadImage_front();
} else if (image_name.equals("image_top")) {
uploadImage_top();
} else if (image_name.equals("image_bottom")) {
uploadImage_bottom();
} else if (image_name.equals("image_side_1")) {
uploadImage_side1();
} else if (image_name.equals("image_side_2")) {
uploadImage_side2();
} else if (image_name.equals("image_back")) {
uploadImage_back();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(false)
.setMinCropWindowSize(600, 600)
.setAspectRatio(2, 2)
.setRequestedSize(500, 500)
.start(this);
}
Please refer the following url.This may help you. "https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/"
I'm not good in english...
// took extra int
static int a=0;
private void onClickData() {
cover_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=1;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
author_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=2;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==1){
// change the value again
a=0;
}
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==2){
// change the value again
a=0;
}
}

Image displays when choosing from gallery but not when capturing from camera

On the press of a button, dispatchTakePictureIntent() lets the user choose between taking a picture or choosing one from the gallery four times. These four URIs are stored in an ArrayList and the four should be shown in their respective ImageViews. The problem I'm having is that when I "capture a picture", it doesn't show in the ImageView right away; but the pictures I chose from gallery do.
The picture I captured is properly saved and can be found in "choose from gallery" the next time I press the button. Can anybody see what I'm doing wrong?
takePictureIntent():
private void dispatchTakePictureIntent() {
for(int i = 0; i < 4; i++) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
outputFileUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Log.w("error","IOException");
}catch (NullPointerException nullEx) {
Log.w("error","NullPointerException");
}
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
if(id.equals(HAPPY_ID))
startActivityForResult(chooserIntent, REQUEST_HAPPY_PHOTO);
if(id.equals(SURPRISED_ID))
startActivityForResult(chooserIntent, REQUEST_SURPRISED_PHOTO);
if(id.equals(AFRAID_ID))
startActivityForResult(chooserIntent, REQUEST_AFRAID_PHOTO);
if(id.equals(UPSET_ID))
startActivityForResult(chooserIntent, REQUEST_UPSET_PHOTO);
if(id.equals(SAD_ID))
startActivityForResult(chooserIntent, REQUEST_SAD_PHOTO);
}
}
}
onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_HAPPY_PHOTO || requestCode == REQUEST_SURPRISED_PHOTO || requestCode == REQUEST_AFRAID_PHOTO ||
requestCode == REQUEST_UPSET_PHOTO || requestCode == REQUEST_SAD_PHOTO) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
//Log.d("doing ids", "right before id");
//Log.d("doing ids", "id is " + id);
if(requestCode == REQUEST_HAPPY_PHOTO) {
//Log.d("doing ids", "in happy");
happyList.add(selectedImageUri);
}
if(requestCode == REQUEST_SURPRISED_PHOTO) {
//Log.d("doing ids", "in surprised");
surprisedList.add(selectedImageUri);
}
if(requestCode == REQUEST_AFRAID_PHOTO) {
//Log.d("doing ids", "in surprised");
afraidList.add(selectedImageUri);
}
if(requestCode == REQUEST_UPSET_PHOTO) {
//Log.d("doing ids", "in surprised");
upsetList.add(selectedImageUri);
}
if(requestCode == REQUEST_SAD_PHOTO) {
//Log.d("doing ids", "in surprised");
sadList.add(selectedImageUri);
}
}
}
}
Try this, this works for me
public Uri captureImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (chooserIntent.resolveActivity(getPackageManager()) != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Image File name");
Uri takenImageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, takenImageUri);
startActivityForResult(intentPicture, MyConstants.REQUEST_IMAGE_CAPTURE);
return takenImageUri;
}
return null;
}
public String getRealPathFromURI(Uri contentUri){
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e){
return contentUri.getPath();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
switch (requestCode){
case MyConstants.REQUEST_IMAGE_CAPTURE:
if (takenImageUri != null) {
Uri imagePath =getRealPathFromURI(takenImageUri,this));
}
}
}
}
rather than looping for 4 times, why not make each imageView an OnClickListener to get the image one by one?

Get contact name?

I want to get the contact name, but I'm not able to. After looking at this answer, I tried to get the name using family, given, and display, but nothing worked
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_CONTACT && resultCode == RESULT_OK) {
Uri contactUri = data.getData();
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst(); //Move to first row...I actually dont know why this part is necessary, but I get an error without it...
int NumberColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); //Int column is the column of the numbers
int NameColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
String contactNumber = cursor.getString(NumberColumn);
String contactName = cursor.getString(NameColumn);
Toast.makeText(MainActivity.this, ""+ contactNumber +"" +contactName, Toast.LENGTH_SHORT).show();
}
/
public void addContact(View v){ //OnClick listener to launch contact picker
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
Try below code for getting contact of specific number
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactName();
}
}
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number.
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
Log.d(TAG, "Contact Name: " + contactName);
}
More detail refer below link https://tausiq.wordpress.com/2012/08/23/android-get-contact-details-id-name-phone-photo/

Upload image from entire phone

I have created an activity that upon button click user are able to upload a picture from their device gallery, which would get cast to an imageview. The problem is that it is only able to retrieve image from device gallery, not from phone camera gallery, or from phone google drive folder. I would want that its able to upload any picture from their phone, regardless of the source.
Below is the code:
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.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);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
Any help would be greatly appreciated.
Update:
private static final int READ_REQUEST_CODE = 42;
in the code
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}
}
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
}
error:
The method parse(String) in the type Uri is not applicable for the arguments (File)
in line
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
Update 2:
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.fromFile(new File("/sdcard/myimage.jpg")));
error:
The method setImageUri(Uri) is undefined for the type ImageView
It would be better to use Intent to search the image type files available in your device.
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE); // set READ_REQUEST_CODE to 42 in your class
Now, process your results in the onActivityResult() method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}

Categories