How to get into the Downloads Folder to load all the pictures? - android

I want to add the downloads folder to my code,
this is my helper class (File Paths):
//"storage/emulated/0" = Environment.getExternalStorageDirectory().getPath().
public String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public String PICTURES = ROOT_DIR + "/Pictures";
public String CAMERA = ROOT_DIR + "/DCIM/camera";
public String DOWNLOADS = ROOT_DIR + "/Download";
and this my class where I use this paths
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if(FileSearch.getDirectoryPaths(filePaths.PICTURES) != null){
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
ArrayList<String> directoryNames = new ArrayList<>();
for(int i = 0; i < directories.size(); i++){
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
directories.add(filePaths.CAMERA);
directories.add(filePaths.DOWNLOADS);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, directories); // WARUM
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup image grid for the directory chosen
setupGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
If I cut the downloads part out, I get all the files of the other paths but if the downloads part is inside my code, I got an Exception because the downloads files arent added to the arrayList later.
I need the correct path for the downloads.
I found this:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
but this returns me a file and I need a String in my helper class.
EDIT:
Sorry, it was my fault. I got the Exception because I didnt had any pictures in my other directories. After I inserted one, my Downloads Folder was showed. I solved this error with try and catch now.

You can get String path from File like this
String path = file.toURI().toString();

Related

Sort list view with Folders and Files types alphabetically in andorid

Sort list view with Folders and Files alphabetically
I am trying the following code
public class MainActivity extends ActionBarActivity {
private File file;
private List<String> myList;
private ListView listView;
private TextView pathTextView;
private String mediapath = new String(Environment.getExternalStorageDirectory().getAbsolutePath());
private final static String[] acceptedExtensions= {"mp3", "mp2", "wav", "flac", "ogg", "au" , "snd", "mid", "midi", "kar"
, "mga", "aif", "aiff", "aifc", "m3u", "oga", "spx"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.pathlist);
pathTextView=(TextView) findViewById(R.id.path);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
Log.e("Root",root_sd);
String state = Environment.getExternalStorageState();
File list[] = null ;
/* if ( Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ) { // we can read the External Storage...
list=getAllFilesOfDir(Environment.getExternalStorageDirectory());
}*/
pathTextView.setText(root_sd);
file = new File( root_sd ) ;
list = file.listFiles(new AudioFilter());
Log.e("Size of list ","" +list.length);
//LoadDirectory(root_sd);
for( int i=0; i< list.length; i++)
{
String name=list[i].getName();
int count = getAudioFileCount(list[i].getAbsolutePath());
Log.e("Count : "+count, list[i].getAbsolutePath());
if(count!=0)
myList.add(name);
/*int count=getAllFilesOfDir(list[i]);
Log.e("Songs count ",""+count);
*/
}
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList ));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
File temp_file = new File( file, myList.get( position ) );
if( !temp_file.isFile())
{
//LoadDirectory(myList.get( position ));
file = new File( file, myList.get( position ));
File list[] = file.listFiles(new AudioFilter());
myList.clear();
for( int i=0; i< list.length; i++)
{
String name=list[i].getName();
int count = getAudioFileCount(list[i].getAbsolutePath());
Log.e("Count : "+count, list[i].getAbsolutePath());
if(count!=0)
myList.add(name);
/*int count=getAllFilesOfDir(list[i]);
Log.e("Songs count ",""+count);
if(count!=0)
myList.add(name);*/
}
pathTextView.setText( file.toString());
//Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, myList ));
}
}
});
}
It gives me the files and folders for all songs
Howevever ,If a folder contains both sub folders and songs ,I want to sort the listview to show all sub folders first and then all the songs in that folder
How can this be done
use this function
Collections.sort(myList);
add this line before setAdapter.
it will sort your String Arraylist in Alphabet order.
Try the following code to sort:
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});

Listview of backendless directories

