Listed all audio files from gallery ,This is my code to rename and delete list of audio files.By using this code i can able to perform rename and delete operations on list only those are not effecting audio file,How to perform rename and delete operations on audio file in gallery based on my code ,i tried like this by using Filebut didn't work,id there any wrong in my code ,correct me plz
here is my code
Variables
ListView myList;
List values;
ArrayAdapter adapter;
MediaPlayerActivity mp = new MediaPlayerActivity();
Code to rename and delete by using contextmenu
case CONTEXT_MENU_DELETE:
Toast.makeText(
this,
"You selected item " + context_menu_number
+ " from the context menu", Toast.LENGTH_SHORT)
.show();
Toast.makeText(
this,
"You removed item " + number_of_item_in_listview
+ " from the list", Toast.LENGTH_SHORT).show();
values.remove(number_of_item_in_listview);
// myadapter.notifyDataSetChanged(); //if this does not work,
// reinitialize the adapter:
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
values);
myList.setAdapter(adapter);
File f = new File(path + filename);
if (f != null && f.exists()) {
// delete it
f.delete();
}
return (true);
case CONTEXT_MENU_RENAME:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("öğeyi yeniden adlandırmak");
alert.setMessage("Seçili öğe için yeni bir isim girin");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("tamam",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
values.set(number_of_item_in_listview, value
+ ".3gp");
adapter.notifyDataSetChanged();
/*
* File sdcard =
* Environment.getExternalStorageDirectory(); File
* from = new File(sdcard,"from.txt"); File to = new
* File(sdcard,"to.txt"); from.renameTo(to);
*/
File f = new File(path + filename);
if (f != null && f.exists()) {
File from = new File(f, f.getName());
File to = new File(f, value);
from.renameTo(to);
}
}
});
alert.setNegativeButton("iptal",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
Rename the files:
Its working fine:Put this code where you want to change the name.
File sdcard = new File(Environment.getExternalStorageDirectory(), "sample");
String fromFullPath = "/username556596268.mp3";
String toFullPath = "/username.mp3";
File from = new File(sdcard,fromFullPath);
File to = new File(sdcard,toFullPath);
from.renameTo(to);
here "sample" is my sdcard main directory name,"fromFullPath" is my filename it is in inside the sample directory, "toFullPath" is my changed name.
Delete the files:
Its working fine:Put this code where you want to delete file.
File sdcard = new File(Environment.getExternalStorageDirectory(), "sample");
String fromFullPath = "/username556596268.mp3";
File from = new File(sdcard,fromFullPath);
from.delete();
from.deleteOnExit();
Related
i am trying to save a file in the emulator with the name that choose it the user and the current date .
but i get an error message that say :open failed :EACCES (Permission denied )
how to fix this error i will appreciate any help
SingInSActivity.java
public class SignSoldgerActivity extends Activity {
EditText edit_txt_note;
final Context context = this;
// attribute for the date picker
public String fileName;
Button btn_save_soldger;
TextView txtatePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_soldger);
edit_txt_note = (EditText) findViewById(R.id.editTxtNote);
txtatePicker = (TextView) findViewById(R.id.txtDate);
btn_save_soldger = (Button) findViewById(R.id.btnSaveSoldger);
btn_save_soldger.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// / for creating a dialog
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
String userinputResult = userInput
.getText().toString();
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy/MM/dd_HH:mm:ss");
Date now = new Date();
fileName = formatter.format(now) + "__"
+ userinputResult;
txtatePicker.setText(fileName);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// / for saving the file on the SD
try {
String sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + fileName + ".txt";
File myFile = new File(sdPath);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
// append or write
myOutWriter.append(edit_txt_note.getText());
myOutWriter.close();
fOut.close();
edit_txt_note.setText("");
Toast.makeText(getBaseContext(),
"Done Writing SD" + fileName, Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
the permission is added in the
manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Emulator SD Card size should be defined
You need to edit your AVD to allot an SD card size to it. You need to launch the AVD Manager dor it of course.
Here's the screen where you add it:
Updating after to include your comments
You're mostly missing the path seperator.
String sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + fileName + ".txt";
must be changed to
String sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() +"/"+ fileName + ".txt";
Please add following in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Most likely you need to read as well so this is needed for that:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Also note that most likely SD card has different allowed characters so you might need to replace all "|\\?*<\":>+[]/'"; with wanted character like _
Here is my code to display all music file names in a list view ,here i am taking all files in an array list then displaying in a listview,by using contextmenu performing "rename" on listitems but these changes are not effecting actual file which is in sd card ,suggest me how to do this ,i tried file operations like this.
path = "/sdcard/";
if (getIntent().hasExtra("path")) {
path = getIntent().getStringExtra("path");
}
setTitle(path);
// Read all files sorted into the values-array
values = new ArrayList();
File dir = new File(path);
if (!dir.canRead()) {
setTitle(getTitle() + " (inaccessible)");
}
final String[] list = dir.list();
if (list != null) {
for (String file : list) {
if (file.contains(".3gp")) {
values.add(file);
}
}
}
Collections.sort(values);
// Put the data into the list
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2,
android.R.id.text1, values);
setListAdapter(adapter);
registerForContextMenu(myList);
}
final int CONTEXT_MENU_DELETE = 1;
final int CONTEXT_MENU_RENAME = 2;
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "silmek");
menu.add(Menu.NONE, CONTEXT_MENU_RENAME, Menu.NONE, "adını değiştirmek");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
Long id = myList.getAdapter().getItemId(info.position);
final int number_of_item_in_listview = Integer.valueOf(id.intValue());
final int context_menu_number = item.getItemId();
switch (item.getItemId()) {
This is how i am renaming file prgrammatically using contextmenu for listview
case CONTEXT_MENU_RENAME:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("öğeyi yeniden adlandırmak");
alert.setMessage("Seçili öğe için yeni bir isim girin");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("tamam",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
values.set(number_of_item_in_listview, value
+ ".3gp");
adapter.notifyDataSetChanged();
/*
* File sdcard =
* Environment.getExternalStorageDirectory(); File
* from = new File(sdcard,"from.txt"); File to = new
* File(sdcard,"to.txt"); from.renameTo(to);
*/
File f = new File(path + filename);
if (f != null && f.exists()) {
File from = new File(f, f.getName());
File to = new File(f, value);
from.renameTo(to);
}
}
});
alert.setNegativeButton("iptal",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
return (true);
}
return (super.onOptionsItemSelected(item));
I would recommend using File.renameTo() rather than running the mv command, since I'm fairly sure the latter isn't supported..
Have you given your application permission to write to the SD Card?
You do this by adding the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If it doesn't work once the permission is added check the device log for errors when you try to rename the file (either using the adb command or in the logcat view in Eclipse).
When accessing the SD Card you shouldn't hard-code the path but instead use the Environment.getExternalStorageDirectory() method to get the directory.
The following code works for me:
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);
I write an algorithm to rename a file, how can I print the current name in the input field?
final EditText input = new EditText(MainActivity.this);
new AlertDialog.Builder(MainActivity.this)
.setTitle("Rename")
.setMessage("Add new name:")
.setView(input)
.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
if (directory.isDirectory()) {
File from = new File(directory.getAbsolutePath());
File to = new File(directory.getParent() + "/" + value);
from.renameTo(to);
} else {
File from = new File(directory.getAbsolutePath());
File to = new File(directory.getParent() + "/" + value + "." + checkFormat);
from.renameTo(to);
}
go(currentDirectory);
}
}).setNegativeButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
I would greatly appreciate the help
If I understand correctly, this should work to put the old name in the input box.
File old = null;
if (directory.isDirectory()) {
old = new File(directory.getAbsolutePath());
}
final EditText input = new EditText(MainActivity.this);
input.setText(old.toString());
...
//the rest of your code
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();
}
};
this is my file browser code below when show files from sd card i put multiple apk files in sd card but this code just show apk files in sd card not install when click what do ido? please help me. i want to run apk files which show on listview but is not run how do i modify this code to run selected file??
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
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(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()){
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) {
// TODO Auto-generated method stub
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.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK", null).show();
}
}
}
Implement a ListView (follow this TUTORIAL).
Then implement a listener to handle the click on the items ( listView.onItemClickListener(); )
and then use the snipper below for the installation:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("file:///path/to/your.apk"))
.setType("application/vnd.android.package-archive");
startActivity(promptInstall);
ref: https://stackoverflow.com/a/4604922/847818
You have to go step-by-step.