How to get all images from gallery in API 29? - android

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;
}

Related

Retrieve all images directories in 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);
}

How to get all the image from gallery to my application using recyclerview?and how to set image in onbind holder for loding gallery images

public void onBindViewHolder(MyAdapter.MyViewHolde holder, int position) {
//how to set image for loading the images for gallery
----------
}
//and code for how to get images from gallery in main activity
You have to first get all images from gallery in you activity then have to set the list of images to RecyclerView
Use below method to get all all images-
private ArrayList<String> getAllShownImagesPath(Activity activity) {
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
ArrayList<String> listOfAllImages = new ArrayList<String>();
String absolutePathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME };
cursor = activity.getContentResolver().query(uri, projection, null,
null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
column_index_folder_name = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
return listOfAllImages;
}
Now set the This list of images to RecyclerView Adapter.
Take this RecyclerView Example as an reffrence to set all gallery images.
public class GalleryFragment extends Fragment {
public GalleryFragment() {
// Required empty public constructor
}
private Context context;
private RecyclerView recyclerView;
ArrayList<String> imageData;
MyAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
context = getActivity();
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
MyTask myTask = new MyTask();
myTask.execute();
return view;
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
imageData = getAllShownImagesPath(getActivity());
Log.e("imageData: ", String.valueOf(imageData.size()));
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new MyAdapter(imageData, getActivity());
recyclerView.setAdapter(adapter);
}
}
private ArrayList<String> getAllShownImagesPath(Activity activity) {
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
ArrayList<String> listOfAllImages = new ArrayList<String>();
String absolutePathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
cursor = activity.getContentResolver().query(uri, projection, null,
null, 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);
listOfAllImages.add(absolutePathOfImage);
}
return listOfAllImages;
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolde> {
Context context;
private ArrayList<String> imageData = new ArrayList<String>();
public MyAdapter(ArrayList<String> imageData, FragmentActivity activity) {
this.imageData = imageData;
this.context = activity;
}
#Override
public MyAdapter.MyViewHolde onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.inflate_single_image_row, parent, false);
return new MyViewHolde(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolde holder, int position) {
String data = imageData.get(position);
if (data != null){
Glide.with(context).load(data).into(holder.singleImageView);
}else {
Toast.makeText(context, "Images Empty", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
return imageData.size();
}
public class MyViewHolde extends RecyclerView.ViewHolder {
ImageView singleImageView;
public MyViewHolde(View itemView) {
super(itemView);
singleImageView = (ImageView) itemView.findViewById(R.id.singleImageView);
}
}
}
This Get list of photo galleries on Android will help you..
One thing i want to add here is you should add the gallery retrieving data inside a AsyncTask or Thread. It is not good practice to fetch gallery data in UI thread because if gallery images are huge than you may get ANR due to processing in UI tread.

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);

AsyncTask and custom CursorAdaper