I'm using backendless and I'm trying to display my directories in a listview. I'm using Android Studio.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Backendless.setUrl(Defaults.SERVER_URL);
Backendless.initApp(this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION);
Backendless.Files.listing("/Uploads", "*docs", true, new AsyncCallback<BackendlessCollection<FileInfo>>() {
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
String[] info = {URL, publicURL, name};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, info);
getListView().setAdapter(adapter);
}
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
}
});
}
}
It has no error but the app doesn't open. Can anyone help me what to do?
Here is the start for fixing your problem:
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
// create a list for your data
List<String> infoList = new ArrayList<>();
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
// put everything into one string temporarily
// String[] info = {URL, publicURL, name};
String info = URL + " " + publicURL + " " + name;
infoList.add(info);
}
// loop through ALL your data before creating/assigning adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, infoList);
getListView().setAdapter(adapter);
}
Now your adapter is going to get a little more complicated, because you will not want to have everything on one line. You will need to create a layout for your list item. Then you need to use either SimpleAdapter or create a custom class extending BaseAdapter and use that to display your data.

Android - Configurable directory?

One of the steps in building my app is to let the user select a folder in which some files are stored. How can i make this configurable, without hardcoding the directory. Is there any 3rd party library that i can use to do this ?
#Vikram's link provides a dialog that you can use. You can then save the directory the user chose using Shared Preferences.
Here is a simple example on how to use Shared Preferences.
Another tutorial can be found here.
UPDATE: A switch suddenly turned on inside me to do something like this. Credits still go to schwiz in this answer for the base code used. :)
//global variables
private File[] fileList;
private String[] filenameList;
private File[] loadFileList(String directory) {
File path = new File(directory);
if(path.exists()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
//add some filters here, for now return true to see all files
//File file = new File(dir, filename);
//return filename.contains(".txt") || file.isDirectory();
return true;
}
};
//if null return an empty array instead
File[] list = path.listFiles(filter);
return list == null ? new File[0] : list;
} else {
return new File[0];
}
}
public void showFileListDialog(final String directory, final Context context) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(context);
File[] tempFileList = loadFileList(directory);
//if directory is root, no need to up one directory
if(directory.equals("/")) {
fileList = new File[tempFileList.length];
filenameList = new String[tempFileList.length];
//iterate over tempFileList
for(int i = 0; i < tempFileList.length; i++) {
fileList[i] = tempFileList[i];
filenameList[i] = tempFileList[i].getName();
}
} else {
fileList = new File[tempFileList.length+1];
filenameList = new String[tempFileList.length+1];
//add an "up" option as first item
fileList[0] = new File(upOneDirectory(directory));
filenameList[0] = "..";
//iterate over tempFileList
for(int i = 0; i < tempFileList.length; i++) {
fileList[i+1] = tempFileList[i];
filenameList[i+1] = tempFileList[i].getName();
}
}
builder.setTitle("Choose your file: " + directory);
builder.setItems(filenameList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File chosenFile = fileList[which];
if(chosenFile.isDirectory()) {
showFileListDialog(chosenFile.getAbsolutePath(), context);
}
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
public String upOneDirectory(String directory) {
String[] dirs = directory.split(File.separator);
StringBuilder stringBuilder = new StringBuilder("");
for(int i = 0; i < dirs.length-1; i++) {
stringBuilder.append(dirs[i]).append(File.separator);
}
return stringBuilder.toString();
}
The code above acts like a mini file explorer that lists the files and folders of the Android File System. You use it like:
showFileListDialog(Environment.getExternalStorageDirectory().toString(),
MainActivity.this);
Answering your question:
Add global key variables
//package name goes here.
public static final String PACKAGE_NAME = "com.example.app";
public static final String KEY_DIRECTORY_SELECTED =
PACKAGE_NAME + ".DIRECTORY_SELECTED";
private SharedPreferences prefs;
initialize your SharedPreferences somewhere on onCreate before you use it:
prefs = getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
and then you can add a positive button to the dialog
builder.setPositiveButton("Save Directory", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putString(KEY_DIRECTORY_SELECTED, directory).commit();
}
});
In your activity, instead of using the SDCard default directory you can
//if no saved directory yet, use SDCard directory as default
String oldChosenDirectory = prefs.getString(KEY_DIRECTORY_SELECTED,
Environment.getExternalStorageDirectory().toString());
showFileListDialog(oldChosenDirectory, MainActivity.this);
As Vikram pointed out. you also need to do this in your FileNameFilter so that the dialog will display directories ONLY.
Update: As noted in this SO answer, the parameters dir and filename does not refer to the same file. The dir parameter is the directory containing the file, while filename is the filename of the file itself. To determine whether the filte itself is a directory, we need to create a new file from the parameters like so:
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File file = new File(dir.getAbsolutePath() + File.separator + filename);
return file.isDirectory();
}
};

How to list all the files in a custom Directory

