upload captured image to cloudinary in android - android

I want to upload a captured picture image cloudinary I have an error in this statment :
cloudinary.uploader().upload(is, Cloudinary.emptyMap());
java.lang.NoClassDefFoundError: org.apache.commons.lang.StringUtils
I want to ask what should I pass at this to define the name of the pic
first I get the the uri and convert it to string to get the path
then convert this real path to InputStream
so, I could pass it to the cloudinary uploading statement
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
TextView tv;
String s="aa";
Map config = new HashMap();
Cloudinary cloudinary;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
config.put("cloud_name", "dkepfkeuu");
config.put("api_key", "key");
config.put("api_secret", "secret");
cloudinary = new Cloudinary(config);
tv=(TextView)findViewById(R.id.textView);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
Bitmap photo;
InputStream is;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
s= data.getDataString();
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
Uri uripath= data.getData();
String uri = getRealPathFromURI( uripath);
try {
is = new FileInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Toast.makeText(this, "uri:\n" +
uri, Toast.LENGTH_LONG).show();
tv.setText(s+"---"+uri);
try {
cloudinary.uploader().upload(is, Cloudinary.emptyMap());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor =getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}

You don't need to convert the Uri into a string, I am doing the following in my upload code:
InputStream in = getContentResolver().openInputStream(profileImageUri);
CloudinaryClient.upload(in, profileImageName);
CloudinaryClient:
public static void upload(final InputStream inputStream, final String publicId) {
final Map<String, String> options = new HashMap<>();
options.put("public_id", publicId);
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
cloudinary.uploader().upload(inputStream, options);
} catch (IOException e) {
//TODO: better error handling when image uploading fails
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
Note: you can pass null as options, I just use it to specifiy a name for the image I am uploading.

Related

Cant load picture

I have a problem when I'm trying to load a picture that saved on the phone.
I have a "Helper class"
public class FileHelper {
public static String saveBitmapToFile(Bitmap bitmap, Context context, String fileName) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// write the compressed bitmap to the outputStream(bytes)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = null;
try {
fo = context.openFileOutput(fileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
Toast.makeText(context, "בעיה ,", Toast.LENGTH_SHORT).show();
}
try {
fo.write(bytes.toByteArray());
fo.close();// close file output
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
}
Here's where I'm trying to upload the photo:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
iv = (ImageView) findViewById(R.id.ivPic);
btnTakePic = (Button) findViewById(R.id.btnpic);
btnPickPicture = (Button) findViewById(R.id.btnpicpic);
try {
bitmap = BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
} catch (FileNotFoundException e) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cam);
}
iv.setImageBitmap(bitmap);
btnTakePic.setOnClickListener(this);
btnPickPicture.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = null;
if (v == btnTakePic) {
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
} else if (v == btnPickPicture) {
Intent pickPickIntent = new Intent(Intent.ACTION_PICK);
File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String picDirPath = picDir.getPath();
Uri uData = Uri.parse(picDirPath);
pickPickIntent.setDataAndType(uData, "image/*");
startActivityForResult(pickPickIntent, PICK_PICTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK)
{
bitmap = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bitmap);
FileHelper.saveBitmapToFile(bitmap,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
} else if (requestCode == PICK_PICTURE) {
if (resultCode == RESULT_OK) {
Uri URI = data.getData();
String[] FILE = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
options = new BitmapFactory.Options();
int columnIndex = cursor.getColumnIndex(FILE[0]);
String ImageDecode = cursor.getString(columnIndex);
cursor.close();
options.inSampleSize = 5;
Bitmap bmp = BitmapFactory.decodeFile(ImageDecode, options);
iv.setImageBitmap(bmp);
FileHelper.saveBitmapToFile(bmp,getApplicationContext(),PIC_FILE_NAME);
Bitmap bitmapx = iv.getDrawingCache();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("BitmapImage", bitmapx);
}
}
}
and Here is where I am trying to load the saved pic:
private void updateHeader()
{
ImageView ivHeader = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.ivHeader);
try{
bitmap= BitmapFactory.decodeStream(this.openFileInput(PIC_FILE_NAME));
ivHeader.setImageBitmap(bitmap);
}
catch (FileNotFoundException e){
Toast.makeText(getApplicationContext(),"error occured",Toast.LENGTH_LONG);
}
}
I have to say that the Toast message is not shown and There are no errors. App not crashing but the pic stays with no change.
Make sure you have external read storage permission. Here is how to request permission.
PS: Also make sure you have added that permission to AndroidManifest.xml

Browse and upload pdf or word file in Android

private void getDocument()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/msword,application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
startActivityForResult(intent, REQUEST_CODE_DOC);
}
#Override
protected void onActivityResult(int req, int result, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(req, result, data);
if (result == RESULT_OK)
{
Uri fileuri = data.getData();
docFilePath = getFileNameByUri(this, fileuri);
}
}
// get file path
private String getFileNameByUri(Context context, Uri uri)
{
String filepath = "";//default fileName
//Uri filePathUri = uri;
File file;
if (uri.getScheme().toString().compareTo("content") == 0)
{
Cursor cursor = context.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION }, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String mImagePath = cursor.getString(column_index);
cursor.close();
filepath = mImagePath;
}
else if (uri.getScheme().compareTo("file") == 0)
{
try
{
file = new File(new URI(uri.toString()));
if (file.exists())
filepath = file.getAbsolutePath();
}
catch (URISyntaxException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
filepath = uri.getPath();
}
return filepath;
}
I am creating an android mobile application in which user can upload his CV (PDF form or word form) and which can be then sent to the server.
I have used this code to attach/upload PDF or word file, but when I run the application in Android Studio, the attachment button can't be clicked. How can I solve it?
public class RegisterActivity extends AppCompatActivity {
ImageButton btnAttach;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().setTitle("Registeration");
btnAttach = (ImageButton) findViewById(R.id.attachImageButton);
// view products click event
btnAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching All products Activity
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
}
public void attachImageButton_OnClick(View view) {
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
}
private void getDocument()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/msword,application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
// startActivityForResult(intent, REQUEST_CODE_DOC);
}
#Override
protected void onActivityResult(int req, int result, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(req, result, data);
if (result == RESULT_OK)
{
Uri fileuri = data.getData();
// docFilePath = getFileNameByUri(this, fileuri);
}
}
// get file path
private String getFileNameByUri(Context context, Uri uri)
{
String filepath = "";//default fileName
//Uri filePathUri = uri;
File file;
if (uri.getScheme().toString().compareTo("content") == 0)
{
Cursor cursor = context.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA, MediaStore.Images.Media.ORIENTATION }, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String mImagePath = cursor.getString(column_index);
cursor.close();
filepath = mImagePath;
}
else
if (uri.getScheme().compareTo("file") == 0)
{
try
{
file = new File(new URI(uri.toString()));
if (file.exists())
filepath = file.getAbsolutePath();
}
catch (URISyntaxException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
filepath = uri.getPath();
}
return filepath;
}
}

