android read file from sd card - android

I just need to covert the path in file to InputStream here is my code. I select the path by calling Intent but it always gives me filenotfoundexception
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK) {
File file = new File(Environment.getExternalStorageDirectory(), data.getData().toString());
Uri path = Uri.fromFile(file);
File fpath=new File(path.toString());
try {
InputStream myfile=new FileInputStream(fpath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
thanks for help in advance...

try this:
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
InputStream myfile=cr.openInputStream(uri));;
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Intent intent = new Intent();
intent.setType("image/*");
//intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity(). RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
//Setting the Bitmap to ImageView
Glide.with(getActivity()).load(filePath).asBitmap().placeholder(R.drawable.ic_launcher).into(avatarContainer);
//avatarContainer.setImageBitmap(bitmap);
//uploadFile(filePath.getPath());
try {
uploadFile(getPath(filePath));
} catch (Exception e) {
Config.displayToast("Please Select Image From Gallary");
alertDialog.dismiss();
ServerRequest.dismissDialogBox(context);
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == getActivity() .RESULT_OK){
String filepath = fileUri.getPath();
Log.d("Filepath is",""+filepath);
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filepath, options);
//avatarContainer.setImageBitmap(bitmap);
Glide.with(getActivity()).load(filepath).asBitmap().placeholder(R.drawable.ic_launcher).into(avatarContainer);
uploadFile(filepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Related

Get the exact File Size of an Image from the selected image in gallery

This is my code for file chooser
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);
}
then onActivityResult()
#Override
public 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) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
System.out.println(bitmap.getByteCount());
int w = bitmap.getWidth();
int h = bitmap.getHeight();
if (w!= 512 || h!= 512)
{
txvLogoError.setText("Invalid image dimensions. Please choose another.");
}
else
{
txvLogoError.setText("");
imbAppLogo.setPadding(10,10,10,10);
imbAppLogo.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my question is, how can I get the exact file size of the image selected? I tried File.length() but the result is 0.
Try this .
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int dataSize=0;
if (requestCode == 2 && resultCode == RESULT_OK)
{
Uri uri = data.getData();
String scheme = uri.getScheme();
System.out.println("Scheme type " + scheme);
if(scheme.equals(ContentResolver.SCHEME_CONTENT))
{
try {
InputStream fileInputStream=getApplicationContext().getContentResolver().openInputStream(uri);
dataSize = fileInputStream.available();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("File size in bytes"+dataSize);
}
else if(scheme.equals(ContentResolver.SCHEME_FILE))
{
String path = uri.getPath();
try {
f = new File(path);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("File size in bytes"+f.length());
}
}
}
try the following,
File f = new File(filePath.getPath());
long size = f.length();
Otherwise you can try
Cursor returnCursor = getContentResolver().query(filePath, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);

Image from gallery, photos and camera not working always

final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(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);
cameraIntents.add(intent);
}
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI); galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, 1);
So , thats How I call to open either camera or take a picture. How i read them on onactivityresult????check below the code. The problem, when image chosen from photos it works, when taken from camera it works. But when chosen from gallery folder, it doesnt work for some reason. Also some of clients are reporting me problem on sony xperia e4 phones.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK && requestCode == 1
) {
Bitmap bm = null;
try
{
Bundle extras = data.getExtras();
bm = (Bitmap) extras.get("data");
}
catch(Exception e)
{
try
{
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Common.setBitmap(null);
bm = BitmapFactory.decodeFile(filePath);
BitmapFactory.decodeFile(Common.getRealPathFromURI(data.getData(), rootView.getContext()), bounds);
if(bm == null)
bm = BitmapFactory.decodeFile(Common.getRealPathFromURI(selectedImage, AddStoreActivity.this), options);
if(bm == null)
bm = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
}
catch(Exception e1)
{
}
}
}
} catch (Exception e) {
}
}
public static String getRealPathFromURI(Uri contentURI, Context cont) {
Cursor cursor = cont.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaColumns.DATA);
return cursor.getString(idx);
}
}
This is how I do this and it works:
private void displayAddPhotoDialog() {
final CharSequence[] items = getResources().getStringArray(R.array.photo_dialog_options);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(R.string.photo_dialog_title));
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == TAKE_PHOTO_OPTION) {
dispatchTakePictureIntent();
} else if (item == CHOOSE_FROM_LIBRARY_OPTION) {
dispatchPickImageIntent();
} else if (item == CANCEL_OPTION) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
imageUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_SHORT).show();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
} else {
Toast.makeText(getActivity(), R.string.no_camera_error_message, Toast.LENGTH_SHORT).show();
}
}
protected void dispatchPickImageIntent() {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)), GALLERY_REQUEST_CODE);
}
And your onActivityResult method should look like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
photoReceivedFromCamera = true;
getActivity().getContentResolver().notifyChange(imageUri, null);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(imageUri);
getActivity().sendBroadcast(mediaScanIntent);
//do want you want with the uri(taken photo)
} else if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_CANCELED) {
//The user cancelled the take picture action...
if (!photoReceivedFromCamera) {
//If the user has not previously taken a picture,
//this means he is cancelling the take photo process
onCancelTakePicture();
}
} else if (requestCode == GALLERY_REQUEST_CODE && data != null && data.getData() != null) {
Uri uri = data.getData();
//do want you want with the uri(selected image)
}
}

Captured image does not display on ImageView

In my Activity A, there is an ImageView and a Button. When the button is clicked, it goes to activeTakePhoto(). The imgUri gets displayed but nothing is displayed in my ImageView.
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
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();
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
ImageView imgView=(ImageView)findViewById(R.id.imageView);
Uri imgUri=Uri.fromFile(picture);
imgView.setImageURI(imgUri);
Toast.makeText(getApplication(),imgUri+"",Toast.LENGTH_LONG).show();
}
}
}
You can try this code,it may help:
#Override
public void onClick(View v) {
if (v == imgCamera) {
Toast.makeText(getApplicationContext(), "open camera", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
}//on click
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("RESULT CODE", "--" + resultCode);
if (resultCode == RESULT_OK) {
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 (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
in activeTakePhoto
Replace
String fileName = "temp.jpg";
with
fileName=Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.jpg"

Select bitmap image from gallary and on button click save to Sdcard

hello very good noon to all.Actually i want to select an image from gallery and then i want to save the selected image in Sdcard which is available in android device.
pick image from Sd card:
Intent mediaChooser = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
// comma-separated MIME types
mediaChooser.setType("image/*");
startActivityForResult(mediaChooser, RESULT_LOAD_WATER_IMAGE);
And On Activity Result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
String path;
path = getRealPathFromURI(data.getData());
}
break;
}
Implementation Of getRealPathFromURI:
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();
}
}
Save Image To Sd Card On Click:
// TODO Auto-generated method stub
String root = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(root + "/Your Folder Name");
myDir.mkdirs();
String fname = "Your File Name";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("error" + e);
}
Using the code below, you can pick up an image from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
After that, the picked up image will be return by the onActivityResult() method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
//Get the image file path
final String imageFilePath = cursor.getString(0);
cursor.close();
//save it the sdcard
saveToSDCard(imageFilePath);
}
super.onActivityResult(requestCode, resultCode, data);
}

Android camera capture activity returns null Uri

This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
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();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}

Categories

Resources