delete image from sd card in android - android

I try to select images from sd card,specific folder and show it in my gridView successfully.I have one problem.in gridview onClickListener i want to delete this image by position.strange situation.file deleted in my folder ,but gridview still showing images
private void fetchGalleryImages() {
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED};
Cursor imagecursor = getContentResolver().query(mImageUri, columns, MediaStore.Images.Media.DATA + " like ? ", new String[]{"%/Download/New Folder%"}, null);
galleryImageUrls = new ArrayList<>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);//get column index
galleryImageUrls.add(imagecursor.getString(dataColumnIndex));//get Image from column index
Log.e("array path", galleryImageUrls.get(i));
}
}
private void setUpGridView() {
imagesAdapter = new GridView_Adapter(CustomGallery_Activity.this, galleryImageUrls, true);
galleryImagesGridView.setAdapter(imagesAdapter);
galleryImagesGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File file = new File(galleryImageUrls.get(position));
if (file.exists())
{
file.delete();
imagesAdapter = new GridView_Adapter(CustomGallery_Activity.this, galleryImageUrls, true);
galleryImagesGridView.setAdapter(imagesAdapter);
}
}
});
}
Sorry I misateked.I added this line in OnClick
galleryImageUrls.remove(position);
I closed app and run again but i have same problem.. I want to update my gridview

This is correct answer.I solved myself
private void setUpGridView() {
imagesAdapter = new GridView_Adapter(CustomGallery_Activity.this, galleryImageUrls, true);
galleryImagesGridView.setAdapter(imagesAdapter);
galleryImagesGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File file = new File(galleryImageUrls.get(position));
if (file.exists())
{
file.delete();
deleteFileFromMediaManager(galleryImageUrls.get(position));
galleryImageUrls.remove(position);
imagesAdapter = new GridView_Adapter(CustomGallery_Activity.this, galleryImageUrls, true);
galleryImagesGridView.setAdapter(imagesAdapter);
}
}
});
}
private void deleteFileFromMediaManager(String path) {
try {
MediaScannerConnection.scanFile(CustomGallery_Activity.this, new String[] { path },
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
CustomGallery_Activity.this.getContentResolver()
.delete(uri, null, null);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Cannot fetch album art and album name together

I'm trying to show album art with album names.
If I use MediaStore.Audio.Media.EXTERNAL_CONTENT_URI then the album names are repeated; but I am able to show album art.
And if I use MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI then album names are not repeated but no album art is shown.
How can I get unrepeated Album Names with album art (if available)?
Screenshot
Note: I created a songs list before in which song name, artist name, song duration and album arts were fetched. But I can't fetch album name and album art(either album art is fetched or album name) with same methodology in Albums tab (I have four tabs for Songs, Artists, Albums and Playlists).
Thank you for your help.
Here is the code:
Albums.java
List<Album> sampleAlbum = new ArrayList<>();
public void getAlbum() {
ContentResolver contentResolver = getActivity().getContentResolver();
Uri songUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor songCursor = contentResolver.query(songUri, null, null, null, null);
if (songCursor != null && songCursor.moveToFirst()) {
int songAlbum = songCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM);
int songPath = songCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
do {
Album newAlbum = new Album();
newAlbum.albumName = songCursor.getString(songAlbum);
newAlbum.pathName = songCursor.getString(songPath);
sampleAlbum.add(newAlbum);
}
while (songCursor.moveToNext());
}
}
AlbumRecyclerAdapter.java
public class AlbumRecyclerAdapter extends RecyclerView.Adapter<AlbumViewHolder> {
private List<Album> albums;
private Context context;
public AlbumRecyclerAdapter(Context context, List<Album> albums) {
this.albums = albums;
this.context = context;
}
#Override
public AlbumViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.album_recycler_item, parent, false);
return new AlbumViewHolder(view);
}
#Override
public void onBindViewHolder(AlbumViewHolder holder, final int position) {
final Album sampleAlbum = albums.get(position);
holder.album_name.setText(sampleAlbum.albumName);
try {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(albums.get(position).pathName);
byte[] data = mmr.getEmbeddedPicture();
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
holder.album_image.setImageBitmap(bitmap);
holder.album_image.setAdjustViewBounds(true);
holder.album_image.setLayoutParams(new LinearLayout.LayoutParams(500, 500));
}
else {
holder.album_image.setImageResource(R.drawable.default);
holder.album_image.setAdjustViewBounds(true);
holder.album_image.setLayoutParams(new LinearLayout.LayoutParams(500, 500));
}
}
catch (Exception e) {
e.printStackTrace();
}
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Album " + sampleAlbum.albumName + "'s songs will be opened", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return albums.size();
}
}