I'm trying to list all the files in a directory I have made, when I create the directory I warp a file for each contact into the dir. I then want to be able to list all those files inside/within the directory. I have tried everything including
String a = listFiles().tostring();
Yet, nothing happens. To sum it up, I want to list all the files within a custom dir in the SD card.
Here's my updated code
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream = new FileInputStream(path);
String read = path.getbytes().tostring();
You have to see this tutorial how to build an android file browser it will help you a lot!!
This one list all folder and files in sdcard you can adapt it to what you need by changing the value of currentDir in the code
This code is travel entire sdcard and list files. that's may be helpful to you ..!
import java.io.*;
import java.util.*;
public class DirUtils {
public static List recurseDir(String dir) {
String result, _result[];
result = recurseInDirFrom(dir);
_result = result.split("\\|");
return Arrays.asList(_result);
}
private static String recurseInDirFrom(String dirItem) {
File file;
String result,list[];
result = dirItem;
file = new File(dirItem);
if (file.isDirectory()) {
list = file.list();
File[] fileslist = file.listFiles(new MyDocFileFilter());
if (fileslist != null) {
for (File file1: fileslist) {
System.out.println(file1.getAbsolutePath());
}
}
else {
System.out.println("No Subdirectory Found.");
}
for (int i = 0; i < list.length; i++)
result = result + "\n" + recurseInDirFrom(dirItem + File.separatorChar + list[i]);
}
return result;
}
static class MyDocFileFilter implements FileFilter
{
private final String[] myDocumentExtensions
= new String[] {".java", ".png", ".html", "class"};
public boolean accept(File file) {
if (!file.isFile())
return false;
for (String extension : myDocumentExtensions) {
if (file.getName().toLowerCase().endsWith(extension))
return true;
}
return false;
}
}
public static void main(String arg[]) {
DirUtils.recurseDir("your path ");
}
}

List all the folder and files of Dropbox using Dropbox API

Am looking for the tutorial to display all the files and folder in a listview..but I didn't get anything..Does anyone here know that how can I show all the folder and files of Dropbox into my listview..So that when I click on any of the file..Then that file starts download..
Well I know here that How to download a file from Dropbox, but for that I need to put that name of the file in my code in a static way..
I am also going to use filter afterwards for .csv file only...but I want to show all the files in a listview.
Thanks..
String[] fnames = null;
Entry dirent = mApi.metadata("/", 1000, null, true, null);
ArrayList<Entry> files = new ArrayList<Entry>();
ArrayList<String> dir=new ArrayList<String>();
for (Entry ent: dirent.contents)
{
files.add(ent);// Add it to the list of thumbs we can choose from
//dir = new ArrayList<String>();
dir.add(new String(files.get(i++).path));
}
i=0;
fnames=dir.toArray(new String[dir.size()]);
return fnames;
This is what i use.
once you have stringarray fnames,you can display it in a listview.
You can display it in a gridview like this
final GridView gv=(GridView)temp.findViewById(R.id.gridView1);
ArrayAdapter<String> ad = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1,fnames);
gv.setBackgroundColor(Color.BLACK);
gv.setNumColumns(3);
gv.setGravity(Gravity.CENTER);
gv.setAdapter(ad);
gv.setBackgroundResource(R.drawable.black_cloud1);
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(mContext,gv.getItemAtPosition(arg2).toString(),Toast.LENGTH_SHORT).show();
temp.setData(fnames,gv.getItemAtPosition(arg2).toString());
return;
}
});
Try this code to list the files.....I don't know more about Dropbox, try it
Entry contact = mDBApi.metadata("/", 0, null, true, null);
List<Entry> CFolder = contact.contents;
for (Entry entry : CFolder) {
Log.i("DbExampleLog", "Filename: " + entry.fileName());}
please use this one , it is the latest api .....
public void login(String accessToken) {
DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder("ManualApp")
.withHttpRequestor(OkHttp3Requestor.INSTANCE)
.build();
mDbxClient = new DbxClientV2(requestConfig, accessToken);
}
public List<Metadata> getListFile(String path) {
if (mDbxClient == null) {
RkLogger.e("get files error", "must login first please");
return null;
}
try {
return mDbxClient.files().listFolder(path).getEntries();
} catch (DbxException e) {
RkLogger.e("DbxException ", e.toString());
return null;
}
}

Categories

Resources