Android: Saving image from gallery and then loading into imageview

I have an onclick that will allow a user to select a file from gallery like so:
case R.id.ColourCustom:
customBorderChange();
break;
private void customBorderChange() {
final ImageView QPBackground = (ImageView) findViewById(R.id.QPBackground);
menuHandler.removeCallbacks(menuTimer);
menuHandler.postDelayed(menuTimer, 5000);
bgHandler.removeCallbacks(runnableBG);
bgHandler.postDelayed(runnableBG, 2000);
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GALLERY_REQUEST);
File file = getFileStreamPath("QuickPlayBG.png");
if (file.exists()) {
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
} else {
String uri21 = "#drawable/bg_green";
int imageResource21 = getResources().getIdentifier(uri21, null, getPackageName());
QPBackground.setBackgroundResource(imageResource21);
}
}
This sends you here:
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
Uri selectedImageUri;
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null !=
data) {
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
cursor.close();
}
try {
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
saveBGFile(photo);
} catch (Exception e) {
String errorMessage = "Make your mind up mate!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
try {
saveQPConfig();
} catch (IOException e) {
String errorMessage = "Saving failed";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Which saves the file, using saveBGFile:
public void saveBGFile(Bitmap image) {
FileOutputStream out = null;
String filename = "QuickPlayBG.png";
try {
out = new FileOutputStream(filename);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue is with this line only:
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
It doesn't load anything. If I change "QuickPlayBG.png" to another filename that I am using in another part of my app, it loads fine. Both files are created using the same method. I verified that "QuickPlayBG.png" exists.
Compiler gives me the following hint:
E/﹕ ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
E/﹕ isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0
I think it has to do with the way I am saving the image, but I cannot see the fault myself. What could be the problem, that it is not loading the image?
Edit:
Here is the getThumbnail method I am using (works for another filename):
public Bitmap getThumbnail(String filename) {
final Context context = this;
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
Bitmap thumbnail = null;
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() !exist", ex.getMessage());
}
}
return thumbnail;
}
Use this short and sweet code for this. use intent of gallery.
1.declaire variable.
private static int RESULT_IMG = 1;
String imgString;
2.call intent of gallery on onclick of button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
3.onActivityResult to your code.
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
try {
if (requestCode == RESULT_IMG && responseCode == RESULT_OK
&& null != data) {
Uri pickedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgString = cursor.getString(columnIndex);
cursor.close();
//set bitmap to your imageview
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory.decodeFile(imgString));
} else {
Toast.makeText(this, "please select picture",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "error message", Toast.LENGTH_LONG)
.show();
}
}

Why can't some images be displayed on ImageView (Android)?

When I pick an image from my gallery, screenshots are shown but some images taken from camera aren't shown.
To be more specific, images taken using the system Camera app can't be shown while the ones taken using Camera360 can.
I wonder if there's any problem with my code. If there isn't, maybe it's because of my phone?
Thanks in advance. Sorry, my English isn't very good.
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
img = (ImageView) findViewById(R.id.ImageView01);
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
Drawable image;
try {
InputStream inputStream = getContentResolver()
.openInputStream(selectedImageUri);
image = Drawable.createFromStream(inputStream, "file///"
+ selectedImagePath.toString());
} catch (FileNotFoundException e) {
image = getResources().getDrawable(R.drawable.ic_launcher);
}
img.setImageDrawable(null);
img.setImageDrawable(image);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Oh, I found the problem. My image is too large. Updated code with several improvements below:
private static Context context;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int SELECT_PICTURE = 3;
private String selectedImagePath;
private static String imageFilePath;
private static String videoFilePath;
private Uri fileUri;
private Bitmap bitmap;
private Button btnGallery, btnCamera;
private Intent selectPictureIntent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_image);
context = this;
btnGallery = (Button) findViewById(R.id.Button01);
btnCamera = (Button) findViewById(R.id.Button02);
btnGallery.setOnClickListener(this);
btnCamera.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
Log.d("bitmap", selectedImageUri.getScheme());
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
// Selected image is local image
Bitmap b = new BitmapDrawable(context.getResources(),
selectedImagePath).getBitmap();
int i = (int) (b.getHeight() * (512.0 / b.getWidth()));
bitmap = Bitmap.createScaledBitmap(b, 512, i, true);
} else {
// Selected image is Picasa image
loadPicasaImageFromGallery(selectedImageUri);
}
ImageView img = (ImageView) findViewById(R.id.ImageView01);
img.setImageBitmap(bitmap);
}
}
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
addImageToGallery(imageFilePath, context);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
addVideoToGallery(videoFilePath, context);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
}
public Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor = getContentResolver()
.openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor
.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else
return uri.getPath();
}
private void loadPicasaImageFromGallery(final Uri uri) {
String[] projection = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
if (columnIndex != -1) {
new Thread(new Runnable() {
// NEW THREAD BECAUSE NETWORK REQUEST WILL BE MADE THAT WILL
// BE A LONG PROCESS & BLOCK UI
// IF CALLED IN UI THREAD
public void run() {
try {
Bitmap bm = android.provider.MediaStore.Images.Media
.getBitmap(getContentResolver(), uri);
int i = (int) (bm.getHeight() * (512.0 / bm
.getWidth()));
bitmap = Bitmap
.createScaledBitmap(bm, 512, i, true);
// THIS IS THE BITMAP IMAGE WE ARE LOOKING FOR
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
}
cursor.close();
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MappyDiary");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MappyDiary", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
imageFilePath = mediaStorageDir.getPath() + File.separator + "IMG_"
+ timeStamp + ".jpg";
mediaFile = new File(imageFilePath);
} else if (type == MEDIA_TYPE_VIDEO) {
videoFilePath = mediaStorageDir.getPath() + File.separator + "VID_"
+ timeStamp + ".mp4";
mediaFile = new File(videoFilePath);
} else {
return null;
}
return mediaFile;
}
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
public static void addVideoToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Video.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
values);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Button01:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
selectPictureIntent = Intent
.createChooser(intent, "Select Picture");
startActivityForResult(selectPictureIntent, SELECT_PICTURE);
break;
case R.id.Button02:
// create Intent to take a picture and return control to the calling
// application
Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent2.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent2, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
default:
break;
}
}

[Android - Kitkat ]Get/pick an image from Android's built-in Gallery app programmatically

Try to pick only one particular image from the SD card.I am able to pick images from gallery and Photos app in kikat.But not getting file path when i pick image from recents am getting file path as null.
I tried https://stackoverflow.com/a/2636538/1140321.
This works for Kitkat
public class BrowsePictureActivity extends Activity{
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browsepicture);
imageView = (ImageView)findViewById(R.id.imageView1);
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
if (Build.VERSION.SDK_INT < 19) {
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
imageView.setImageBitmap(bitmap);
}
else {
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
imageView.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
}
You need to add permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Categories

Resources