Blank screen when opening a pdf using 'com.github.barteksc:android-pdf-viewer:2.8.2' library

I have an issue with using this library
compile 'com.github.barteksc:android-pdf-viewer:2.8.2'
Well I have a couple of pdfs created from my app and I want to give th user an option to view them from the app.Im loading the files from a dialog and on select the selected pdf shoulld open.Here is the dialog.
public class FileExplore extends BaseActivityAlt {
private static final String TAG = "F_PATH";
private static final int DIALOG_LOAD_FILE = 1000;
ArrayList<String> str = new ArrayList<String>();
ListAdapter adapter;
private Boolean firstLvl = true;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory() + "/Travelite/Saved/");
private String chosenFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this,TicketActivity.class);
startActivity(intent);
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.mipmap.pdf_icon);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.company;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Up", R.drawable.forward);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle(R.string.choose_file);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
File file = new File(Environment.getExternalStorageDirectory(),
chosenFile);
Intent intent = new Intent(FileExplore.this,PdfViewer.class);
intent.putExtra("Filename",chosenFile);
startActivity(intent);
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}}
And here is the class loaded onClicking an item in the dialog
public class PdfViewer extends BaseActivityAlt implements OnLoadCompleteListener, OnPageErrorListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf_viewer);
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
String filename = getIntent().getStringExtra("Filename");
File pdffile = new File(Environment.getExternalStorageDirectory(),filename);
Uri file = Uri.fromFile(pdffile);
Toast.makeText(PdfViewer.this, filename, Toast.LENGTH_LONG).show();
pdfView.fromUri(file)
.defaultPage(1)
.password(null)
.load();
}
#Override
public void loadComplete(int nbPages) {
}
#Override
public void onPageError(int page, Throwable t) {
}}
I just realised my mistake: I completely forgot to add the path.

Android - Listview .remove() function is not working as expected

