Retrieve all images directories in android - android

I have tried this to get directories and load images from them but it is very slow to load images and when camera is selected it crashed after some time...
< -------- Code to get directories and images from them ------- >
public static ArrayList<String> getImageBuckets(Context mContext){
ArrayList<String> buckets = new ArrayList<>();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String bucketPath = cursor.getString(cursor.getColumnIndex(projection[0]));
String fisrtImage = cursor.getString(cursor.getColumnIndex(projection[1]));
file = new File(fisrtImage);
if (file.exists() && !buckets.contains(bucketPath)) {
buckets.add(bucketPath);
}
}
cursor.close();
}
return buckets;
}
public static ArrayList<String> getImagesByBucket(Context mContext , #NonNull String bucketPath){
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.DATA};
String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME+" =?";
String orderBy = MediaStore.Images.Media.DATE_ADDED+" DESC";
ArrayList<String> images = new ArrayList<>();
Cursor cursor = mContext.getContentResolver().query(uri, projection, selection,new String[]{bucketPath}, orderBy);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String path = cursor.getString(cursor.getColumnIndex(projection[0]));
file = new File(path);
if (file.exists() && !images.contains(path)) {
images.add(path);
}
}
cursor.close();
}
return images;
}
< ---------- Here is adapter and method to select directory --------->
<--------------------Adapter------------------>
public class GridImageAdapter extends ArrayAdapter<String> {
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
#Override
public int getCount() {
return imgURLs.size();
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridImageProgressbar);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridImageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String imgURL = getItem(position);
Picasso.with(mContext).load(mAppend + imgURL).error(R.drawable.ic_person).into(holder.image, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
if (holder.mProgressBar != null) {
Picasso.with(mContext).load(mAppend + imgURL).into(holder.image);
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onError() {
if (holder.mProgressBar != null) {
Picasso.with(mContext).load(mAppend + imgURL).into(holder.image);
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
private static class ViewHolder {
SquareImageView image;
ProgressBar mProgressBar;
}
}
< -------------- Method to set grid view ----------->
private void Directory() {
directories = FileSearch.getImageBuckets(getActivity());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
,android.R.layout.simple_spinner_item ,directories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Log.d(TAG, "onItemSelected: selected" + directories.get(position));
setGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setGridView(String selectedDir){
Log.d(TAG, "setGridView: Dir chosen");
final ArrayList<String> imageURL = FileSearch.getImagesByBucket(getActivity() ,selectedDir);
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLOUMN;
gridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(getActivity() , R.layout.grid_image_layout ,append , imageURL);
gridView.setAdapter(adapter);
}

Related

How to get all images from gallery in API 29?

So I am loading all images from the gallery it is working fine but MediaStore.MediaColumns.DATA is deprecated. I am unable to find an example that using the latest method to perform this task without MediaStore.MediaColumns.DATA
My Code right now
imageGallery = findViewById(R.id.image_grid);
ArrayList<String> imagePathList = getGalleryImagesPath();
final GridAdapter gridAdapter = new GridAdapter(AddPostActivity.this, imagePathList);
imageGallery.setAdapter(gridAdapter);
imageGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Picasso.get().load(new File(gridAdapter.getItem(position))).resizeDimen(R.dimen.add_post_image, R.dimen.add_post_image).into(addPostImage);
postButton.setEnabled(true);
}
});
private ArrayList<String> getGalleryImagesPath() {
ArrayList<String> imagePathList = new ArrayList<String>();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
// MediaStore.MediaColumns.DATA is deprecated
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
imagePathList.add(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)));
}
cursor.close();
}
return imagePathList;
}
private static class GridAdapter extends BaseAdapter {
private final ArrayList<String> imagePathList;
private final Context context;
GridAdapter(Context context, ArrayList<String> imagePathList) {
this.imagePathList = imagePathList;
this.context = context;
}
#Override
public int getCount() {
return imagePathList.size();
}
#Override
public String getItem(int position) {
return imagePathList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
SquareImageView gridImage;
if (convertView == null) {
gridImage = new SquareImageView(context);
} else {
gridImage = (SquareImageView) convertView;
}
Picasso.get().load(new File(getItem(position))).resize(200, 200).into(gridImage);
return gridImage;
}
}
Update #1
private ArrayList<Uri> getGalleryImagesPath() {
ArrayList<Uri> imagePathList = new ArrayList<Uri>();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns._ID};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
imagePathList.add(ContentUris.withAppendedId(uri, id));
}
cursor.close();
}
return imagePathList;
}

