Android file browser error - android

im trying to make folder browser for my app, but i have error that throws me out of browser activity. When activity is started , it shows root folder with all folders in it, then I can click on one of the folders, and it opens and shows all folders in it, and after that, if i click on something, ive got error,also variable File[] filenames is null after last click. So method getFileFromList(String path) works fine 2 times and crashes on 3rd. And i dont have any errors in console. Whats wrong with my code?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fflist);
pathtext = (TextView) findViewById(R.id.pathtext);
getFileFromList("/");
registerForContextMenu(getListView());
}
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.d(LOG_TAG, String.valueOf(position));
String clickedItem = neededFilenames.get(position);
getFileFromList(clickedItem);
}
public void getFileFromList(String path) {
Log.d(LOG_TAG, path);
neededFilenames = new ArrayList<String>();
File dir = new File(path);
File[] filenames = dir.listFiles();
Log.d(LOG_TAG, String.valueOf(filenames));
if (filenames != null) {
for (int i = 0; i < filenames.length; i++) {
if (filenames[i].isDirectory() && !filenames[i].isHidden() && filenames[i].canRead()) {
neededFilenames.add(filenames[i].getName());
}
}
Log.d(LOG_TAG, String.valueOf(neededFilenames));
} else Toast.makeText(this, "something wrong", Toast.LENGTH_SHORT).show();
Collections.sort(neededFilenames);
pathtext.setText("Location: /" + path);
FileFolderAdapter adapter = new FileFolderAdapter(this, neededFilenames);
setListAdapter(adapter);
}

actually i found out, that this "browser" only works in the root folder and 1 click out of it< because at the begining, when you using only items names,you have legit "path" to root- "/" , and after 1 click you will get "path" variable as - " /folder" and that still is legit path to folder, after 2 click on any folder in that first folder, you just have only that folder name "folder", without all path to root "/", so you cant make new File only out of name without having full path from root. not sure if its understandable enough, but maybe it helps someone :)

Related

How do I open a the folder where an image is located from my Xamarin Android Application?

I have tried looking almost everywhere on how to open the parent folder of a child image displayed in my app with no success. Am debugging my Android Application to a device running Android API level 29. The inbuilt samsung File Manager has a menu item for navigating to the source folder of any file and that is why I believe there is a way to tell the App to open the location of the image displayed on my ImageSwitcher object. The app has a context menu with a Open Source Folder menu item for opening the source folder of the image, the code to do that is the problem...
Code
public override bool OnContextItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.image_folder:
try
{
//I tried this inbuild dotnet method but it does not work
string file_path = new Java.IO.File(files[index]).AbsolutePath;
DirectoryInfo info= new DirectoryInfo(file_path);
info.MoveTo(new Java.IO.File(file_path).Parent);
}catch(Exception ex)
{
Android.App.AlertDialog.Builder mybuilder= new Android.App.AlertDialog.Builder(this);
mybuilder.SetTitle("Exception");
mybuilder.SetMessage(ex.Message);
mybuilder.Show();
}
break;
}
}
Code below shows how I obtained the path to the ImageSwicther currentl image.
void read_images()
{
//access the application's directory
Java.IO.File original_file = (Application.GetExternalFilesDir(null));
//check if the file is read only
if (original_file.CanRead())
{
//Toast.MakeText(this, "This folder can be read", ToastLength.Long).Show();
}
if (original_file.Exists() && original_file.IsDirectory)
{
try
{
//make sure the file is an image file
//apply the code for image mime type extensions
files = Directory.GetFiles(original_file.AbsolutePath);
for (int i = 0; i < files.Length; i++)
{
//delete any file that does not end with an image format
if (files[i].EndsWith("jpg") == false || files[i].EndsWith("png") == false)
{
Directory.Delete(files[i]);
}
}
}
catch (Exception e)
{
Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
alert.SetTitle("File Read Exception");
alert.SetMessage(e.Message + "\n" + e.Data);
alert.Show();
}
// Toast.MakeText(this, "File exists",ToastLength.Short).Show();
}
}
Now that the I have the paths to the images in a string array, all I do is use an integer variable called index to switch the path and display it to the ImageSwitcher object when user swipes right or left like
//increment index for right swipe and decrement for left
myswitcher.ClearAnimation();
myswitcher.SetInAnimation(this,Resource.Animation.slide_in_left);
myswitcher.SetOutAnimation(this,Resource.Animation.slide_out_left);
myswitcher.SetImageURI(Android.Net.Uri.FromFile(new Java.IO.File(files[index])));
NB:
The files[index] is a string array containing paths of all the images displayed in the imageswitcher object.

Making a GridView take images from a specific folder