I'm in some trouble with custom cursorAdapter and AsyncTask. I wanted to setup listView and adapter first and after that in asyctask to query data from database. But for a first time cursor in adapter is null and it throws an a exception. How can be handled this such on situation in my custom cursor adapter? Relocation of setAdapter to onPostExecute didn't helped also. Any suggestions will be also great.
Main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConversationsListCursorAdapter conversationsListCursorAdapter = new ConversationsListCursorAdapter(context, R.layout.conversations_list_item, null, 0);
conversationsListView = (ListView) findViewById(android.R.id.list);
conversationsListView.setAdapter(conversationsListCursorAdapter);
}
#Override
protected void onResume() {
super.onResume();
new GetConversationsTask().execute((Object[]) null);
}
#Override
protected void onStop() {
Cursor cursor = conversationsListCursorAdapter.getCursor();
if (cursor != null) {
cursor.close();
}
conversationsListCursorAdapter.changeCursor(null);
super.onStop();
}
private class GetConversationsTask extends AsyncTask<Object, Object, Cursor> {
#SuppressLint("NewApi")
#Override
protected Cursor doInBackground(Object... params) {
Uri uri = ClouContentProvider.CONVERSATIONS_CONTENT_URI;
Cursor cursor = null;
if (android.os.Build.VERSION.SDK_INT < 11) {
cursor = getContentResolver().query(uri, null, null, null, null);
} else {
CursorLoader cursorLoader = new CursorLoader(context, uri, null, null, null, null);
cursor = cursorLoader.loadInBackground();
}
return cursor;
}
#Override
protected void onPostExecute(Cursor cursor) {
conversationsListCursorAdapter.changeCursor(cursor);
cursor.close();
}
}
Cursor adapter:
public class ConversationsListCursorAdapter extends CursorAdapter {
private final Cursor mCursor;
private final Context mContext;
private final int mLayout;
private final int mSnippetIndex;
private final int mDateIndex;
private final int mMessageCount;
private final int mRead;
private final LayoutInflater mLayoutInflater;
//private static final String TAG = ConversationsListCursorAdapter.class.getSimpleName();
static class ViewHolder {
TextView tvBody;
TextView tvPerson;
TextView tvCount;
TextView tvDate;
QuickContactBadge ivPhoto;
View vRead;
}
public ConversationsListCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
super(context, cursor, flags);
this.mContext = context;
this.mLayout = layout;
this.mCursor = cursor;
this.mSnippetIndex = mCursor.getColumnIndex(ConversationsProviderMetaData.ConversationsTableMetaData.SNIPPET);
this.mDateIndex = mCursor.getColumnIndex(ConversationsProviderMetaData.ConversationsTableMetaData.DATE);
this.mMessageCount = mCursor.getColumnIndex(ConversationsProviderMetaData.ConversationsTableMetaData.MESSAGE_COUNT);
this.mRead = mCursor.getColumnIndex(ConversationsProviderMetaData.ConversationsTableMetaData.READ);
this.mLayoutInflater = LayoutInflater.from(mContext);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View rowView = mLayoutInflater.inflate(mLayout, parent, false);
ViewHolder holder = new ViewHolder();
holder.tvBody = (TextView) rowView.findViewById(R.id.body);
holder.tvPerson = (TextView) rowView.findViewById(R.id.addr);
holder.tvCount = (TextView) rowView.findViewById(R.id.count);
holder.tvDate = (TextView) rowView.findViewById(R.id.date);
holder.ivPhoto = (QuickContactBadge) rowView.findViewById(R.id.photo);
holder.vRead = (View) rowView.findViewById(R.id.read);
rowView.setTag(holder);
return rowView;
}
#Override
public void bindView(View v, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) v.getTag();
String cBody = cursor.getString(mSnippetIndex);
Integer cCount = cursor.getInt(mMessageCount);
Long cDate = cursor.getLong(mDateIndex);
Integer cRead = cursor.getInt(mRead);
holder.tvBody.setText(cBody);
if (cCount < 0) {
holder.tvCount.setText("");
} else {
holder.tvCount.setText("(" + cCount + ")");
}
if (cRead == 0) {
holder.vRead.setVisibility(View.VISIBLE);
} else {
holder.vRead.setVisibility(View.INVISIBLE);
}
holder.tvDate.setText(ClouUtils.getDate(context, cDate));
holder.tvPerson.setText(cursor.getString(mCursor.getColumnIndex(ConversationsProviderMetaData.ConversationsTableMetaData.CANONICAL)));
holder.ivPhoto.setImageResource(R.drawable.ic_contact_picture);
holder.ivPhoto.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Cursor cursor) {
// First check if it's null
if(cursor !=null){
// use swap to get the old cursor and close it
Cursor oldC = conversationsListCursorAdapter.swapCursor(cursor);
if(oldC != null){
oldC.close();
}
// DO NOT CLOSE THE NEW CURSOR
// this one you must close whenever the list goes onPause(); but not before
}
}

Categories

Resources