Android - List images from external storage into Recycleview

I'm trying to do a simple thing and its get all images from the external storage into recycle view and display them.
My problem is that for some reason i recieve null and i dont know why.
I successfully getting all the images into array list of string.
And then on the Reycleview i'm getting error of null exception.
Cant find what im doing wrong.
The log shows me that the error comes from the Recycler.From the method "onBindViewHolder" (i also mentioned this line).
It craches holder.imgView.setImageURI(imageUri); - still cant understand why,
even though i checked that its not null.
My Code
private BootstrapButton btnLoadImage;
private RecyclerView rvImages;
private static final int REQUEST_CODE = 1;
private boolean mStoragePermissions;
private ArrayList<String> imageLists;
private ImageViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage = (BootstrapButton)findViewById(R.id.btnLoadImges);
rvImages = (RecyclerView)findViewById(R.id.rvPictures);
btnLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mStoragePermissions){
imageLists = getFilePaths();
Log.d("MainActivity",imageLists.toString());
if(imageLists != null)
setAdapter(imageLists);
}else{
verifyStoragePermissions();
}
}
});
}
private void setAdapter(ArrayList<String> imageLists) {
adapter = new ImageViewAdapter(getApplication(),imageLists);
rvImages.setAdapter(adapter);
rvImages.setLayoutManager(new GridLayoutManager(getApplication(),3));
btnLoadImage.setVisibility(View.INVISIBLE);
}
public ArrayList<String> getFilePaths()
{
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null)
{
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst()))
{
do
{
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try{
dirList.add(tempDir);
}
catch(Exception e)
{
Log.d("MainActivity",e.getMessage().toString());
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for(int i=0;i<dirList.size();i++)
{
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if(imageList == null)
continue;
for (File imagePath : imageList) {
try {
if(imagePath.isDirectory())
{
imageList = imagePath.listFiles();
}
if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG") )
{
String path= imagePath.getAbsolutePath();
resultIAV.add(path);
}
}
// }
catch (Exception e) {
e.printStackTrace();
}
}
}
return resultIAV;
}
public class ImageViewAdapter extends RecyclerView.Adapter<ImageViewHolder>{
private LayoutInflater inflater;
private Context context;
private ArrayList<String> data;
public ImageViewAdapter(Context context, ArrayList<String> data){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.data = data;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.image_item,parent,false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
String imgSrc = data.get(position);
Uri imageUri = Uri.parse(imgSrc);
if(imageUri != null) {
//**Here i always getting null exception **
holder.imgView.setImageURI(imageUri);
}
}
#Override
public int getItemCount() {
return data.size();
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
private ImageView imgView;
public ImageViewHolder(View itemView){
super(itemView);
imgView = (ImageView)findViewById(R.id.imageView);
}
}
}
What is null is this in your ImageViewHolder ImageView imgView;
You're using
imgView = (ImageView)findViewById(R.id.imageView);
But look that findViewById is finding a view in your activity, and not in your RecyclerView ViewHolder, precisely in your image_item.xml root layout.
So, just use findViewById in that view:
public ImageViewHolder(View itemView){
super(itemView);
imgView = (ImageView) itemView.findViewById(R.id.imageView);
}

FileNotFoundException using Universal Image Loader

This is my first app on Android and I am using the Universal Image Loader Library to load images into a GridView.
The problem I am having is
FileNotFoundException: No entry for content://media/external/images/thumbnails/...(all thumbnails )
The thumbnails are not loaded in the GridView, but when I tap on a gridItem, the Intent is started and an imageId is passed to the next activity.
Here is the code I am using (based on the Sample example at UIL( github)
public class ImageGridFragment extends AbsListViewBaseFragment {
Cursor mCursor;
int[]imageIDs;
String bucket;
ArrayList<String> imageUrls;
int firstImageIndex;
int lastImageIndex;
int columnIndex;
String sender;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getActivity().getIntent();
sender = intent.getExtras().getString("sender");
bucket = intent.getExtras().getString("albumName");
imageIDs = getImagesFromBucket();
imageUrls = new ArrayList<>();
for(int i = 0; i < imageIDs.length; i++){
int imageID = imageIDs[i];
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
imageUrls.add(imageURI.toString());
}
BitmapFactory.Options resizeOptions = new BitmapFactory.Options();
resizeOptions.inSampleSize = 3; // decrease size 3 times
resizeOptions.inScaled = true;
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.decodingOptions(resizeOptions)
.postProcessor(new BitmapProcessor() {
#Override
public Bitmap process(Bitmap bmp) {
return Bitmap.createScaledBitmap(bmp, 120, 120, false);
}
})
.build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gallery_grid_view, container, false);
listView = (GridView) rootView.findViewById(R.id.gridView);
listView.setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent returnToSender;
if (sender.equals("First")) {
returnToSender = new Intent(ImageGridFragment.this.getActivity(), FirstImageActivity.class);
firstImageIndex = 0;
returnToSender.putExtra("firstImageIndex", firstImageIndex);
// Move cursor to current position
mCursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = mCursor.getInt(columnIndex);
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID);
returnToSender.putExtra("imageURI", imageURI);
String comingFrom = "gridView";
returnToSender.putExtra("comingFrom", comingFrom);
mCursor.close();
returnToSender.putExtra("albumName", bucket);
} else {
returnToSender = new Intent(ImageGridFragment.this.getActivity(), LastImageActivity.class);
lastImageIndex = 0;
returnToSender.putExtra("lastImageIndex", lastImageIndex);
}
startActivity(returnToSender);
}
});
return rootView;
}
private int[] getImagesFromBucket()
{
int[] ids = null;
ArrayList<Integer> lstIds = new ArrayList<>();
String searchParams;
if(bucket != null)
{
searchParams = "bucket_display_name = \""+bucket+"\"";
}
else
{
return ids;
}
String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN};
String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";
mCursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
searchParams,
null,orderBy);
if(mCursor.moveToFirst())
{
do
{
int id = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID));
lstIds.add(id);
}
while(mCursor.moveToNext());
}
ids = new int[lstIds.size()];
for(int i=0;i<ids.length;i++)
{
ids[i] = lstIds.get(i);
}
return ids;
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
ImageAdapter() {
inflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.item_grid_image, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.gridImageView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ImageLoader.getInstance()
.displayImage(imageUrls.get(position), holder.imageView, options, new SimpleImageLoadingListener() {
});
return view;
}
}
static class ViewHolder {
ImageView imageView;
}
}
Any help with understanding what I am doing wrong and how to fix it would be greatly appreciated.
SOLVED!
I changed this line
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
to
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID);
If your path having filename with extension like .png, .jpg or any than it is file path, in such case you have to add string as
"file://"+ filename.
And if your path not having any extension and not web url, so it is content uri, here you have to add
"content://"+filename.
For more click here.

