I have a gridview in one screen and in gridview i am displaying all the images which is present in SDCard this is working fine. Now what i want to do is when i click on any of gridview images it should go to next activity and should display that particular image in full screen. I have referred some other link and tried but not getting proper solution.
public class Gallary_Images extends Activity {
private Cursor cursor;
private int columnIndex;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_images);
// Set up an array of the Thumbnail Image ID column we want
String[] projection = { MediaStore.Images.Thumbnails._ID };
// Create the cursor pointing to the SDCard
cursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection,
null, // Return all rows
null, MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView sdcardImages = (GridView) findViewById(R.id.gridView1);
sdcardImages.setAdapter(new ImageAdapter(this));
// Set up a click listener
sdcardImages.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
Intent i = new Intent(getApplicationContext(),
ViewGallery_Photo.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
private class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount() {
return cursor.getCount();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView
.setLayoutParams(new GridView.LayoutParams(100, 100));
} else {
picturesView = (ImageView) convertView;
}
return picturesView;
}
}
}
This is my gridview class where i am calling next activity. Now i don't know how should i get the images in next activity. Please help...
First thing that you must try is a put an URi of image in your intent like this
intent.putExtra("imageUri", imageUri.toString());
where imageUri is Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""+ imageID));
but before this you must know your imageID, so the whole code must be like this
sdcardImages.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id) {
Intent i = new Intent(getApplicationContext(),ViewGallery_Photo.class);
cursor.moveToPosition(position);
int imageID = cursor.getInt(columnIndex);
Uri imageUri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
""+ imageID));
intent.putExtra("imageUri", imageUri.toString());
startActivity(i);
}
});
Try out as below:
Add data filed in your projection string.
String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
public void onItemClick(AdapterView<?> arg0, android.view.View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(),ViewGallery_Photo.class);
cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, null);
final int dataColumnIndex = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
final int idColumIndex = actualimagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
cursor.moveToPosition(position);
filename = cursor.getString(dataColumnIndex);
i.putExtra("imagePath", filename );
startActivity(i);
Related
I'm listing video from device memory with a BaseAdapter and I've noticed that scrolling is not very performing, very slow.
Should I use a different method to do this work or is there a way to improve this one ?
public class StoredVideo extends Activity {
public final static String EXTRA_MESSAGE = "it.mypackage.com";
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
MediaStore.Video.Thumbnails.VIDEO_ID };
private String thumbPath;
SharedPreferences pref;
String account;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videomain);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
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 };
String orderBy = android.provider.MediaStore.Video.Media.DATE_TAKEN;
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, orderBy + " DESC");
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
videolist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
return onLongListItemClick(v, pos, id);
}
protected boolean onLongListItemClick(View v, final int pos, long id) {
final String str= videolist.getItemAtPosition(pos).toString();
Log.i("ListView", "onLongListItemClick stirng=" + str);
AlertDialog.Builder builder = new
AlertDialog.Builder(StoredVideo.this);
builder.setMessage("Are you sure you want to delete this video ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(videocursor.moveToFirst()) {
videocursor.moveToPosition(pos);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
String filename = videocursor.getString(video_column_index);
removeMedia(filename);
videocursor.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
init_phone_video_grid();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
}
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);
Log.d("TAGME", filename);
String videoinfo[] = new String[2];
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.Thumbnails.DATA));
Log.d("ThumbPath: ",thumbPath);
}
videoinfo[0] = filename;
videoinfo[1] = thumbPath;
Intent intent = new Intent(StoredVideo.this, ViewVideo.class);
intent.putExtra(EXTRA_MESSAGE, videoinfo);
StoredVideo.this.startActivity(intent);
}
};
public void removeMedia(String filename) {
File existingFile = new File("\"" + filename + "\"");
existingFile.delete();
Toast.makeText(StoredVideo.this, "File " + filename + " deleted", Toast.LENGTH_LONG).show();
ContentResolver resolver = StoredVideo.this.getContentResolver();
resolver.delete(Video.Media.EXTERNAL_CONTENT_URI, Video.Media.DATA + "=?", new String[]{filename});
}
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 void deleteItem(int 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.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);
holder.txtTitle.setText(id);
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);
if(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;
}
}
ListView Adapter's getView() method will be called numerous times as you scroll the List. So you should not perform any operation that takes more time or more memory. Otherwise bear with slow performance or crash.
Let's see how you can optimize:
Avoid operations that takes more time or memory
Do not call managedQuery() from your getView which will affect the performance badly. And you are creating thumbnails there. I wouldn't do that if I need more responsive ListView. If you need them so badly, go for AsyncTask.
Reuse the View
The adapters, by default, recycles the views during getView calls to avoid unnecessary object creation. Yikes! Go for it. It's just simple.
View v = convertView;
if(v == null) {
//inflate view
}
// do the rest
Include ViewHolder Patter
The ViewHolder pattern brings the smoothness into the ListView. If you want sleek scroll, read
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
http://www.vogella.com/tutorials/AndroidListView/article.html
PS: The System.gc() call is not the best option to free up memory. Let's see what he Android Doc says,
System.gc() indicates to the VM that it would be a good time to run the garbage collector. Note that this is a hint only. There is no guarantee that the garbage collector will actually be run.
you should not assign every time null to the convertView
convertView = null;
if (convertView == null) {
remove convertView = null. Get rid also of System.gc();
I know that here are many answers how to delete items, but I can't make it work. It show errors. Can you look? I added in adapter remove(position), but I think it works wrongly.
So I want after using onItemLongClickListener to delete file and its thumbnail too.
Main:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView grid = (GridView) findViewById(R.id.gridview);
final ThumbnailAdapter thumbnails = new ThumbnailAdapter(this);
grid.setAdapter(thumbnails);
grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int position,
long id) {
final String imgPath = thumbnails.getImagePath(position);
File file = new File(imgPath);
file.delete();
thumbnails.remove(position);
thumbnails.notifyDataSetChanged();
grid.invalidateViews();
grid.setAdapter(thumbnails);
return true;
}
});
Adapter:
public class ThumbnailAdapter extends BaseAdapter {
// Context required for performing queries
private final Context mContext;
// Cursor for thumbnails
private final Cursor cursor;
private final int imgId;
private final int imgData;
private final int count;
public ThumbnailAdapter(Context c) {
this.mContext = c;
// Get list of all images, sorted by last taken first
final String[] projection = {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA
};
cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
MediaStore.Images.Media.DATE_TAKEN + " DESC"
);
imgId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
imgData = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
count = cursor.getCount();
Log.d("ThumbnailAdapter", count + " images found");
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
cursor.moveToPosition(position);
final Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(
mContext.getContentResolver(),
cursor.getInt(imgId),
MediaStore.Images.Thumbnails.MICRO_KIND,
null
);
imageView.setImageBitmap(thumbnail);
Log.d("ThumbnailAdapter", "render: " + cursor.getString(imgData));
return imageView;
}
public String getImagePath(int position) {
cursor.moveToPosition(position);
return cursor.getString(imgData);
}
public void remove(int position) {
remove(position);
notifyDataSetChanged();
}
}
I guess its stack overflow. your remove method in the adapter is recursive forever.
Instead of deleting file youself ask content resolver to remove it. and the reload data.
you dont have to call grid.setAdapter(thumbnails) again in the click listner
Check this line please though :
file.delete();
thumbnails.remove(position);
You are deleting your file first and then removing it from adapter. It should be other way around. You reset your adapter then delete the actual file. Your thumbnail is deleted while still being attached to the adapter.
I want to fetch all images in my application from android photo gallery .because I want to load an image into my application again after saving it into android gallery .
For Saving my image into gallery I use below method.
MediaStore.Images.Media.insertImage(ContentResolverObj, bitMap, "uniqueTitle", "description");
Now programatically I want to fetch all images into my application and want to get above saved image on the basis of tile.Two questions here.
1st:Can I fetch all images from photo gallery of android ?
2nd:can I read single photo detail like title etc after fetching it.
by using this code i am able to display phone gallery images in gridview, depending on your requirement change this..
public class MyPhoneGallery extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor;
private int image_column_index, actual_image_column_index;
GridView imagegrid;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
init_phone_image_grid();
}
private void init_phone_image_grid() {
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 = (GridView) 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);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int mygetItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
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(125, 125));
}
else {
i = (ImageView) convertView;
}
return i;
}
}
}
I used this code and got image, maybe it works for you
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
imagecursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
ids[i] = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
You can find adapter code gridview and setadapter from below URL
source code for adapter and gridview
Here is my image gallery code. So far, for testing purpose I directly used some manually stored images,
public class Photo_Gallery extends Activity
{
//---the images to display---
Integer[] imageIDs = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displayview);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
//---display the images selected---
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount() {
return imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(75, 60));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
And here is the code I used to capture images.
case R.id.takeSnapBtn:
try {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, imageData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Following is the onActivityResult(),
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
imageView.setImageBitmap(bmp);
}
}
I would be glad if some one provide me an example of how to dynamically update the gallery with images taken from the camera.
Store the images captured from app and read those images from sd card to gallery..
File sdDir = new File("/sdcard/Pictures/YOUR_DIR");
sdDirFiles = sdDir.listFiles();
for (i = 0; i < sdDirFiles.length; i++) {
//ADD to gallery HERE..
}
If u get all images under the sdcard of perticular Bucket(folder) then use this code...
public class SubGalleryView extends Activity {
private ArrayList<Integer> ImageIds = new ArrayList<Integer>();
private GridView subGalleryView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub_gallery_view);
//Provide Bucket_Name/Folder_Name Using Bundle.
Bundle bundle = getIntent().getExtras();
Toast.makeText(this, bundle.getString("Bucket_Name"),
Toast.LENGTH_SHORT).show();
//Using Projection We get all images of all folder.
String[] projection = new String[] { MediaStore.Images.Media._ID,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME };
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
null, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
//using this do{}while(); we get all image_id under perticular bucket. and strored in ArrayList of ImagesIds.
do {
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME);
if (cursor.getString(columnIndex).equalsIgnoreCase(
bundle.getString("Bucket_Name"))) {
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int imageID = cursor.getInt(columnIndex);
ImageIds.add(imageID);
} else if (bundle.getString("Bucket_Name").equalsIgnoreCase(
"All Pictures")) {
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int imageID = cursor.getInt(columnIndex);
ImageIds.add(imageID);
}
} while (cursor.moveToNext());
}
//Pass ImageIds arrayList to Adapter.
subGalleryAdapter imageAdapter = new subGalleryAdapter(
SubGalleryView.this, R.layout.sub_gallery_view_item, ImageIds);
subGalleryView = (GridView) findViewById(R.id.subGallery);
subGalleryView.setAdapter(imageAdapter);
}
public class subGalleryAdapter extends ArrayAdapter<Integer> {
private Context contex;
private int resourceId;
private LayoutInflater layoutInflater = null;
private ArrayList<Integer> mlist;
public subGalleryAdapter(Activity context, int resourceId,
ArrayList<Integer> list) {
super(context, resourceId, list);
this.mlist = list;
this.contex = context;
this.resourceId = resourceId;
this.layoutInflater = context.getLayoutInflater();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView viewHolder;
if (convertView == null) {
viewHolder = new ImageView(contex);
convertView = layoutInflater.inflate(resourceId, parent, false);
viewHolder = (ImageView) convertView
.findViewById(R.id.imageView1);
} else {
viewHolder = (ImageView) convertView
.findViewById(R.id.imageView1);
}
viewHolder.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"" + mlist.get(position)));
return convertView;
}
}
}
Using this code u get all images from perticular folder passing bucket display name in bundle. and if u get all images of all bucket(folder) form sdcard then use this code
public class SubGalleryViewy extends Activity {
private Cursor cursor;
private int columnIndex;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sdcard);
// Set up an array of the Thumbnail Image ID column we want
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView sdcardImages = (GridView) findViewById(R.id.sdcard);
sdcardImages.setAdapter(new ImageAdapter(this));
// Set up a click listener
sdcardImages.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Get the data location of the image
String[] projection = {MediaStore.Images.Media.DATA};
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
// Get image filename
String imagePath = cursor.getString(columnIndex);
// Use this path to do further processing, i.e. full screen display
}
});
}
/**
* Adapter for our image files.
*/
private class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount() {
return cursor.getCount();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
}
public class VideoDemo extends Activity {
private VideoView video;
private MediaController ctlr;
File clip=new File(Environment.getExternalStorageDirectory();
{
if (clip.exists()) {
video=(VideoView)findViewById(R.id.videoGrdView);
video.setVideoPath(clip.getAbsolutePath());
ctlr=new MediaController(this);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
}
}};
}
}
So i've got a VideoGrdView of all videos on my sd card to display in a separate activity, now i need to know how to click a video from the grid and have it play through this media player. Any help is appreciated.
public class Menus extends Activity {
//set constants for MediaStore to query, and show videos
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private GridView _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
protected Context _context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_context = getApplicationContext();
_gallery = (GridView) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
//initialize the videos uri
//showToast(_contentUri.getPath());
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(_itemClickLis);
}
private AdapterView.OnItemClickListener _itemClickLis = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
// We want to get the column index for the data uri
int count = _cursor.getCount();
//
_cursor.moveToFirst();
//
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
startActivity(new Intent("com.ave"));
}
};
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
}
}
//
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);;
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setLayoutParams(new GridView.LayoutParams(96, 96));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(),
id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
return thumb;
}
}
}
Gallery, pretty much works the same way as a ListView. Inside the onItemClick method, you should be able to know which specific item was clicked. Get the Uri/absolute path for that item, and pass on that information to the next activity.
In the VideoDemo class, extract this Uri/path and set it to the VideoView.