I have a listview that is able to delete a specific image via onLongClick, but it isn't working so far. When testing, the dialog appears If i want to delete or not, i press Yes/Ok and the toast appears saying Item deleted, however the item is still there.
UPDATED ( I got the remove and delete function working thanks to user1140237)
UPDATED MAIN ACTIVITY
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yearbook);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"/CapturyGallery");
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"/CapturyGallery");
// Create a new folder if no folder named CapturyGallery exist
file.mkdirs();
}
if (file.isDirectory())
{
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++)
{
//Get the path image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
Arrays.sort(listFile);
final ListAdapter listAdapter = new CustomAdapter(Yearbook.this, FilePathStrings, FileNameStrings);
ListView lv = (ListView) findViewById(R.id.ListingView);
lv.setAdapter(listAdapter);
final ArrayList<String> list = new ArrayList(Arrays.asList(FilePathStrings));
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//Deletes item
AlertDialog.Builder adb=new AlertDialog.Builder(Yearbook.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + FileNameStrings[position]);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File file = new File(list.get(positionToRemove));
if (file.delete()) {
list.remove(position);
((CustomAdapter) listAdapter).updateMyData(FilePathStrings, FileNameStrings);
Toast.makeText(getApplicationContext(), FileNameStrings[position] + " deleted", Toast.LENGTH_LONG).show();
}
}
});
adb.show();
return true;
}
});
}
CUSTOMADAPTER
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private String[] filepath;
private String[] filename;
private static LayoutInflater inflater = null;
public CustomAdapter(Activity a, String[] fpath, String[] fname) {
activity = a;
filepath = fpath;
filename = fname;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateMyData(String[] fpath, String[] fname) {
filepath = fpath;
filename = fname;
notifyDataSetChanged();
}
#Override
public int getCount() {
return filepath.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
class MyViewHolder {
ImageView myImage;
TextView timestamp;
TextView myName;
TextView myHeader;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.PicView);
timestamp = (TextView) v.findViewById(R.id.timestamp);
myName = (TextView) v.findViewById(R.id.myName);
myHeader = (TextView) v.findViewById(R.id.textSeparator);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
MyViewHolder holder = null;
if (vi == null) {
vi = inflater.inflate(R.layout.custom_row, null);
holder = new MyViewHolder(vi);
vi.setTag(holder);
} else {
holder = (MyViewHolder) vi.getTag();
}
Bitmap bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(filepath[position]),100,100);
holder.myImage.setImageBitmap(bmp);
//PicImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.myImage.setPadding(8, 8, 8, 8);
//Set Title
holder.myName.setText(filename[position]);
ExifInterface intf = null;
try {
intf = new ExifInterface(filepath[position]);
} catch(IOException e) {
e.printStackTrace();
}
if(intf != null) {
String dateString = intf.getAttribute(ExifInterface.TAG_DATETIME);
holder.timestamp.setText("Date Taken: " + dateString.toString());
}
return vi;
}
And so my last problem is, whenever i remove something from my listview it crashed. However, the file was indeed removed. Im not sure what is the error because i tested it on my mobile phone
You need to update list data in your custom adapter too. after removing than call notifydatasetchanged
Keep below method in you customadapter to udpate list data & after that call it in longpress
public void updateMyData(String[] fpath, String[] fname) {
filepath = fpath;
filename = fname;
notifyDataSetChanged();
}
You need to call this from longPress
list.remove(position);
((CustomAdapter )listAdapter).updateMyData( FilePathStrings, FileNameStrings); /// here in your case you need to define both array global sorry not time to clean up your code
Toast.makeText(getApplicationContext(), FileNameStrings[position] +" deleted",Toast.LENGTH_LONG).show();
UPDATED
To remove file from the mentioned dir & updating listview you need to delete file from that location first and than you need to update listview
File file = new File(list.get(position));
if (file.delete()) {// this will required permission in Manifest for Write_EXTERNAL_STORATE
// if file is deleted from SD CARD
list.remove(position);
((CustomAdapter )listAdapter).updateMyData( FilePathStrings, FileNameStrings); /// here in your case you need to define both array global sorry not time to clean up your code
Toast.makeText(getApplicationContext(), FileNameStrings[position] + " deleted", Toast.LENGTH_LONG).show();
}
*CustomAdapter *
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filepath;
private ArrayList<String> filename;
private JSONArray jListData;
private int size = 0;
public CustomAdapter(Activity a, JSONArray jListData) {
activity = a;
this.jListData = jListData;
if (filepath != null)
size = jListData.length();
}
public void updateMyData(JSONArray jListData) {
this.jListData = jListData;
size = jListData.length();
notifyDataSetChanged();
}
#Override
public int getCount() {
return size;
}
public JSONObject getItem(int position) {
try {
return (JSONObject) jListData.get(position);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public long getItemId(int position) {
return position;
}
class MyViewHolder {
ImageView myImage;
TextView timestamp;
TextView myName;
TextView myHeader;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.PicView);
timestamp = (TextView) v.findViewById(R.id.timestamp);
myName = (TextView) v.findViewById(R.id.myName);
myHeader = (TextView) v.findViewById(R.id.textSeparator);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
MyViewHolder holder = null;
try {
if (vi == null) {
vi = LayoutInflater.from(activity).inflate(R.layout.custom_row, parent, false);
holder = new MyViewHolder(vi);
vi.setTag(holder);
} else {
holder = (MyViewHolder) vi.getTag();
}
JSONObject rowObject = this.jListData.getJSONObject(position);
Bitmap bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(rowObject.optString("filename")), 100, 100);
holder.myImage.setImageBitmap(bmp);
//PicImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.myImage.setPadding(8, 8, 8, 8);
//Set Title
holder.myName.setText(rowObject.optString("filename"));
ExifInterface intf = null;
try {
intf = new ExifInterface(rowObject.optString("filepath"));
} catch (IOException e) {
e.printStackTrace();
}
if (intf != null) {
String dateString = intf.getAttribute(ExifInterface.TAG_DATETIME);
holder.timestamp.setText("Date Taken: " + dateString.toString());
}
} catch (JSONException e) {
}
return vi;
}
}
ACTIVITY
private JSONArray jArrayFileData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yearbook);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
// Create a new folder if no folder named CapturyGallery exist
file.mkdirs();
}
jArrayFileData = new JSONArray();
if (file.isDirectory()) {
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++) {
JSONObject jObject = new JSONObject();
//Get the path image file
// FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
// FileNameStrings[i] = listFile[i].getName();
jObject.put("filepath", listFile[i].getAbsolutePath());
jObject.put("filename", listFile[i].getName());
jArrayFileData.put(jObject);
}
}
// Arrays.sort(listFile);
final ListAdapter listAdapter = new CustomAdapter(Yearbook.this, jArrayFileData);
ListView lv = (ListView) findViewById(R.id.ListingView);
lv.setAdapter(listAdapter);
// final ArrayList<String> list = new ArrayList(Arrays.asList(FilePathStrings));
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//Deletes item
AlertDialog.Builder adb = new AlertDialog.Builder(Yearbook.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + FileNameStrings[position]);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File file = new File(list.get(positionToRemove));
if (file.delete()) {
Toast.makeText(getApplicationContext(), jArrayFileData.getJSONObject(position).optString("filename") + " deleted", Toast.LENGTH_LONG).show();
jArrayFileData.remove(position);
// list.remove(position);
((CustomAdapter) listAdapter).updateMyData(jArrayFileData);
}
} catch (JSONException e) {
}
}
});
adb.show();
return true;
}
});
}
Use Arraylist<String> for fpath and fname in your code: Then to delete data from your listview.
Use this:
fpath.remove(index_toDelete);
fpath.remove(index_toDelete);
customAdapter.notifyDataSetChanged();