Slow loading images from sdcard to gridview

I've been trying to create multiple image chooser, everything works fine, but the grid scroll is very lazy and slow, I've been tried to use different libraries for image loading in getView() (Picasso,aquery..)
but its no difference ,even with asynctask, that's my code:
Main:
public class Media extends ActionBarActivity {
private AQuery aq;
GridView myGridView;
MyAdapter mySimpleCursorAdapter;
boolean isOddClicked = true;
static String img=null;
final Uri srcUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String srcData = MediaStore.Images.Media.DATA;
final String srcImgId = MediaStore.Images.Media._ID;
final Uri thumbUri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
final String thumb_DATA = MediaStore.Images.Thumbnails.DATA;
final String thumb_IMAGE_ID = MediaStore.Images.Thumbnails.IMAGE_ID;
ArrayList<String> al = new ArrayList<String>(5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media);
//Always show the menu
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
myGridView = (GridView)findViewById(R.id.gridview);
//
CursorLoader cursorLoader = new CursorLoader(
this,srcUri,null,null,null,MediaStore.Images.Media.DATE_TAKEN+ " DESC");
//
Cursor cursor = cursorLoader.loadInBackground();
//
int[] to = {android.R.id.text1};
String[] from = {MediaStore.MediaColumns.TITLE};
mySimpleCursorAdapter = new MyAdapter(
this,android.R.layout.simple_list_item_1,
cursor,from,to,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//
myGridView.setAdapter(mySimpleCursorAdapter);
myGridView.setOnItemClickListener(myOnItemClickListener);
}
OnItemClickListener myOnItemClickListener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Cursor cursor = mySimpleCursorAdapter.getCursor();
cursor.moveToPosition(position);
int int_ID = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID));
}
};
private Bitmap getThumbnail(int id){
String[] thumbColumns = {srcData, srcImgId};
CursorLoader thumbCursorLoader = new CursorLoader(
this,srcUri,thumbColumns,srcImgId + "=" + id,null,null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
Bitmap thumbBitmap = null;
if(thumbCursor.moveToFirst()){
int thCulumnIndex = thumbCursor.getColumnIndex(srcData);
String thumbPath = thumbCursor.getString(thCulumnIndex);
Toast.makeText(getApplicationContext(),thumbPath,Toast.LENGTH_LONG).show();
thumbBitmap = BitmapFactory.decodeFile(thumbPath);
//Create a Dialog to display the thumbnail
AlertDialog.Builder thumbDialog = new AlertDialog.Builder(Media.this);
ImageView thumbView = new ImageView(Media.this);
thumbView.setImageBitmap(thumbBitmap);
LinearLayout layout = new LinearLayout(Media.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(thumbView);
thumbDialog.setView(layout);
thumbDialog.show();
}else{
Toast.makeText(getApplicationContext(),"NO Thumbnail!",Toast.LENGTH_LONG).show();
}
return thumbBitmap;
}
public class MyAdapter extends SimpleCursorAdapter{
Cursor myCursor;
Context myContext;
public MyAdapter(Context context, int layout, Cursor c, String[] from,int[] to, int flags) {
super(context, layout, c, from, to, flags);
myCursor = c;
myContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater=getLayoutInflater();
convertView =inflater.inflate(R.layout.media_row, parent, false);
holder = new ViewHolder();
holder.thumbnail = (ImageView)convertView.findViewById(R.id.thumb);
holder.title = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
myCursor.moveToPosition(position);
final int myID = myCursor.getInt(myCursor.getColumnIndex(MediaStore.Images.Media._ID));
final String[] thumbColumns = {srcData ,srcImgId};
CursorLoader thumbCursorLoader = new CursorLoader(
myContext,srcUri,thumbColumns,srcImgId + "=" + myID,null,null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
if(thumbCursor.moveToFirst()){
final int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);
final String thumbPath = thumbCursor.getString(thCulumnIndex);
Bitmap o = MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), myID, Images.Thumbnails.MICRO_KIND, null);
//holder.thumbnail.setImageBitmap(o);
//Phase II:
String uri = null;
Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(
getContentResolver(), myID,
MediaStore.Images.Thumbnails.MINI_KIND,null );
if( cursor != null && cursor.getCount() > 0 ) {
cursor.moveToFirst();//**EDIT**
uri = cursor.getString( cursor.getColumnIndex( MediaStore.Images.Thumbnails.DATA ) );
}
MediaAsync loadAsync = new MediaAsync(getApplicationContext(), holder.thumbnail);
loadAsync.onPostExecute(thumbPath);
/*
holder.thumbnail.setOnClickListener(new OnClickListener(){
public void onClick(View v){
img = thumbPath;
al.add(thumbPath);
if (holder.title.isChecked()) {
holder.title.setChecked(false);
holder.thumbnail.setBackgroundResource(0);
}else{
holder.title.setChecked(true);
holder.thumbnail.setBackgroundResource(R.drawable.media_row_border);
}
}
});
*/
}
return convertView ;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.media, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
else if (id == R.id.done) {
Intent main = new Intent(this, Main.class);
main.putStringArrayListExtra("media_lst", al);
startActivity(main);
}
return super.onOptionsItemSelected(item);
}
private static class ViewHolder {
ImageView thumbnail;
CheckBox title;
}
}
mediaAsynce :
public class MediaAsync extends AsyncTask<String,String, String>{
private ImageView mImageView;
private Context mContext;
public MediaAsync(Context context,ImageView imageView) {
mImageView = imageView;
mContext = context;
}
#Override
protected String doInBackground(String... params) {
String url = params[0].toString();
return url;
}
#Override
protected void onPostExecute(String result) {
Uri uri = Uri.fromFile(new File(result));
Picasso.with(mContext)
.load(uri)
//.resize(100, mWidth)
.into(mImageView);
// AQuery aq = new AQuery(mContext);
// aq.id(mImageView).image(result, true, true, 0, R.drawable.ic_launcher);
}
}
As you said you have tried picasso library it should work
Just try once again using picassso like this Async task and all is not required
Just create a simple adapter and load images.
public class GridViewDynamicAdapter extends BaseDynamicGridAdapter {
ImageDetails details;
public static List<ImageDetails> list;
public GridViewDynamicAdapter(Context context, List<ImageDetails> items,
int columnCount) {
super(context, items, columnCount);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheeseViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.item_grid, null);
holder = new CheeseViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (CheeseViewHolder) convertView.getTag();
}
if (position == getCount() - 1) {
ImageApplication.fromRecorderPaths = (List<ImageDetails>) getItems();
}
details = (ImageDetails) getItem(position);
// Log.d("Setting=", details.path);
holder.build(getContext(), details.path);
return convertView;
}
private class CheeseViewHolder {
private ImageView image;
private CheeseViewHolder(View view) {
image = (ImageView) view.findViewById(R.id.item_img);
}
void build(final Context context, String title) {
Picasso.with(context).load(new File(title)).centerCrop()
.resize(150, 150).error(R.drawable.ic_launcher).into(image);
}
}
}
OR
Try this example

