I am trying to convert the image paths of selected images in my grid view to uris, so that I can then pass those onto my photo editor, and edit from there.
if (cb.isChecked()) {
String paths = imagePaths.get(i);
Uri uri = Uri.parse(paths);
editImagesUri[count] = uri;
count++;
}
That is my code where I am getting my NullPointerException, and I just can't seem to figure out what the problem is.
I have changed around the content in the if statement a few times so that it essentially does the same thing, but the error is still the same.
This is the value of paths:
imagePaths = new ArrayList<String>();
imagePaths = getPathOfAllImages(getActivity());
This is the value of uri:
private static Uri[] editImagesUri;
getPathOfAllImages is a method I found on this website as an answer. Here is the code for it:
public static ArrayList<String> getPathOfAllImages(Activity activity) {
ArrayList<String> absolutePathOfImageList = new ArrayList<String>();
String absolutePathOfImage = null;
String nameOfFile = null;
String absolutePathOfFileWithoutFileName = null;
Uri uri;
Cursor cursor;
int column_index;
int column_displayname;
int lastIndex;
int counter = 0;
// absolutePathOfImages.clear();
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaColumns.DATA,
MediaColumns.DISPLAY_NAME };
cursor = activity.managedQuery(uri, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
column_displayname = cursor
.getColumnIndexOrThrow(MediaColumns.DISPLAY_NAME);
// cursor.moveToFirst();
while (cursor.moveToNext()) {
// for(int i=0; i<cursor.getColumnCount();i++){
// Log.i(TAG,cursor.getColumnName(i)+".....Data Present ...."+cursor.getString(i));
// }
// Log.i(TAG,"=====================================");
absolutePathOfImage = cursor.getString(column_index);
nameOfFile = cursor.getString(column_displayname);
lastIndex = absolutePathOfImage.lastIndexOf(nameOfFile);
lastIndex = lastIndex >= 0 ? lastIndex
: nameOfFile.length() - 1;
absolutePathOfFileWithoutFileName = absolutePathOfImage
.substring(0, lastIndex);
if (absolutePathOfImage != null) {
absolutePathOfImageList.add(absolutePathOfImage);
}
}
// Log.i(TAG,"........Detected images for Grid....."
// + absolutePathOfImageList);
return absolutePathOfImageList;
}
Related
I Know this is already answered question.But I'm unable to figure it out when using SQLite DB. My app captures some documents and will be stores in phone memory. I'm using SQLite DB in my app which stores the path of the above image. How can i delete the image from phone memory if i delete the image in SQLite DB.
String photoPath = cursor.getString(i_COL_PICTURE);
--My path is
`"content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F153/ORIGINAL/NONE/1743496576"
`
When you want delete some file in your storage, Just do this.
File file = new File(yourFilePathHere);
deleted = file.delete();
I am considering you have required permissions because you are able to write files in storage.
Edit
You are using MediaStore for getting images. So now when you want delete file you should delete file from MediaStore also. I have a method which will help you.
public static int deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
int deletedRow = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
return deletedRow;
}
} else return result;
return result;
}
Call it in your Activity like
deleteFileFromMediaStore(getContentResolver(), fileToDelete)
Note Check if you are getting absolute path by MediaStore. Here is my method to get all gallery images if you have problem with your code.
public static ArrayList<ModelBucket> getImageBuckets(Context context) {
ArrayList<ModelBucket> list = new ArrayList<>();
String absolutePathOfImage;
String absoluteFolder;
boolean same_folder = false;
int pos = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = context.getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
if (cursor == null) return null;
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
absoluteFolder = cursor.getString(column_index_folder_name);
Log.d("Column", absolutePathOfImage);
Log.d("Folder", absoluteFolder);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getFolderName().equals(absoluteFolder)) {
same_folder = true;
pos = i;
break;
} else {
same_folder = false;
}
}
if (same_folder) {
ArrayList<String> al_path = new ArrayList<>(list.get(pos).getAllFilesPath());
al_path.add(absolutePathOfImage);
list.get(pos).setAllFilesPath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
ModelBucket modelBucket = new ModelBucket();
modelBucket.setFolderName(absoluteFolder);
modelBucket.setAllFilesPath(al_path);
list.add(modelBucket);
}
}
return list;
}
here ModelBucket.class is a model class.
public class ModelBucket {
String folderName;
ArrayList<String> allFilesPath;
ArrayList<ModelFile> files;
// make getter setter
}
before deleting the image get the path of the image and pass the path to below code
File fdelete = new File(path);
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + path);
} else {
System.out.println("file not Deleted :" + path);
}
}
after this remove the path from sqlite db
If you have your Uri pointing to the file you can do :
String pathToFile = myUri.getEncodedPath(); // this gives your the real path to the file, like /emulated/0/sdcard/myImageFile.jpg
File file = new File(pathToFile);
if(file.exists()){
file.delete();
}
I'm working on a custom image gallery for my application but I got a serious issue under Samsung Galaxy S4 and S5. The following code works great on HTC and Xperia devices but not at all on Samsung ones.
Basically, the pathes are always null on these devices.
Here is the code I made.
In big lines, it returns a list of categories containing a name and a list of images. The aim is to provide a folder based gallery like the native one.
Should you have any idea why it fails on Samsung galaxy ?
Thanks for your help.
public List<Category> getCategories()
{
Map<String, Category> map = new HashMap<String, Category>();
String[] projection = new String[] {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
};
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Media.DATE_TAKEN + " DESC");
if (cursor == null) return;
if (cur.moveToFirst())
{
Category category = null;
long id = 0L;
String bucket = null;;
int idColumn = cur.getColumnIndex(MediaStore.Images.Media._ID);
int bucketColumn = cur.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
do
{
id = cur.getLong(idColumn);
bucket = cur.getString(bucketColumn);
if (map.get(bucket) == null)
{
category = new Category(bucket);
map.put(bucket, category);
}
category = map.get(bucket);
category.addImage( idToImage(id) );
}
while (cur.moveToNext());
}
return map.values().toArray();
}
private Image idToImage(long id)
{
Image image = new Image();
image.setThumbnail( getThumbnail(id) );
image.setImage( getImage(id) );
return image;
}
private String getThumbnail(long id)
{
String path = null;
Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(getContentResolver(), id, MediaStore.Images.Thumbnails.MINI_KIND, null);
if( cursor != null && cursor.getCount() > 0 )
{
cursor.moveToFirst();
path = cursor.getString( cursor.getColumnIndex( MediaStore.Images.Thumbnails.DATA ) );
cursor.close();
}
return path;
}
private String getImage(long id)
{
String path = null;
String[] projection = {MediaStore.Images.Media.DATA};
String where = MediaStore.Images.Media._ID + " = " + id;
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, where, null, null);
int dataColumn = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if( cursor != null && cursor.getCount() > 0 )
{
cursor.moveToFirst();
path = cursor.getString(dataColumn);
}
return path;
}
It will work
/**
* Get actual file path from gallery
*/
public String getPath(Uri uri, Context ctx) {
String[] projection = {MediaStore.Images.Media.DATA};
String result;
Cursor cursor = ctx.getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) {
return null;
}
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
return result;
}
In my application there is a button, that, when pressed, is supposed to open either the picture gallery, or the video gallery, or the audioplayer.
Please how would I construct an intent to perform that?
Try with this just onclick of any button pass the file path and then this method poen any type of file according to that file
File file = new File(filePath);
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null)
type = "*/*";
Uri uri = Uri.parse("www.google.com");
Intent type_intent = new Intent(Intent.ACTION_VIEW, uri);
Uri data = Uri.fromFile(file);
type_intent.setDataAndType(data, type);
startActivity(type_intent);
For images
private void getallimages(File dir)
{
String[] STAR = { "*" };
controller.images.clear();
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();//this is my wrapper class
if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
{
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default this it do for check box unselect u dont need to fill this
controller.images.add(imageItem);//this i just add all info in wrapper class
}
}
}
for audio
private void getallaudio()
{
String[] STAR = { "*" };
controller.audioWrapper.clear();
Cursor audioCursor = cntx.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
if (audioCursor != null)
{
if (audioCursor.moveToFirst())
{
do
{
String path = audioCursor.getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
controller.audioWrapper.add(new MediaWrapper(new File(path).getName(), path, "Audio",false));
}while (audioCursor.moveToNext());
}
}
}
and for video
private void getallvideo()
{
String[] STAR = { "*" };
controller.videoWrapper.clear();
Cursor videoCursor = cntx.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
if (videoCursor != null)
{
if (videoCursor.moveToFirst())
{
do
{
String path = videoCursor.getString(videoCursor.getColumnIndex(MediaStore.Images.Media.DATA));
controller.videoWrapper.add(new MediaWrapper(new File(path).getName(), path, "Video",false,color_string));
}while (videoCursor.moveToNext());
}
}
}
I would realize it this way:
On Button click, pop up a custom dialog box with 3 buttons.
picture gallery button
video gallery button
audio player button
Depending on user selection, you start the intent which corresponds to the action.
Anyone know how to get a listing of all images that show up in the Android Gallery?
This query is only gets pictures taken locally on the phone. Does anyone know the URI where the Picasa image database is stored?? Appreciate the help.
private void getListOfAllPictures()
{
final String[] filePathColumn = { MediaStore.Images.Media._ID, MediaColumns.DATA, MediaColumns.DISPLAY_NAME, Images.Media.ORIENTATION, Images.Media.LATITUDE, Images.Media.LONGITUDE };
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
filePathColumn, null, null, null);
Vector<ImageDescriptor> imageDescriptors = new Vector<ImageDescriptor>();
if(cursor != null)
{
cursor.moveToFirst();
int IMG_ID_INDEX = cursor.getColumnIndex(MediaStore.Images.Media._ID);
int DATA_INDEX = cursor.getColumnIndex(MediaColumns.DATA);
int LATITUDE_INDEX = cursor.getColumnIndex(Images.Media.LATITUDE);
int LONGITUDE_INDEX = cursor.getColumnIndex(Images.Media.LONGITUDE);
int ORIENTATION_INDEX = cursor.getColumnIndex(Images.Media.ORIENTATION);
while(!cursor.isAfterLast())
{
//Blah Blah
cursor.moveToNext();
}
}
cursor.close();
Log.v(TAG, "Found " + imageDescriptors.size() + " images.");
}
ok its my code and it work for me it give all images which i can see in Android Gallery
just call this function from this line
getallimages(Environment.getExternalStorageDirectory());
and my function is below
private void getallimages(File dir)
{
String[] STAR = { "*" };
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default
controller.images.add(imageItem);
}
}
is possible to load thumbnails with Universal image Loader for android?. i got Thumbnail of image and video file in Sdcard then i don't know how to display these thumbnails with using of this library in gridview so please tell me anyone know how to do?
i got thumbnail from this code:
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID }; // Images getting
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
imagecursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
/*this.count = params[0];
if(count == 0)
this.count = imagecursor.getCount();
else if(count >= 12)
*/
bitList = new ArrayList<Bitmap>();
arrPathList = new ArrayList<String>();
selectedPath = new ArrayList<String>();
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
bitList.add( MediaStore.Images.Thumbnails.getThumbnail(
mContext.getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null));
arrPathList.add(imagecursor.getString(dataColumnIndex));
}
this.durationcount = new ArrayList<String>(); // Video Getting
final String[] parameters = { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID, MediaStore.Video.Media.DURATION , MediaStore.Video.Media.MIME_TYPE}; // Videos getting
final String orderBy_v = MediaStore.Video.Media._ID;
videocursor = mContext.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, parameters, null,
null, orderBy_v);
int video_column_index = videocursor.getColumnIndex(MediaStore.Video.Media._ID);
int video_column_duration = videocursor.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.DURATION); // for duration of the video
totalCount = imagecursor.getCount() + videocursor.getCount(); /// Checking
durationcount_a = new String[imagecursor.getCount() + videocursor.getCount()];
for(int i = 0; i < videocursor.getCount(); i ++){
videocursor.moveToPosition(ii);
int id_v = videocursor.getInt(video_column_index);
int datacolumn_v = videocursor.getColumnIndex(MediaStore.Video.Media.DATA);
long duration = videocursor.getInt(video_column_duration); // getting duration of the every videos
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(duration),
TimeUnit.MILLISECONDS.toMinutes(duration) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration)),
TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
durationcount.add(hms);
durationcount_a[(imagecursor.getCount()) + ii] = hms;
bitList.add(MediaStore.Video.Thumbnails.getThumbnail(mContext.getContentResolver(), id_v,
MediaStore.Video.Thumbnails.MICRO_KIND, null));
arrPathList.add(videocursor.getString(datacolumn_v));
}
thumbnailsselection = new boolean[totalCount];
return null;
}
Thanks in advance.
u have to get the path or uri of the thumbnail to load it using universal image loader.
see this to get the uri :-
Get thumbnail Uri/path of the image stored in sd card + android
i have also worked on same kind of project and hosted it over git-hub .. i have two versions of it one without ImageLoader and other with imageloader .. right now i have hosted only former one :-
here is the path https://github.com/r4jiv007/CustomFilePicker.git
here is the method i used :-
private String getImageThumbnail(int id) {
final String thumb_DATA = MediaStore.Images.Thumbnails.DATA;
final String thumb_IMAGE_ID = MediaStore.Images.Thumbnails.IMAGE_ID;
Uri uri = thumbUri;
String[] projection = {thumb_DATA, thumb_IMAGE_ID};
String selection = thumb_IMAGE_ID + "=" + id + " AND " + MediaStore.Images.Thumbnails.KIND + "=" + MediaStore.Images.Thumbnails.MINI_KIND;
Cursor thumbCursor = getContentResolver().query(uri, projection, selection, null, null);
String thumbPath = null;
Bitmap thumbBitmap = null;
if (thumbCursor != null && thumbCursor.getCount() > 0) {
thumbCursor.moveToFirst();
int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);
thumbPath = thumbCursor.getString(thCulumnIndex);
/*
Toast.makeText(getApplicationContext(),
thumbPath,
Toast.LENGTH_LONG).show();*/
// thumbBitmap = BitmapFactory.decodeFile(thumbPath);
}
Log.i("ImageMiniKind", thumbPath + "");
return thumbPath;
}
and u have to use :-
imageLoader.displayImage("file://" + fileX.getmThumbPath() + "", imageView, options);
for loading the image.. and also beware some times there is no thumbnail for images !!
for loading thumbnail of video files
private String getVideoThumbnail(int id) {
final String thumb_DATA = MediaStore.Video.Thumbnails.DATA;
final String thumb_VIDEO_ID = MediaStore.Video.Thumbnails.VIDEO_ID;
Uri uri = MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI;
String[] projection = {thumb_DATA, thumb_VIDEO_ID};
String selection = thumb_VIDEO_ID + "=" + id + " AND " + MediaStore.Video.Thumbnails.KIND + "=" + MediaStore.Video.Thumbnails.MINI_KIND;
Cursor thumbCursor = getContentResolver().query(uri, projection, selection, null, null);
String thumbPath = null;
// Bitmap thumbBitmap = null;
if (thumbCursor.moveToFirst()) {
int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);
thumbPath = thumbCursor.getString(thCulumnIndex);
}
return thumbPath;
}
now all you have to do is pass the path to imageloader library