So, basically I have this code (all credits to mburhman's File Explorer - https://github.com/mburman/Android-File-Explore):
private File path = new File(Environment.getExternalStorageDirectory() + "");
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
readDir = (Button) findViewById(R.id.btnReadDirectory);
readDir.setOnClickListener(this);
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
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.drawable.file_icon);
File sel = new File(path, fList[i]);
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.directory_icon;
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.directory_up);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
UIHelper.displayText(this, R.id.tvPath, "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) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
Sorry for it being long. I just want to ask why is it not possible by changing File path to:
File path = getExternalFilesDir(null);
or how do you make it happen so I can store my files to my reserved external SD Card.
EDIT:
Actually, found out that I was pointing to the assets folder since I was following this blog post.
This is method which points to the assets folder
https://gist.github.com/huxaiphaer/268b94a0e7959822fa679a7523701187
It basically is possible, but the place of the external storage for your application is different on different devices (basically because some devices have the external as part of their integrated storage). I have taken the code below from somewhere on SO and it works for me:
private File getAbsoluteFile(String relativePath, Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return new File(context.getExternalFilesDir(null), relativePath);
} else {
return new File(context.getFilesDir(), relativePath);
}
}
Related
Here is my current code. I am very new to programming and Android Studio. I assumed that there is a stupid logic error somewhere in here but have checked it over (and over, and over) and cannot for the life of me figure out why files will not delete.
The intention is for the bottom bar to come up when an item/items are long clicked and the DEL button will appear and when the user confirms, the file will delete. However, the files will not delete/be removed from the list of items after confirming.
Please help! Thanks
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
}
class TextAdapter extends BaseAdapter{
// String array of items in a directory
private List<String> data = new ArrayList<>();
// Boolean array to store which items are selected in list
private boolean[] selection;
public void setData(List<String> data){
if(data != null){
this.data.clear();
if(data.size() > 0){
this.data.addAll(data);
}
notifyDataSetChanged();
}
}
void setSelection(boolean[] selection){
if(selection != null){
// Creating new array copy
this.selection = new boolean[selection.length];
// Populating new array copy
for (int i = 0; i < selection.length; i++){
this.selection[i] = selection[i];
}
// Notifying that data changed
notifyDataSetChanged();
}
}
#Override
public int getCount() {
return data.size();
}
#Override
public String getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
convertView.setTag(new ViewHolder((TextView) convertView.findViewById(R.id.textItem)));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
final String path = getItem(position);
holder.info.setText(path.substring(path.lastIndexOf('/')+1));
if(selection != null){
if(selection[position]){
holder.info.setBackgroundColor(Color.LTGRAY);
}
else{
holder.info.setBackgroundColor(Color.WHITE);
}
}
return convertView;
}
class ViewHolder{
TextView info;
ViewHolder(TextView info){
this.info = info;
}
}
}
// Checking permissions
private static final int REQUEST_PERMISSIONS = 1234;
// String array storing read/write external storage permission
private static final String[] PERMISSIONS = {
// Requires min SDK version 16
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
// Asking for 2 permissions
private static final int PERMISSIONS_COUNT = 2;
// Return boolean for if permissions will be granted
#SuppressLint("NewApi")
private boolean arePermissionsDenied(){
int p = 0;
while (p < PERMISSIONS_COUNT){
// If permission is not granted
if(checkSelfPermission(PERMISSIONS[p]) != PackageManager.PERMISSION_GRANTED){
return true;
}
p++;
}
return false;
}
// Flag to check if file manager is intialized
private boolean isFileManagerInit = false;
// Stores which items are selected in manager for modifying/opening
private boolean[] selection;
private File[] files;
private List<String>filesList;
private int filesFoundCount;
// OnResume
#Override
protected void onResume(){
super.onResume();
// If build is Marshmellow or higher, we have to ask for permissions
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && arePermissionsDenied()) {
// Requesting for permissions
requestPermissions(PERMISSIONS, REQUEST_PERMISSIONS);
return;
}
// Checking if File Manager has been initialized. If not, initialize
if(!isFileManagerInit){
// Setting default folder
final String rootPath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
final File dir = new File(rootPath);
// Creating file array
files = dir.listFiles();
// Displaying current path
final TextView pathOutput = findViewById(R.id.pathOutput);
// Setting pathOutput text to rootPath
pathOutput.setText(rootPath.substring(rootPath.lastIndexOf('/')+1));
// Number of files
filesFoundCount = files.length;
// Creating List elements and populating
final ListView listView = findViewById(R.id.listView);
final TextAdapter textAdapter1 = new TextAdapter();
listView.setAdapter(textAdapter1);
filesList = new ArrayList<>();
for(int i = 0; i < filesFoundCount; i++){
filesList.add(String.valueOf(files[i].getAbsolutePath()));
}
textAdapter1.setData(filesList);
// Allocating memory for array
selection = new boolean[files.length];
// To set item as selected
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// If unselected, select it
selection[position] = !selection[position];
// If selected, unselect it
textAdapter1.setSelection(selection);
boolean isAtLeastOneSelected = false;
// Checking if elements are selected
for(int i = 0; i < selection.length; i++){
if(selection[i]){
isAtLeastOneSelected = true;
break;
}
}
// If there are selections made, pull up the buttons on bottom
if(isAtLeastOneSelected){
findViewById(R.id.bottomBar).setVisibility(View.VISIBLE);
}
// If there are no selections, then hide bottom bar
else{
findViewById(R.id.bottomBar).setVisibility(View.GONE);
}
return false;
}
});
final Button b1 = findViewById(R.id.b1);
final Button b2 = findViewById(R.id.b2);
final Button b3 = findViewById(R.id.b3);
final Button b4 = findViewById(R.id.b4);
final Button b5 = findViewById(R.id.b5);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder deleteDialog = new AlertDialog.Builder(MainActivity.this);
deleteDialog.setTitle("Delete");
deleteDialog.setMessage("Are you sure you want to delete this file/folder?");
deleteDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
// If user wants to delete
public void onClick(DialogInterface dialog, int which) {
for(int i = 0; i < files.length; i++){
if(selection[i]){
deleteFileOrFolder(files[i]);
selection[i]=false;
}
}
files = dir.listFiles();
filesFoundCount = files.length;
filesList.clear();
for(int i = 0; i < filesFoundCount; i++){
filesList.add(String.valueOf(files[i].getAbsolutePath()));
}
textAdapter1.setData(filesList);
}
});
deleteDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
deleteDialog.show();
}
});
// Setting isFileManagerInit to true
isFileManagerInit = true;
}
}
// Method that will delete file or folder
private void deleteFileOrFolder(File fileOrFolder){
// Check if file or directory
// If folder
if(fileOrFolder.isDirectory()){
// If folder is empty
if(fileOrFolder.list().length == 0){
fileOrFolder.delete();
}
// Delete every file in the folder
else{
String files[] = fileOrFolder.list();
for(String temp:files){
File fileToDelete = new File(fileOrFolder, temp);
deleteFileOrFolder(fileToDelete);
}
// Deleting folder itself
if(fileOrFolder.list().length == 0){
fileOrFolder.delete();
}
}
}
// If just a file
else{
fileOrFolder.delete();
}
}
// Checking if the user granted permissions
#SuppressLint("NewApi")
#Override
public void onRequestPermissionsResult(final int requestCode, final String[] permissions,
final int[] grantResults){
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// If requestCode equal to request permissions and are not null
if(requestCode == REQUEST_PERMISSIONS && grantResults.length>0){
// If permissions denied, clear app data to continue asking user for permissions
if(arePermissionsDenied() == true){
// Requires 19 or higher, but will not be called anyway if that is the case, ignore warnings
((ActivityManager) Objects.requireNonNull(this.getSystemService(ACTIVITY_SERVICE))).clearApplicationUserData();
recreate();
}
else{
onResume();
}
}
}
}
This array declaration is invalid:
String files[] = fileOrFolder.list();
Don't over complicate the deleteFileOrFolder() method. Try it like this:
private boolean deleteFileOrFolder(File fileOrFolder){
File[] files = fileOrFolder.listFiles();
if (files != null) {
for (File file : files) {
deleteFileOrFolder(file);
}
}
return fileOrFolder.delete();
}
I have a listview which display a list of files (without filename extension) stored in the internal memory of the phone.
Then I have implement the OnItemLongClickListener that allow the user to delete a file.
OnItemLongClickListener works with the "switch" statement.
because position of the items in the list view will change every time a file will be deleted, I would like to implement a rule that check if the name of the file match the related file, no matter if name of the file is moved in case 0, case 1 and so on.
To be clear:
Initial Listview:
switch Listview items related file to delete
case 0; A A.map
case 1; B B.map
case 2; C C.map
case 3; D D.map
Listview after B has been deleted:
switch Listview items related file to delete
case 0; A A.map
case 1; C C.map
case 2; D
Now, if before I wrote a rule at case 1 which was to delete B.map, it works fine.
But now item C have the same rule of case 1 , and rule does not match.
Because I am new to android, I don't know how to dove this problem.
Can somebody help me?
This is the Activity
public class MainActivity extends Activity {
ListView lv;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/");
File[] filelist = dir.listFiles();
String[] theNamesOfFiles = new String[filelist.length];
for (int i = 0; i < theNamesOfFiles.length; i++) {
String temp = filelist[i].getName();
theNamesOfFiles[i] = temp.substring(0, temp.lastIndexOf('.'));
}
Arrays.sort(theNamesOfFiles);
adapter = new ArrayAdapter<String>(this, R.layout.list_row, theNamesOfFiles);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// setting onItemLongClickListener and passing the position to the function
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch(position){
case 0:{
}
break;
case 1:{
}
break;
case 2:{
}
break;
case 3:{
}
break;
case 4:{
}
break;
}
return true;
}
});
}
public void doDeleteFile(int position){
File fileToDelete = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "A.map");
if(!fileToDelete.isDirectory()){
try{
if(fileToDelete.delete()){
System.out.println("File delete operation success");
}
else{
System.out.println("File delete operation failed");
}
}catch(Exception ex){
System.out.println("Exception :"+ex.getMessage());
}
}else{
System.out.println("It is not a file");
}
}
}
when you deleted your item remove it from array also and then call notifyDataSetChange() on adapter after updating the array item
No need to check for name.You can do it by position
I would do it like this:
First I will have a data structure about the items.
public class MyFile {
File file;
String fileName;
public MyFile(File file)
{
this.file = file;
this.fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
}
#Override
public String toString() {
return this.fileName;
}
}
toString() method is important. That method gives the text in the ListView in the ArrayAdapter.
Then I would initialize the adapter like this.
adapter = new ArrayAdapter<MyFile>(this, R.layout.list_row, arrayOfMyFileObjects);
And lastly in onItemLongClick() function you can get the respective MyFile object like this
MyFile item = adapter.getItem(position);
And then you can delete using deleteFile(item.file);
I think the below code should do it.
public class MainActivity extends Activity {
ListView lv;
ArrayAdapter<MyFile> adapter;
public void list() {
lv = (ListView) findViewById(R.id.listView1);
File dir = new File(Environment.getExternalStorageDirectory().getPath()
+ "/osmdroid/tiles/");
File[] filelist = dir.listFiles();
ArrayList<MyFile> theNamesOfFiles = new ArrayList<MyFile>();
for (File temp : filelist) {
theNamesOfFiles.add(new MyFile(temp));
}
Collections.sort(theNamesOfFiles, new Comparator<MyFile>() {
#Override
public int compare(MyFile lhs, MyFile rhs) {
return lhs.toString().compareToIgnoreCase(rhs.toString());
}
});
adapter = new ArrayAdapter<MyFile>(this, R.layout.list_row,
theNamesOfFiles);
lv.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
list();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// setting onItemLongClickListener and passing the position to the
// function
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
doDeleteFile(adapter.getItem(position).file);
return true;
}
});
}
public void doDeleteFile(File fileToDelete) {
if (!fileToDelete.isDirectory()) {
try {
if (fileToDelete.delete()) {
System.out.println("File delete operation success");
}
else {
System.out.println("File delete operation failed");
}
} catch (Exception ex) {
System.out.println("Exception :" + ex.getMessage());
}
} else {
System.out.println("It is not a file");
}
}
public class MyFile {
File file;
String fileName;
public MyFile(File file)
{
this.file = file;
this.fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
}
#Override
public String toString() {
return this.fileName;
}
}
}
I looking for help to list all files in Android external storage device. I want to look up in all the folders, including the subfolders for the main folder. Is there a way to this?
I have worked on a basic one, but I still haven't got the desired result. It doesn't work.
Here is my code:
File[] files_array;
files_array = new File(Environment.getExternalStorageDirectory().getAbsolutePath()).listFiles();
This method returns 0 size. What is the matter? This is my activity:
public class Main extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<File> files = getListFiles(Environment.getExternalStorageDirectory());
setListAdapter(new ArrayAdapter<File>(Main.this, android.R.layout.simple_list_item_1, files));
Toast.makeText(this, "" + files.size(), Toast.LENGTH_LONG).show();
}
private List<File> getListFiles(File parentDir) {
// On first call, parentDir is your sdcard root path
ArrayList<File> inFiles = new ArrayList<File>(); // Initialize an array list to store file names
File[] files = parentDir.listFiles(); // List all files in this directory
for (File file : files) {
if (file.isDirectory()) { // If the file is a directory
inFiles.addAll(getListFiles(file)); // *** Call this recursively to get all lower level files ***
}
}
return inFiles;
}
}
public void Search_Dir(File dir) {
String pdfPattern = ".pdf";
Log.d("check",
"Environment.getExternalStorageDirectory()------"
+ dir.getName());
File FileList[] = dir.listFiles();
Log.d("check",
"filelist length---- "
+ FileList.length);
if (FileList != null) {
for (int i = 0; i < FileList.length; i++) {
if (FileList[i].isDirectory()) {
Search_Dir(FileList[i]);
} else {
Log.d("check",
"for check from .pdf---- "
+ FileList[i].getName());
if (FileList[i].getName().endsWith(pdfPattern)) {
// here you have that file.
pdfArrayList.add(FileList[i].getPath());
}
}
}
}
}
Here is a solution found on the web:
public void walkdir(File dir) {
File[] listFile;
listFile = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().toLowerCase().endsWith(".pdf")) {
files_list.add(listFile[i]);
}
}
}
}
}
You actually only need calling the method above with the parent directory that you want to start with. I recommend to put Environment.getExternalStorageDirectory() in the parent directory so it will not change with different devices.
Conceptually, what you are doing is not complete. Your code only gives you a File for the root level directory. To determine all the files within this directory and the sub directories, you need recursive calls so that all the files are listed to the end of the folder levels.
private List<File> getListFiles(File parentDir) {
// On first call, parentDir is your sdcard root path
ArrayList<File> inFiles = new ArrayList<File>(); // initialize an array list to store file names
File[] files = parentDir.listFiles(); // list all files in this directory
for (File file : files) {
if (file.isDirectory()) { // if the file is a directory
inFiles.addAll(getListFiles(file)); // **CALL THIS RECURSIVELY TO GET ALL LOWER LEVEL FILES**
}
}
return inFiles;
}
Now call this function as:
getListFiles(Environment.getExternalStorageDirectory());
Now, you can add your ArrayList as a source to a List Control.
Bonus: If you would like to represent list the files in a tree like view, I would recommend you to look at https://code.google.com/p/tree-view-list-android/
Source:
List all the files from all the folder in a single list
Search all .pdf file present in the Android device
Try with this: The java.io package has been reimplemented within Android. You are able to use the same mechanisms in Android as you do in Java.
File fileList = new File("/sdcard"); // Path which you want to read
if (fileList != null) {
File[] files = fileList.listFiles();
for (File f : files) {
// Do something with the files
}
}
}
I used this code:
private File[] listOfDir;
/* ... */
TextView tv = (TextView) rootView.findViewById(R.id.textView1);
listOfDir = show();
String temp = "";
if (listOfDir != null) {
for (File i : listOfDir) {
temp += i.getName() + '\n';
}
} else {
temp = "null";
}
tv.setText(temp);
...
public File[] show() {
File[] dirs = null;
File dir = new File( /* Your path */ );
dirs = dir.listFiles();
return dirs;
}
And just call show to get list all the name.
I think this will help. First you need to fetch the contents of the SD card as shown below:
public class FileList extends ListActivity
{
private File file;
private List<String> myList;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd + "/external_sd");
File list[] = file.listFiles();
for(int i=0; i< list.length; i++)
{
myList.add(list[i].getName());
}
setListAdapter(new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
myList));
}
Now that you have all the files and folders from your sdcard in your listview, whenever, you go into a folder, then you need to fetch the contents of that folder as shown below:
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
File temp_file = new File(file, myList.get(position));
if(!temp_file.isFile())
{
file = new File(file, myList.get(position));
File list[] = file.listFiles();
myList.clear();
for(int i=0; i< list.length; i++)
{
myList.add(list[i].getName());
}
Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList));
}
}
And again on pressing back you need to load back the contents of your previous folder as shown below:
#Override
public void onBackPressed() {
String parent = file.getParent().toString();
file = new File(parent);
File list[] = file.listFiles();
myList.clear();
for(int i=0; i< list.length; i++)
{
myList.add(list[i].getName());
}
Toast.makeText(getApplicationContext(), parent, Toast.LENGTH_LONG).show();
setListAdapter(new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
myList));
I think this is what you need.
I wrote a tutorial on this a while ago and still use this from time to time. Have a look; you might find what you need.
playing-with-sdcard-in-android
Try this:
If you don't want the directory to be listed, put files.add(file1[i]); line in the else block:
public class MainActivity extends ListActivity {
ArrayList<File> files = new ArrayList<File>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File file[] = Environment.getExternalStorageDirectory().listFiles();
recursiveFileFind(file);
setListAdapter(new ArrayAdapter<File>(MainActivity.this,
android.R.layout.simple_list_item_1, files));
Toast.makeText(this, "" + files.size(), Toast.LENGTH_LONG).show();
}
public void recursiveFileFind(File[] file1) {
int i = 0;
String filePath = "";
if (file1 != null) {
while (i != file1.length) {
filePath = file1[i].getAbsolutePath();
files.add(file1[i]);
if (file1[i].isDirectory()) {
File file[] = file1[i].listFiles();
recursiveFileFind(file);
}
else{
}
i++;
Log.d(i + "", filePath);
}
}
}
}
I am trying to copy a file that is in a list of files. I want to copy the selected file when the user long clicks on the item in the list.
public class MainActivity extends ListActivity {
private File file;
private List<String> myList;
String rootsd = Environment.getExternalStorageDirectory().toString();
String old = "/Android/data/co.vine.android/cache/videos";
String dirNameSlash = "/videos/";
String path = Environment.getExternalStorageDirectory() + dirNameSlash;
String newDir = "/Saved";
String olddir2 = new String( rootsd + old );
String newdir2 = new String( rootsd + newDir);
File temp_dir = new File(newDir);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ListView lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) {
String item = (String) getListAdapter().getItem(row);
// CopyFile
Toast.makeText(getApplicationContext(), "File has been copied", Toast.LENGTH_LONG).show();
return true;
}
});
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("MyApp", "No SDCARD");
} else {
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Saved");
directory.mkdirs();
}
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/videos" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
setListAdapter(new ArrayAdapter<String>(this,
R.layout.row, myList ));
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String item = (String) getListAdapter().getItem(position);
Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW);
intentToPlayVideo.setDataAndType(Uri.parse(path + item), "video/*");
startActivity(intentToPlayVideo);
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
Any help would be great. All the files that the user selects will be saved to the same directory. I need help identifying what file the user selects, and then copy that. Thanks!
I recommend you use a FileChanel, is more efficient and fast. Example:
try {
String root_sd = Environment.getExternalStorageDirectory().toString();
String theFile = root_sd + "/" + (String) getListAdapter().getItem(row);
File file = new File(theFile);
FileInputStream source= new FileInputStream(file);
String targetDirectory = Environment.getExternalStorageDirectory().toString();
FileOutputStream destination = new FileOutputStream(targetDirectory + "/videos/" + file.getName);
FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();
long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);
} catch (Exception ex) {
Logger.getLogger(Borrar.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex)
{
//print in logcat
}
catch(IOException e)
{
//print in logcat
}
With a lot of help (on here) I've managed to nearly get my app up and running but I've got a problem. I'm basically a beginner in Java so this is a little deep for me, but I would still like some help. Basically the app displays a list of tones and lets you play them, if you touch and hold it inflates a context menu with an option to copy that selected tone to SD card.
The issue I know lies on the fourth-to-last line: boolean saved = saveas(sound.getSoundResourceId(),"filename"); because the variablesaved is not used.
I'm not too sure how to fix this,or what i should put in place of saved, just wondering if anyone on here has a clue?
Here's the full code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
this.getListView().setSelector(R.drawable.selector);
//create a simple list
mSounds = new ArrayList<Sound>();
Sound s = new Sound();
s.setDescription("Affirmative");
s.setSoundResourceId(R.raw.affirmative);
mSounds.add(s);
s = new Sound();
s.setDescription("Anjels");
s.setSoundResourceId(R.raw.anjels);
mSounds.add(s);
s = new Sound();
s.setDescription("Aggro");
s.setSoundResourceId(R.raw.aggro);
mSounds.add(s);
mSounds.add(s);
mAdapter = new SoundAdapter(this, R.layout.list_row, mSounds);
setListAdapter(mAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id){
Sound s = (Sound) mSounds.get(position);
MediaPlayer mp = MediaPlayer.create(this, s.getSoundResourceId());
mp.start();
}#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean saveas(int ressound, String fName){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="notifications/halon/";
String filename=fName+".ogg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String completePath = baseDir + File.separator + "music" + File.separator + "halon" + File.separator + filename;
boolean exists = (new File(completePath)).exists();
if (!exists){new File(completePath).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(completePath);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Sound sound = (Sound) getListAdapter().getItem(info.position);
int length = mSounds.size(); // get the length of mSounds object
String[] names = new String[length]; // creates a fixed array with strings
for(int i = 0; i < length; i++) {
// add sound name to string array
names[i] = mSounds.get(i).getDescription(); // returns the string name
}
switch(item.getItemId()) {
case R.id.copytosd:
Toast.makeText(this, "Applying " + getResources().getString(R.string.copy) +
" for " + names[(int)info.id],
Toast.LENGTH_SHORT).show();
boolean saved = saveas(sound.getSoundResourceId(),"filename");
return true;
default:
return super.onContextItemSelected(item);
}
}}
If you are not going to use saved, delete the boolean saved = from that statement and just have saveas(sound.getSoundResourceId(),"filename");.