Null pointer exception trying to remove from listview

I get a null pointer exception in the deleteIt method in the filelist.notifyDataSetChanged();
I need some help trying to remove the file, please be kind. It took me a couple of hours how to add the longclick method. This could could be used by someone but I need to help with the removing item from list.
public class AndroidExplorer extends ListActivity
{
private List<String> item = null;
private List<String> path = null;
private TextView myPath;
ArrayAdapter filelist = null;
File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/GV-Skynet");
String root2 = myFile.getAbsolutePath();;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPath = (TextView)findViewById(R.id.path);
getDir(root2);
ListView list = getListView();
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id)
{
File file = new File(path.get(position));
deleteIt("Do you want to Delete", file.getName(), file );
return true;
}
});
}
private void showToast(String msg)
{
Toast error = Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG);
error.show();
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root2))
{
item.add("Return to GV-Skynet Directory");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
String fileName = file.getName();
String fname="";
String ext="";
int mid= fileName.lastIndexOf(".");
fname=fileName.substring(0,mid);
ext=fileName.substring(mid+1,fileName.length());
if(ext.equals("jpg"))
{
Intent intent = new Intent("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(file);
intent.setDataAndType (uri, "image/*");
this.startActivity(intent);
}
if(ext.equals("3gp"))
{
Intent intent = new Intent("android.intent.action.VIEW");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra ("oneshot", 0);
intent.putExtra ("configchange", 0);
Uri uri = Uri.fromFile(file);
intent.setDataAndType (uri, "video/*");
this.startActivity(intent);
}
}
}
public void deleteIt( String title, String name, File file )
{
final String name1 = name;
final File tmFile = file;
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(name1)
.setPositiveButton("YES", new DialogInterface.OnClickListener() // OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
//item = new ArrayList<String>();
item.remove(tmFile.getName()); // remove the item
filelist.notifyDataSetChanged(); // let the adapter know to update
showToast("File Deleted: " + tmFile.getName() );
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() // OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1) {
// do stuff onclick of CANCEL
showToast("CANCELLING DELETE");
}
}).show();
}
}
just try this change your statement
ArrayAdapter filelist = null;
with
ArrayAdapter<String> filelist = null;
and also you are re-declaring filelist in your getDir method so change it to
filelist = new ArrayAdapter<String>(this,R.layout.row, item);
setListAdapter(filelist);
onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
File file = new File(path.get(position));
if (file.exists()) {
deleteIt("Do you want to Delete", file.getName(), file);
} else {
Toast.makeText(this, "File not Exist", Toast.LENGTH_SHORT).show();
}
}

