Actually I tried with this coding it's working fine.i.e., showing all the images perfectly in emulator but coming to mobile it showing repeatedly the same image. I have attached the adapter class also
File file[] = Environment.getExternalStorageDirectory().listFiles();
String strFile = "";
for (int i = 0; i < file.length; i++) {
strFile += file[i].getAbsolutePath() + " :: ";
System.out.println("\n");
}
Log.i("test", strFile);
String[] img = { MediaStore.Images.Thumbnails._ID };
imagecursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,
null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
image_column_index = imagecursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
count = imagecursor.getCount();
imagegrid = (ListView) findViewById(R.id.PhoneImageGrid);
imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
null, null, null);
actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor
.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(),
ViewImage.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
Adapter Class:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
i.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ id));
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
i.setLayoutParams(new GridView.LayoutParams(92, 92));
} else {
i = (ImageView) convertView;
}
return i;
Related
I have implemented gridview in recyclerview to display image and videos with thumbnails.
I have used following code to fetch images in onBindView method
Getting images thumbnails using below code:
bitmap = MediaStore.Images.Thumbnails.getThumbnail(context
.getApplicationContext().getContentResolver(), item.getImgId(),
MediaStore.Images.Thumbnails.MICRO_KIND, null);
Getting video thumbnails using below code:
bitmap = MediaStore.Video.Thumbnails.getThumbnail(context
.getApplicationContext().getContentResolver(), item.getImgId(),
MediaStore.Images.Thumbnails.MICRO_KIND, null);
but every time i scroll view sticks(it takes some time to scroll down or up). i think it is because i am loading thumbnails in onBindView method.
help me improve this code so that it can be scrolled smoothly.
or any API to do it easily.
Put below code into the onCreate:
imageAdapter = new ImageAdapter();
imageAdapter.initialize();
and here is the Adapter for fetching images and video from the local storage check it out:
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList<ImageItem> images = new ArrayList<ImageItem>();
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void initialize() {
images.clear();
final String[] columns = {MediaStore.Images.Thumbnails._ID};
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name, column_id, thum;
String absolutePathOfImage = null;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID, MediaStore.Video.Thumbnails.DATA};
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()) {
int id = cursor.getColumnIndex(MediaStore.Video.Media._ID);
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
Log.e("column_id", cursor.getString(column_id));
Log.e("thum", cursor.getString(thum));
ImageItem obj_model = new ImageItem();
obj_model.id = id;
obj_model.thumb = cursor.getString(thum);
images.add(obj_model);
}
if (imagecursor != null) {
int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
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.id = id;
lastId = id;
imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
images.add(imageItem);
}
imagecursor.close();
}
notifyDataSetChanged();
}
public void checkForNewImages() {
//Here we'll only check for newer images
final String[] columns = {MediaStore.Images.Thumbnails._ID};
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
MediaStore.Images.Media._ID + " > " + lastId, null, orderBy);
int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
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.id = id;
lastId = id;
imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
imageItem.selection = true; //newly added item will be selected by default
images.add(imageItem);
}
imagecursor.close();
notifyDataSetChanged();
}
public int getCount() {
return images.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem1, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
holder.ivVideoIcon = (ImageView) convertView
.findViewById(R.id.ivVideoIcon);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.itemCheckBox);
holder.pbImageLoad = (ProgressBar) convertView
.findViewById(R.id.pbImageLoad);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ImageItem item = images.get(position);
holder.checkbox.setId(position);
holder.imageview.setId(position);
if (item.thumb != null) {
/*Picasso.with(AndroidCustomGalleryActivity.this)
.load("file" + item.thumb)
.into(holder.imageview);*/
holder.ivVideoIcon.setVisibility(View.VISIBLE);
Glide.with(AndroidCustomGalleryActivity.this).load(Uri.fromFile(new File(item.thumb)))
.listener(new RequestListener<Uri, GlideDrawable>() {
#Override
public boolean onException(Exception e, Uri model, Target<GlideDrawable> target, boolean isFirstResource) {
holder.pbImageLoad.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, Uri model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
holder.pbImageLoad.setVisibility(View.GONE);
return false;
}
})
.skipMemoryCache(false)
.into(holder.imageview);
} else {
// holder.imageview.setImageBitmap(item.img);
if (item.img != null) {
holder.ivVideoIcon.setVisibility(View.GONE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
item.img.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(AndroidCustomGalleryActivity.this).load(stream.toByteArray()).asBitmap().listener(new RequestListener<byte[], Bitmap>() {
#Override
public boolean onException(Exception e, byte[] model, Target<Bitmap> target, boolean isFirstResource) {
holder.pbImageLoad.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Bitmap resource, byte[] model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
holder.pbImageLoad.setVisibility(View.GONE);
return false;
}
}).skipMemoryCache(false).into(holder.imageview);
}
}
holder.checkbox.setChecked(item.selection);
return convertView;
}
}
class ViewHolder {
ImageView imageview;
ImageView ivVideoIcon;
CheckBox checkbox;
ProgressBar pbImageLoad;
}
class ImageItem {
boolean selection;
int id;
Bitmap img;
String thumb;
}
I am trying to display video files in listview from folder 'xyz' on sdcard, i have successfully displayed but problem is that it displays all video files stored on sdcard even out of folder 'abc' actually i want only video files stored in folder 'xyz' to be displayed. I am googling since 4 days but didn't find any solution for that. My code is that is showing all videos and working perfectly :
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
String[] thumbColumns = null ;
File videoFiles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init_phone_video_grid();
#SuppressWarnings("deprecation")
private void init_phone_video_grid() {
System.gc();
String[] proj = { 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,proj,
null, null,null);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.list);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
System.gc();
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
String filename = videocursor.getString(video_column_index);
Intent intent = new Intent(MainActivity.this, ViewVideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
}
};
public class VideoAdapter extends BaseAdapter {
private Context vContext;
public VideoAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
ViewHolder holder;
String id = null;
convertView = null;
if (convertView == null) {
convertView = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtSize = (TextView) convertView.findViewById(R.id.txtSize);
holder.thumbImage = (ImageView) convertView.findViewById(R.id.imgIcon);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
id = videocursor.getString(video_column_index);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
// id += " Size(KB):" + // videocursor.getString(video_column_index);
holder.txtTitle.setText(id);
holder.txtSize.setText(" Size(KB):" + videocursor.getString(video_column_index));
String[] proj = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj,
MediaStore.Video.Media.DISPLAY_NAME + "=?",
new String[] { id }, null);
cursor.moveToFirst();
long ids = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
options);
holder.thumbImage.setImageBitmap(curThumb);
curThumb = null;
}
return convertView;
}
}
static class ViewHolder {
TextView txtTitle;
TextView txtSize;
ImageView thumbImage;
}
Try this
public static final String[] VIDEO_PROJECTION = {MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DATA};
public static final Uri VIDEO_SOURCE_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Querying the data using the content resolver
CursorLoader cursorLoader = new CursorLoader(getActivity(), VIDEO_SOURCE_URI, VIDEO_PROJECTION, MediaStore.Video.Media.DATA + " like ? ", new String[]{"%FOLDER_NAME%"},
MediaStore.Video.Media.DATA + " COLLATE NOCASE ASC;");
It retrievers all the video files from the FOLDER_NAME. Since there can be one or more folders with a name so it is better to provide absolute path.
I am displaying all images from the device storage.
The problem is that when I scroll up it's not smooth (lags in between).
I am using etsy/AndroidStaggeredGrid and using the code below:
public class GalleryFragment extends Fragment {
StaggeredGridView gridview;
ArrayList<Gallery> galleries;
CameraGalleryAdapter gallerylist;
String[] arrPath;
String[] videoPath;
int count,count2,count3,count4;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
galleries=new ArrayList<Gallery>();
((ActionBarActivity) getActivity()).getSupportActionBar().show();
gridview = (StaggeredGridView)rootView.findViewById(R.id.gridcamera);
progressBar=(ProgressBar)rootView.findViewById(R.id.progressBar);
gallerylist=new CameraGalleryAdapter(getActivity().getApplicationContext(),R.layout.gallery_grid,galleries);
gridview.setAdapter(gallerylist);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Fragment currentFragment = new PreviewFragment();
Bundle args = new Bundle();
// CameraActivity.isGalleryFrgament=false;
if (galleries.get(i).getIsImage()) {
args.putString("imagepath", galleries.get(i).getImageUrl());
args.putString("isVideo", "gallery");
} else {
args.putString("isVideo", "videogallery");
args.putString("fileUri", galleries.get(i).getVideoUrl());
}
currentFragment.setArguments(args);
FragmentManager frgManager;
frgManager = getActivity().getSupportFragmentManager();
frgManager.beginTransaction().replace(R.id.camera_container, currentFragment).addToBackStack("tag").commit();
}
});
getImages();
return rootView;
}
private void getImages()
{
((CameraActivity)getActivity()).setOnBackPressedListener(new BaseBackPressedListener(getActivity(),true));
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID,MediaStore.Video.Media.DATA,
};
final String orderBy = MediaStore.Images.Media._ID;
Cursor cursor = getActivity().getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
count = cursor.getCount();
Cursor cursor2 = getActivity().getContentResolver().query(
MediaStore.Images.Media.INTERNAL_CONTENT_URI, columns, null,
null, orderBy);
count2 = cursor2.getCount();
Cursor cursor3 = getActivity().getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
count3 = cursor3.getCount();
Cursor cursor4 = getActivity().getContentResolver().query(
MediaStore.Video.Media.INTERNAL_CONTENT_URI, columns, null,
null, orderBy);
count4 = cursor4.getCount();
arrPath = new String[count+count2+ count3+count4];
videoPath= new String[count+count2+ count3+count4];
for (int i = 0; i < count; i++)
{
cursor.moveToPosition(i);
int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
Gallery ga=new Gallery();
ga.setImageUrl(cursor.getString(dataColumnIndex));
ga.setIsImage(true);
galleries.add(ga);
}
for (int i = 0; i < count2; i++)
{
cursor2.moveToPosition(i);
int dataColumnIndex = cursor2.getColumnIndex(MediaStore.Images.Media.DATA);
Gallery ga=new Gallery();;
ga.setImageUrl(cursor2.getString(dataColumnIndex));
ga.setIsImage(true);
galleries.add(ga);
}
for (int i = 0; i < count3; i++)
{
cursor3.moveToPosition(i);
int dataColumnIndex = cursor3.getColumnIndex(MediaStore.Video.Media.DATA);
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(cursor3.getString(dataColumnIndex),
MediaStore.Images.Thumbnails.MINI_KIND);
Gallery ga=new Gallery();
ga.setVideoThumbnail(thumb);
ga.setVideoUrl(cursor3.getString(dataColumnIndex));
ga.setIsImage(false);
galleries.add(ga);
}
for (int i = 0; i < count4; i++)
{
cursor4.moveToPosition(i);
int dataColumnIndex = cursor4.getColumnIndex(MediaStore.Video.Media.DATA);
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(cursor4.getString(dataColumnIndex),MediaStore.Images.Thumbnails.MINI_KIND);
Gallery ga = new Gallery();
ga.setVideoThumbnail(thumb);
ga.setVideoUrl(cursor4.getString(dataColumnIndex));
ga.setIsImage(false);
galleries.add(ga);
}
}
}
How can i improve scrolling up speed and make it smooth?
hi guys i am making an android application IN which i have to display all the video contents of the sd card (album wise).....it means when WE WILL LOAD THE APPLICATION only the names of albums should be displayED.... AND when we click on the particular album ITS VIDEOS FILES SHOULD BE DISPLAYED................... i have been able to display the album names BUT THE PROBLEM IS THAT there is duplicate album names (i.e. IF TWO VIDEO files are of same album) then two different albums are being displaying...........so i want all the videos of same album should be in one "album name"........... and on the click of that album name "all its video contents should be displayed"
any help will be appreciated below is the main class (AlbumVideo.class)
public class AlbumVideo extends Activity {
private Cursor audiocursor;
private int audio_column_index;
ListView audiolist;
int count;
int album=1;
int dura;
int i1 =R.drawable.ic_launcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagexml1);
init_phone_videos_grid();
}
#SuppressWarnings("deprecation")
private void init_phone_videos_grid() {
System.gc();
final String[] projection = new String[] {
MediaStore.Video.VideoColumns.ALBUM };
final String sortOrder = VideoColumns.ALBUM + " COLLATE LOCALIZED ASC";
audiocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, null, null, sortOrder);
count = audiocursor.getCount();
audiolist = (ListView) findViewById(R.id.PhoneVideo);
audiolist.setAdapter(new AudioAdapter(getApplicationContext()));
audiolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
#SuppressWarnings("rawtypes")
public void onItemClick(AdapterView parent, View v, int position,
long id) {
System.gc();
audio_column_index = audiocursor
.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.ALBUM);
audiocursor.moveToPosition(position);
String filename = audiocursor.getString(audio_column_index);
Intent intent = new Intent(AlbumVideo.this,
AlbumVideoDetail.class);
intent.putExtra("albumfilename",filename);
intent.putExtra("album",album);
startActivity(intent);
}
};
public class AudioAdapter extends BaseAdapter
{
private Context vContext;
CheckBox cb;
int position=0;
int check=0;
String a[]=new String[count];
public AudioAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.list_item1, parent, false);
final Button title = (Button) row.findViewById(R.id.button);
title.setTextColor(Color.parseColor("#000000"));
if (convertView == null) {
audio_column_index =audiocursor.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.ALBUM );
audiocursor.moveToPosition(position);
String TITLE = audiocursor.getString(audio_column_index);
String a[]=new String[count];
Toast.makeText(AlbumVideo.this, "music will be available shortly"+TITLE, Toast.LENGTH_LONG).show();
title.setText(TITLE);
}
return (row);
}
}
}
and the second class to display the songs of the particular album is ("AlbumVideoDetail.class")
public class AlbumVideoDetail extends Activity {
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
String title=null;
String desc=null;
int dura;
int i1 =R.drawable.ic_launcher;
String filename;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagexml);
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("albumfilename");
// String filename1 = filename.substring(filename.indexOf("sdcard"),filename.length());
// String filename2= filename1.substring(7);
Toast.makeText(AlbumVideoDetail.this, "music will be available shortly"+filename, Toast.LENGTH_LONG).show();
init_phone_videos_grid();
}
#SuppressWarnings("deprecation")
private void init_phone_videos_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media.DATA,
MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.SIZE,};
String where = android.provider.MediaStore.Video.Media.ALBUM + "=?";
String whereVal[] = { filename };
String orderBy = android.provider.MediaStore.Video.Media.TITLE;
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, where, whereVal, orderBy);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
}
public class VideoAdapter extends BaseAdapter {
private Context vContext;
CheckBox cb;
int position=0;
int check=0;
public VideoAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.list_item2, parent, false);
final TextView title = (TextView) row.findViewById(R.id.title);
TextView desc = (TextView) row.findViewById(R.id.desc);
TextView dura = (TextView) row.findViewById(R.id.duration);
title.setTextColor(Color.parseColor("#000000"));
desc.setTextColor(Color.parseColor("#000000"));
dura.setTextColor(Color.parseColor("#000000"));
if (convertView == null) {
video_column_index =videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
final String TITLE = videocursor.getString(video_column_index);
title.setText(TITLE);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
String DESC= videocursor.getString(video_column_index);
int desd=Integer.parseInt(DESC);
int kb = (int) ((desd / 1000) % 1000);
int mb = (int) ((desd / 1000) / 1000);
String KB=Integer.toString(kb);
String MB=Integer.toString(mb);
String DESC1 = MB + "." + KB +"mb";
desc.setText(DESC1);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
videocursor.moveToPosition(position);
String DURA= videocursor.getString(video_column_index);
int duro = Integer.parseInt(DURA);
int seconds = (int) ((duro / 1000) % 60);
int minutes = (int) ((duro / 1000) / 60);
String secs=Integer.toString(seconds);
String mins=Integer.toString(minutes);
String DURA1 = mins + ":" + secs;
dura.setText(DURA1);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
final String filename = videocursor.getString(video_column_index);
} return (row);
}
}
}
wow after so much time spent on the internet at last found the solution for it !!!!!!! it an easy n very short step .,][.....i hope it will be helpful to someone ..........
private void init_phone_videos_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media.DATA,
MediaStore.Video.Media._ID, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.MIME_TYPE,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.SIZE,};
String where = android.provider.MediaStore.Video.Media.ALBUM + "=?";
String whereVal[] = { filename };
String orderBy = android.provider.MediaStore.Video.Media.TITLE;
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "DISTINCT "
+proj, where, whereVal, orderBy);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
}
just to add the word "distinct" in the class "album detail"....n it will sort d query according to yourt requirement....
Change the following:
final String[] projection = new String[] {MediaStore.Video.VideoColumns.ALBUM };
into
final String[] projection = new String[]{ "DISTINCT " +MediaStore.Video.VideoColumns.ALBUM};
I'm trying to create a custom gallery that allows users to pick from all the photos and videos contained on their Android device. I know how to create a gallery of just photos and just videos, but if I want to combine both, how can I do this?
I think the issue comes down to how I create my cursor. To select all videos, I created the cursor this way:
String[] videoParams = {MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DATE_TAKEN,
MediaStore.Video.Thumbnails.DATA};
videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoParams, null, null, null);
If I want to query all the media files, not just video, what do I do?
This is what I tried, based off of: Custom Gallery with Images and Videos in android to select multiple items
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};
mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
This gives me the error java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range. The statement has 1 parameters at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
Perhaps my approach is completely wrong, but I can't find any examples of custom android galleries using both images and videos, which is bizarre to me as this seems like it would be a common thing to create.
Here's all of my code, in case it's helpful:
public class GridViewCompatActivity extends Activity {
GridViewCompat gridView;
private static final String TAG = "GridViewCompatActivity";
Cursor videocursor;
Cursor mediaCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view_compat);
gridView = (GridViewCompat) findViewById(R.id.gridView1);
// NOTE: We are using setChoiceMode, as I said, its a drop-in replacement
gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
gridView.setAdapter(new ImageAdapter(getApplicationContext()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> view, View arg1, int pos, long id) {
// We need to invalidate all views on 4.x versions
GridViewCompat gridView = (GridViewCompat) view;
gridView.invalidateViews();
}
});
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checkArray;
checkArray = gridView.getCheckedItemPositions();
String selectedPos = "Selected positions: ";
int count = checkArray.size();
for (int i = 0; i < count; i++) {
if (checkArray.valueAt(i))
selectedPos += checkArray.keyAt(i) + ",";
}
Intent intent = new Intent();
intent.putExtra("result", selectedPos);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
Log.d(TAG, "number of media: " + Integer.toString(MediaStore.Files.FileColumns.DATA.length()));
int mediaParams = MediaStore.MediaColumns.DATA.length();
return mediaParams;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new grid view item for each item referenced by the Adapter
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
CheckBox checkBox;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(R.layout.grid_view_item, parent, false);
}
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
GridViewCompat gvc = (GridViewCompat) parent;
if (gvc.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE) {
SparseBooleanArray checkArray;
checkArray = gvc.getCheckedItemPositions();
checkBox.setChecked(false);
if (checkArray != null) {
if (checkArray.get(position)) {
checkBox.setChecked(true);
}
}
}
// imageView.setImageResource(mThumbIds[position]);
Bitmap bmThumbnail;
Log.d(TAG, "position: " + position);
mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
Log.d(TAG, Integer.toString(mediaCursor.getCount()));
for (int i = 0; i < mediaCursor.getCount(); i++){
mediaCursor.moveToPosition(i);
Boolean isVideo = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA)).length() > 0;
Log.d(TAG, "isVideo: " + isVideo);
String mediaPath = "";
if(isVideo){
mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
video_paths.add(mediaPath);
}else{
mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Images.Media.DATA));
video_paths.add(mediaPath);
}
Log.d(TAG, "mediaPath: " +mediaPath);
}
mediaCursor.moveToPosition(position);
String video_path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.d(TAG, "video_path: " + video_path);
imageView.setImageBitmap(ThumbnailUtils.createVideoThumbnail(video_path, Thumbnails.MICRO_KIND));
return convertView;
}
ArrayList<String> video_paths = new ArrayList<String>();
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};
// String[] videoParams = {MediaStore.Video.Media._ID,
// MediaStore.Video.Media.DATA,
// MediaStore.Video.Media.DATE_TAKEN,
// MediaStore.Video.Thumbnails.DATA};
// }
}
}
public class GalleryFragment extends Fragment
{
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private int[] typeMedia;
private ImageAdapter imageAdapter;
#SuppressLint("NewApi") #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gallery_gridview, container, false);
String[] columns = { MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE,
};
String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
final String orderBy = MediaStore.Files.FileColumns.DATE_ADDED;
Uri queryUri = MediaStore.Files.getContentUri("external");
#SuppressWarnings("deprecation")
Cursor imagecursor = getActivity().managedQuery(queryUri,
columns,
selection,
null, // Selection args (none).
MediaStore.Files.FileColumns.DATE_ADDED + " DESC" // Sort order.
);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Files.FileColumns._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
this.arrPath = new String[this.count];
this.typeMedia = new int[this.count];
this.thumbnailsselection = new boolean[this.count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true;
int type = imagecursor.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE);
int t = imagecursor.getInt(type);
if(t == 1)
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
getActivity().getContentResolver(), id,
MediaStore.Images.Thumbnails.MINI_KIND, bmOptions);
else if(t == 3)
thumbnails[i] = MediaStore.Video.Thumbnails.getThumbnail(
getActivity().getContentResolver(), id,
MediaStore.Video.Thumbnails.MINI_KIND, bmOptions);
arrPath[i]= imagecursor.getString(dataColumnIndex);
typeMedia[i] = imagecursor.getInt(type);
}
GridView imagegrid = (GridView) v.findViewById(R.id.PhoneImageGrid);
Button reSizeGallery = (Button) v.findViewById(R.id.reSizeGallery);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
imagecursor.close();
reSizeGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ChatViewerAdapter.ScreenResize(getActivity());
}
});
return v;//super.onCreateView(inflater, container, savedInstanceState);
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#SuppressLint("NewApi") public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.gallery_view, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.videoICON = (ImageView) convertView.findViewById(R.id.videoICON);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageview.getLayoutParams().height = height/6;
holder.imageview.getLayoutParams().width = width/4;
holder.imageview.setId(position);
if(typeMedia[position] == 1)
holder.videoICON.setVisibility(View.GONE);
else if(typeMedia[position] == 3)
holder.videoICON.setVisibility(View.VISIBLE);
holder.imageview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int id = v.getId();
Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int height = display.getHeight();
final int height_half = (int) (height/2.5);
RelativeLayout fragment_layout = (RelativeLayout) getActivity().findViewById(R.id.fragment_gallery);
fragment_layout.setVisibility(View.VISIBLE);
fragment_layout.getLayoutParams().height = height_half;
GalleryImageChooseFragment f_img_choose =new GalleryImageChooseFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Bundle args = new Bundle();
args.putString("PATH", arrPath[id]);
f_img_choose.setArguments(args);
ft.show(f_img_choose);
ft.replace(R.id.fragment_tattle, f_img_choose);
ft.addToBackStack("f_img_choose");
ft.commit();
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.id = position;
return convertView;
}
}
class ViewHolder {
ImageView imageview;
ImageView videoICON;
int id;
}
}
Download source code form here (Get all videos from gallery android).
public void fn_video() {
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name,column_id,thum;
String absolutePathOfImage = null;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
Log.e("column_id", cursor.getString(column_id));
Log.e("thum", cursor.getString(thum));
Model_Video obj_model = new Model_Video();
obj_model.setBoolean_selected(false);
obj_model.setStr_path(absolutePathOfImage);
obj_model.setStr_thumb(cursor.getString(thum));
al_video.add(obj_model);
}
}
This function will return arraylist of gallery images and videos in descending order. Just pass this function to adapter and show gallery stuff in recyclerview in kotlin.
#SuppressLint("Range")
fun getAllGalleryMedia(): ArrayList<Media> {
val result = ArrayList<Media>()
val projection = arrayOf(
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.MEDIA_TYPE,
MediaStore.Files.FileColumns.MIME_TYPE,
MediaStore.Files.FileColumns.TITLE
)
val selection = (MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
+ " OR "
+ MediaStore.Files.FileColumns.MEDIA_TYPE + "="
+ MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)
val queryUri = MediaStore.Files.getContentUri("external")
Handler(Looper.getMainLooper()).post {
val cursorLoader = CursorLoader(
context,
queryUri,
projection,
selection,
null,
MediaStore.Files.FileColumns.DATE_ADDED + " DESC"
)
val cursor: Cursor? = cursorLoader.loadInBackground()
if (cursor != null) {
while (cursor.moveToNext()) {
val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID))
val displayName =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME))
val imagePath =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA))
val dateAdded =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_ADDED))
val mimeType =
cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE))
result.add(Media(id, displayName, imagePath, dateAdded, mimeType))
}
cursor.close()
}
}
return result
}
This is model class,you can modify according to your needs.
class Media:java.io.Serializable{
var id:Long=0
var displayName:String=""
var imagePath:String=""
var dateAdded:String=""
var mimeType:String=""
var isSelected:Boolean = false
constructor(){
// empty constructor
}
constructor(
id: Long,
displayName: String,
imagePath: String,
dateAdded: String,
mimeType: String
){
this.id = id
this.displayName = displayName
this.imagePath = imagePath
this.dateAdded = dateAdded
this.mimeType = mimeType
}}