Delete item from gridview - android

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.

Related

How to show videos from specific folder in an android activity?

I want to show all videos from a specific folder in android activity. so when user click on it, video will play maybe on android internal video player or etc. Please help me to achieve my tasks. I am also posting a picture of my desired output. I want list videos just like in the picture.this is picture of MX-player, i want same functionality in my application
Try the piece of code given below:
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.listview);
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(VideoActivity.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();
TextView tv = new TextView(vContext.getApplicationContext());
String id = null;
if (convertView == null) {
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE);
videocursor.moveToPosition(position);
id = videocursor.getString(video_column_index);
tv.setText(id);
}
else
{
tv = (TextView) convertView;
return tv;
}
Let me know if you are facing any issue with this, I'll be happy to help you.

android: how to get all folders with names

Hi can somebody help me with my code?? I have a class which should show me folders on my SD card+ folders name, but all folders have same name, but each should have different. How can i implement it??
public class ThumbnailAdapter extends BaseAdapter {
// Context required for performing queries
private final Context mContext;
// Cursor for thumbnails
private final Cursor cursor;
private final int count;
String bucket;
String id;
public ThumbnailAdapter(Context c) {
this.mContext = c;
// Get list of all images, sorted by last taken first
final String[] projection = {
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
};
String BUCKET_GROUP_BY =
"1) GROUP BY 1,(2";
String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
BUCKET_GROUP_BY,
null,
BUCKET_ORDER_BY
);
if (cursor.moveToFirst()) {
int bucketColumn = cursor.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int idColumn = cursor.getColumnIndex(
MediaStore.Images.Media.BUCKET_ID);
do {
// Get the field values
bucket = cursor.getString(bucketColumn);
id = cursor.getString(idColumn);
} while (cursor.moveToNext());
}
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) {
LinearLayout ll = new LinearLayout(mContext);
ImageView imageView = new ImageView(mContext);
TextView mytext = new TextView(mContext);
mytext.setText(bucket);
imageView.setImageResource(R.drawable.your_folder_icon);
ll.addView(imageView);
ll.addView(mytext);
return ll;
}
You are probably not setting your TextView mytext to change the text it displays - try the line:
mytext.setText(projection[position]);
I'm not quite sure how you are indexing your projection String array, but by just providing the right index (using the position variable in the getView() method, you should be able to change the TextView name correctly.

Android : gridview

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

How to dynamically update an image gallery upon the photos taken from the native camera in android?

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

How to get specified video from sdcard in android?

i am able to show all videos from sdcard into ListView but how to show only specified videos from sdcard into Listview in android.Can anybody help please?
-I am showing all videos in Listview.
-show particular video file.
This is my Code.
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);
System.out.println("========gte Count of video List============== :" + videolist);
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(VideoStoredInSDCard.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.Thumbnails.DATA));
Log.i("ThumbPath: ",thumbPath);
}
thumbImage.setImageURI(Uri.parse(thumbPath));
System.out.println("============Thumbnail============== :" + videoThumbnailCursor);
return listItemRow;
}
}
}
I am using other way to get the names of the files from sdcard.
I am using files concept to do this as in How to display files on the SD card in a ListView?

Categories

Resources