I am a newbie to android app making and I am still a beginner with a little knowledge . I have been trying to make an android app that works like a gallery , but it only displays images under a specific folder. For the UI , I am starting with only a GridView (or TwoWayGridView which is derived from the latter) , and have been trying to let this GridView take its contents from this folder .
I have made this folder and copied an image to it for testing and failed. No image was displayed .Plus I am not very familiar with Cursors and ListAdapters . Somethings that I'm sure that are correct are permissions , manifest , and layout of the activity.Moreover , I believe my problem is around URIs . Please check my code below :
Some namings:
Uri contentUri;
Cursor mImageCursor;
TwoWayGridView mImageGrid;
ListAdapter mAdapter;
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
onCreate method :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
File motherDirectory = new File(sdCard+"/Favory");
if(!motherDirectory.exists()){
motherDirectory.mkdir();
}
MediaScannerConnection.scanFile(this, new String[]{motherDirectory.getAbsolutePath()} ,null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
// TODO Auto-generated method stub
contentUri = uri ;
initGrid(uri);
}
});
}
initGrid(Uri) method :
private void initGrid(Uri folderUri) {
mImageCursor = this.getContentResolver().query(folderUri,
ImageThumbnailAdapter.IMAGE_PROJECTION, null, null,
MediaStore.Images.ImageColumns.DISPLAY_NAME);
mImageGrid = (TwoWayGridView) findViewById(R.id.gridview);
mAdapter = new ImageThumbnailAdapter(this, mImageCursor);
mImageGrid.setAdapter(mAdapter);
mImageGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(TwoWayAdapterView<?> parent, View v, int position, long id) {
Log.i(TAG, "showing image: " + mImageCursor.getString(ImageThumbnailAdapter.IMAGE_NAME_COLUMN));
Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
Thanks for your help , and please if there is an easier alternative way of doing this tell me, I care for the results more than the methods now . If you need anything or any more information please tell me in the comments below . Thanks again !
To Read the Files of a folder you can use this function ( from this post ):
String directoryName = Environment.getExternalStorageDirectory().toString()+"/YourFolder/";
public ArrayList<File> listf(String directoryName, ArrayList<File> files) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
Log.e("path : "," "+file);
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
return files;
}
Then you should load this list of files to your GridView Adapter, i suggest you use Universal Image Loader
You just give your file path and Adapter ImageVIew at that position
loadImageUtil.loadBitmapToImageView(imageView, youArrayList.get(position));
For more informations how to use this library you can see examples, there is an example with grid view gridView

How to rename folder of SD-Card from list-view in android

I am trying get all the list of particular folder name from SD-Card to list-view in android. I am giving two option to user they can create folder as well as they can rename folder from application it self.
With the list-view i have given check-box so user can check any single list value at a time and then can perform operation as they want of editing or creating folder in SD-Card.
Everything is working fine till creating folder, but my problem start's here, when user tries to rename folder name, then first time user can successfully changes the folder name but while doing same task second time, user is not able to rename same folder again.
What mistake i am doing, following is my code please help, Thanks in advance.
private static List<String> myList = new ArrayList<String>();
public static void folder_create() {
if (Code.pm == 1) {
String updateFolder = Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/";
File filecall = null;
filecall = new File(updateFolder);
File list[] = filecall.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String mUpdateName = myList.get(i);
File file = new File(updateFolder + "/" + mUpdateName);
System.out.println("=======File======" + file);
File file2 = new File(updateFolder + "/" + Code.className);
System.out.println("=======File2======" + file2);
file.renameTo(file2);
}
} else {
String filepath = Environment.getExternalStorageDirectory()
.getPath();
File file = new File(filepath, "/AudioRecorder/" + Code.className);
if (!file.exists()) {
file.mkdirs();
}
}
}
Here Code is static class and pm is integer variable. So when user click button based on pm variable value it will perform task weather to rename folder or create folder.
If I understand your issue, you're trying to rename a directory after having made 'some tasks'. Are those tasks made into this folder? If yes, be sure that you have closed your streams (creating / modifying content) like so:
stream.close();
Please also check the LogCat to see if some warnings are shown.

How to check for the existence of a file?

String extra=imagepath.get(i).toString();
String extra2=imageid.get(i).toString();
String path = "/mnt/sdcard/Android/data/com.example.webdata/files/Download/" + extra2 + ".jpg";
File f = new File(path);
if(f.exists())
{
//Toast.makeText(getApplicationContext(), "File already exists....",
// Toast.LENGTH_SHORT).show();
}
else
{
downloadfile();
}
I am using the above code to check if a file exists or not. I have checked it with one file and it works fine, but when I use it in my application where there are multiple (100-200) images it always starts downloading files whether they exist or not. Is there a better method than this?
First check how many images on folder:-
File extStore = Environment.getExternalStorageDirectory();
File[] imageDirs = extStore.listFiles(filterForImageFolders);
after above you run the loop and check u r condition:-
for(int i=0;i<list.length;i++)
{
// ur condition
}

android recursively list the files in sd card

I want to search for a particular file in my sd card . So i am trying to list complete files and search for the pattern. Please see code below
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
listfiles( new File(root_sd));
}
public void listfiles(File file) {
//file = new File(path);
// file = new File( root_sd ) ;
File list[] = file.listFiles();
Log.i("DIR", "PATH" +file.getPath());
for (int i = 0; i < list.length; i++) {
// myList.add( list[i].getName() );
File temp_file = new File(file.getAbsolutePath(),list[i].getName());
Log.i("DIR", "PATH" +temp_file.getAbsolutePath());
if (temp_file.isFile() && temp_file.listFiles() != null) {
Log.i("inside", "call fn");
listfiles(temp_file);
} else {
if (list[i].getName().toLowerCase().contains("pattern1"))
Log.i("File", i + list[i].getName());
if (list[i].getName().toLowerCase().contains("pattern2"))
Log.i("File", i + list[i].getName());
}
}
Here only first level of search is happening . This condition if (temp_file.isFile() && temp_file.listFiles() != null)
is always returning false and thus recursive call not happening.
Please help me to fix it. Thanks for your answer and time.
if the temp_file.isFile() returns true then it means it is a file and hence temp_file.listFiles() automatically becomes null thus making your entire statement false. Thus your combined statement returns a false always. What you need is a || in place of &&.

Categories

Resources