How to show all video thumbnails stored in a specific folder in sd card

I am getting bitmaps from MediaStore like this
public class VideoStoredInSDCard extends Activity
{
private Cursor videoCursor;
private int videoColumnIndex;
ListView videolist;
int count;
String thumbPath;
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,MediaStore.Video.Thumbnails.VIDEO_ID };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialization();
}
private void initialization()
{
System.gc();
String[] videoProjection = { MediaStore.Video.Media._ID,MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,MediaStore.Video.Media.SIZE };
videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,videoProjection, null, null, null);
count = videoCursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoListAdapter(this.getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id)
{
System.gc();
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videoCursor.moveToPosition(position);
String filename = videoCursor.getString(videoColumnIndex);
Log.i("FileName: ", filename);
//Intent intent = new Intent(VideoActivity.this, ViewVideo.class);
//intent.putExtra("videofilename", filename);
//startActivity(intent);
}};
public class VideoListAdapter extends BaseAdapter
{
private Context vContext;
int layoutResourceId;
public VideoListAdapter(Context c)
{
vContext = c;
}
public int getCount()
{
return videoCursor.getCount();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View listItemRow = null;
listItemRow = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
TextView txtTitle = (TextView)listItemRow.findViewById(R.id.txtTitle);
TextView txtSize = (TextView)listItemRow.findViewById(R.id.txtSize);
ImageView thumbImage = (ImageView)listItemRow.findViewById(R.id.imgIcon);
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videoCursor.moveToPosition(position);
txtTitle.setText(videoCursor.getString(videoColumnIndex));
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videoCursor.moveToPosition(position);
txtSize.setText(" Size(KB):" + videoCursor.getString(videoColumnIndex));
int videoId = videoCursor.getInt(videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Cursor videoThumbnailCursor = managedQuery(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID+ "=" + videoId, null, null);
if (videoThumbnailCursor.moveToFirst())
{
thumbPath = videoThumbnailCursor.getString(videoThumbnailCursor.getColumnIndex(MediaStore.Video.Thumbna ils.DATA));
Log.i("ThumbPath: ",thumbPath);
}
thumbImage.setImageURI(Uri.parse(thumbPath));
return listItemRow;
}
}
}
How to get thumbnails from a specific folder in sd card. I am using this tutorial http://gypsynight.wordpress.com/2012/02/17/how-to-show-all-video-file-stored-in-your-sd-card-in-a-listview/
It can be done easily this way:
int videoId = videoCursor.getInt(videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
ContentResolver cr = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId, MediaStore.Video.Thumbnails.MICRO_KIND, options);
thumbImage.setImageBitmap(curThumb);

Categories

Resources