Android : Load image from specific directory

I have a gallery that is displaying thumbnail images in custom directories. The gallery displays fine, but I am unable to open the full image by clicking the thumbnail. My [non functioning] click listener is below
try {
if (LoadImageFiles() == true) {
GridView imgGallery = (GridView) findViewById(R.id.gallery);
final ImageAdapter ia = new ImageAdapter(PersonMedia.this);
imgGallery.setAdapter(ia);
// Set up a click listener
imgGallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String imgPath = paths.get(position);
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", imgPath);
startActivity(intent);
}
});
}
} catch (Exception ex) {
Log.e("PersonMedia.LoadPictures", ex.getMessage());
}
Here is how the gallery is populated
//Declare a module level hashtable
private Hashtable<Integer, String> paths;
private boolean LoadImageFiles() {
try{
mySDCardImages = new Vector<ImageView>();
paths = new Hashtable<Integer, String>();
fileCount = 0;
sdDir = new File(imageDirectory);
sdDir.mkdir();
if (sdDir.listFiles() != null)
{
File[] sdDirFiles = sdDir.listFiles();
if (sdDirFiles.length > 0)
{
for (File singleFile : sdDirFiles)
{
Bitmap bmap = decodeFile(singleFile);
BitmapDrawable pic = new BitmapDrawable(bmap);
ImageView myImageView = new ImageView(PersonMedia.this);
myImageView.setImageDrawable(pic);
myImageView.setId(mediaCount);
paths.put(fileCount, singleFile.getAbsolutePath());
mySDCardImages.add(myImageView);
mediaCount++;
fileCount ++;
}
}
}
}
catch(Exception ex){ Log.e("LoadImageFiles", ex.getMessage()); }
return (fileCount > 0);
}
I was able to resolve this by using a hashtable to store the position and path of the images when the thumbnails are loaded. Below are the 2 pertinent code snippets
//Where the gallery is populated and the onclick is defined
private void PopulateGallery() {
try {
if (LoadImageFiles() == true) {
GridView imgGallery = (GridView) findViewById(R.id.gallery);
imgGallery.setAdapter(new ImageAdapter(PersonMedia.this));
// Set up a click listener
imgGallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String imgPath = paths.get(position);
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", imgPath);
startActivity(intent);
}
});
}
} catch (Exception ex) {
Log.e("PersonMedia.LoadPictures", ex.getMessage());
}
}
//Where the images are loaded. You'll need to create a module level hashtable
private Hashtable<Integer, String> paths;
private boolean LoadImageFiles() {
try{
mySDCardImages = new Vector<ImageView>();
paths = new Hashtable<Integer, String>();
fileCount = 0;
sdDir = new File(imageDirectory);
sdDir.mkdir();
if (sdDir.listFiles() != null)
{
File[] sdDirFiles = sdDir.listFiles();
if (sdDirFiles.length > 0)
{
for (File singleFile : sdDirFiles)
{
Bitmap bmap = decodeFile(singleFile);
BitmapDrawable pic = new BitmapDrawable(bmap);
ImageView myImageView = new ImageView(PersonMedia.this);
myImageView.setImageDrawable(pic);
myImageView.setId(mediaCount);
paths.put(fileCount, singleFile.getAbsolutePath());
mySDCardImages.add(myImageView);
mediaCount++;
fileCount ++;
}
}
}
}
catch(Exception ex){ Log.e("LoadImageFiles", ex.getMessage()); }
return (fileCount > 0);
}
Do your images have extensions, such as .jpg or .png? I'm not quite sure but it looks like you are looking for an image that is string version of your personId, without any file extension.
Please correct me if I'm wrong.
Also please post more details, such as the errors you are getting.
Updated answer below.
Use View.setTag(Object), when you are adding items to your ListView (I am guessing). You can call something like the following.
view.setTag("imgFile.jpg");
And then from inside of your onClickListener, just do this:
String img = (String) getTag();

Categories

Resources