My app downloads files from the internet and I need the user to select where to save them. How to make a choice directory on the Android Java? Please give example code
You just need to override onCreateDialog in an activity like this:
//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";
private static final int DIALOG_LOAD_FILE = 1000;
private void loadFileList() {
try {
mPath.mkdirs();
}
catch(SecurityException e) {
Log.e(TAG, "unable to write on the sd card " + e.toString());
}
if(mPath.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
return filename.contains(FTYPE) || sel.isDirectory();
}
};
mFileList = mPath.list(filter);
}
else {
mFileList= new String[0];
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
switch(id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
if(mFileList == null) {
Log.e(TAG, "Showing file picker before loading the file list");
dialog = builder.create();
return dialog;
}
builder.setItems(mFileList, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChosenFile = mFileList[which];
//you can do stuff with the file here too
}
});
break;
}
dialog = builder.show();
return dialog;
}
Check this out :
small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: https://github.com/iPaulPro/aFileChooser
For More Details:
Android file chooser
Related
I am using many sample codes to make a simple new marker in mapsforge.
For example i have tried these samples:
https://www.programcreek.com/java-api-examples/?api=org.mapsforge.map.layer.overlay.Marker
or this one:
https://stackoverflow.com/a/27499732/5720180
But did not created.
Can anyone help me to create a marker on mapsforge offline map?
This is my using code:
createPositionMarker(35.6505667,51.4465217);
private void createPositionMarker(double paramDouble1, double paramDouble2){
final LatLong localLatLong = new LatLong(paramDouble1, paramDouble2);
org.mapsforge.core.graphics.Bitmap bmp = AndroidGraphicFactory.convertToBitmap(getResources().getDrawable(R.drawable.alerton150));
MarkerMapsForge positionmarker = new MarkerMapsForge(localLatLong,bmp,0,0 );
this.mapView.getLayerManager().getLayers().add(positionmarker);
}
public class MainActivity extends Activity {
private MyLocationNewOverlay mLocationOverlay;
private CompassOverlay mCompassOverlay;
// name of the map file in the external storage
private static final String MAP_FILE = "iran.map";
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidGraphicFactory.createInstance(this.getApplication());
this.mapView = new MapView(this);
setContentView(this.mapView);
this.mapView.setClickable(true);
this.mapView.getMapScaleBar().setVisible(true);
this.mapView.setBuiltInZoomControls(true);
this.mapView.setZoomLevelMin((byte) 6);
this.mapView.setZoomLevelMax((byte) 20);
// create a tile cache of suitable size
TileCache tileCache = AndroidUtil.createTileCache(this, "mapcache",
mapView.getModel().displayModel.getTileSize(), 1f,
this.mapView.getModel().frameBufferModel.getOverdrawFactor());
Log.i("LOGO", Environment.getExternalStorageDirectory().toString());
//ask for the permission in android M
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission to record denied");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Permission to access the SD-CARD is required for this app to Download PDF.")
.setTitle("Permission required");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.i(TAG, "Clicked");
makeRequest();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
makeRequest();
}
}
File test = new File(Environment.getExternalStorageDirectory(), "payam_directory");
if (!test.exists()) {
try {
if (test.mkdir()) {
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
// tile renderer layer using internal render theme
Configuration.getInstance().setUserAgentValue(getPackageName());
MapDataStore mapDataStore = new MapFile(new File(Environment.getExternalStorageDirectory() + "/payam_directory/" + MAP_FILE));
TileRendererLayer tileRendererLayer = new TileRendererLayer(tileCache, mapDataStore,
this.mapView.getModel().mapViewPosition, AndroidGraphicFactory.INSTANCE);
tileRendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
// only once a layer is associated with a mapView the rendering starts
this.mapView.getLayerManager().getLayers().add(tileRendererLayer);
this.mapView.setCenter(new LatLong(37.519101, 45.062364));
this.mapView.setZoomLevel((byte) 2);
Bitmap bitmap = AndroidGraphicFactory.convertToBitmap(getResources().getDrawable(R.drawable.m));
bitmap.incrementRefCount();
Marker marker = new Marker(new LatLong(37.519101, 45.062364), bitmap, 0, -bitmap.getHeight() / 2) {
#Override public boolean onTap(LatLong geoPoint, Point viewPosition, Point tapPoint) {
if (contains(viewPosition, tapPoint)) {
Toast.makeText(MainActivity.this, "Urmia, payamasli", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
};
mapView.getLayerManager().getLayers().add(marker);
}
protected void makeRequest() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
}
I am working on an app that allows user to select a file from external storage and send it using Android Beam.
Here is the FileBrowser Activity to select a file from a directory and return the file name and directory path back to main activity:
public class FileBrowser extends Activity {
private String root;
private String currentPath;
private ArrayList<String> targets;
private ArrayList<String> paths;
private File targetFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_browser);
getActionBar().setDisplayHomeAsUpEnabled(true);
root = "/";
currentPath = root;
targets = null;
paths = null;
targetFile = null;
showDir(currentPath);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_file_browser, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void selectDirectory(View view) {
File f = new File(currentPath);
targetFile = f;
//Return target File to activity
returnTarget();
}
public void setCurrentPathText(String message)
{
TextView fileTransferStatusText = (TextView) findViewById(R.id.current_path);
fileTransferStatusText.setText(message);
}
private void showDir(String targetDirectory){
setCurrentPathText("Current Directory: " + currentPath);
targets = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(targetDirectory);
File[] directoryContents = f.listFiles();
if (!targetDirectory.equals(root))
{
targets.add(root);
paths.add(root);
targets.add("../");
paths.add(f.getParent());
}
for(File target: directoryContents)
{
paths.add(target.getPath());
if(target.isDirectory())
{
targets.add(target.getName() + "/");
}
else
{
targets.add(target.getName());
}
}
ListView fileBrowserListView = (ListView) findViewById(R.id.file_browser_listview);
ArrayAdapter<String> directoryData = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, targets);
fileBrowserListView.setAdapter(directoryData);
fileBrowserListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos,long id) {
File f = new File(paths.get(pos));
if(f.isFile())
{
targetFile = f;
returnTarget();
//Return target File to activity
}
else
{
//f must be a dir
if(f.canRead())
{
currentPath = paths.get(pos);
showDir(paths.get(pos));
}
}
}
});
}
public void returnTarget()
{
Intent returnIntent = new Intent();
returnIntent.putExtra("file", targetFile);
returnIntent.putExtra("path", currentPath);
setResult(RESULT_OK, returnIntent);
finish();
}
}
Here is the code for MainActivity where the file returned by FileBrowser Activity is send using android beam:
public class MainActivity extends Activity {
private NfcAdapter nfcAdapter;
public final int fileRequestID = 98;
String name;
String[] extension={".png",".docx",".jpeg",".pdf",".doc"};
ArrayList <String>supportedExtension=new ArrayList<String>(Arrays.asList(extension));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PackageManager pm = this.getPackageManager();
// Check whether NFC is available on device
if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC)) {
// NFC is not available on the device.
Toast.makeText(this, "The device does not has NFC hardware.",
Toast.LENGTH_SHORT).show();
}
// Check whether device is running Android 4.1 or higher
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
// Android Beam feature is not supported.
Toast.makeText(this, "Android Beam is not supported.",
Toast.LENGTH_SHORT).show();
}
else {
// NFC and Android Beam file transfer is supported.
Toast.makeText(this, "Android Beam is supported on your device.",
Toast.LENGTH_SHORT).show();
}
}
public void browseForFile(View view) {
Intent clientStartIntent = new Intent(this, FileBrowser.class);
startActivityForResult(clientStartIntent, fileRequestID);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//fileToSend
boolean filePathProvided;
File fileToSend;
if (resultCode == Activity.RESULT_OK && requestCode == fileRequestID) {
//Fetch result
File targetDir = (File) data.getExtras().get("file");
String path = (String)data.getExtras().get("path");
Log.i("Path=",path);
if(targetDir.isFile())
{
if(targetDir.canRead()) {
try{
String ext=targetDir.getName().substring(targetDir.getName().lastIndexOf("."));
if (supportedExtension.contains(ext)) {
fileToSend = targetDir;
filePathProvided = true;
setTargetFileStatus(targetDir.getName() + " selected for file transfer");
Button btn = (Button) findViewById(R.id.send);
btn.setVisibility(View.VISIBLE);
name = targetDir.getName();
}
else{
Toast.makeText(getApplicationContext(), "File with this extension cannot be printed",
Toast.LENGTH_LONG).show();
}
}catch (Exception e){e.printStackTrace();}
}
else
{
filePathProvided = false;
setTargetFileStatus("You do not have permission to read the file " + targetDir.getName());
}
}
else
{
filePathProvided = false;
setTargetFileStatus("You may not transfer a directory, please select a single file");
}
}
}
public void setTargetFileStatus(String message)
{
TextView targetFileStatus = (TextView) findViewById(R.id.selected_filename);
targetFileStatus.setText(message);
}
public void sendFile(View view) {
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
// Check whether NFC is enabled on device
if(!nfcAdapter.isEnabled()){
Toast.makeText(this, "Please enable NFC.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
else if(!nfcAdapter.isNdefPushEnabled()) {
Toast.makeText(this, "Please enable Android Beam.",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(Settings.ACTION_NFCSHARING_SETTINGS));
}
else {
Uri[] mFileUris = new Uri[1];
String fileName=name;
// Retrieve the path to the user's public pictures directory
File fileDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File fileToTransfer;
fileToTransfer = new File(fileDirectory, fileName);
fileToTransfer.setReadable(true, false);
mFileUris[0] = Uri.fromFile(fileToTransfer);
nfcAdapter.setBeamPushUris(mFileUris, this);
}
}
}
Now, as you can see in my MainActivity, I am setting my directory as Pictures.
File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
My question is How can I dynamically change my directory every time based on the actual directory value obtained from FileBrowser Activity?
I have already went through the android documentation of How to send files using Android Beam, but didn't find it much useful for my problem. I also went through the android documentation of Environment, but couldn't understand much.
Any help regarding this will really be appreciated. Thanks in advance!
You already have the file selected in OnActivityResult method. Just change
mFileUris[0] = Uri.fromFile(fileToTransfer);
to
mFileUris[0] = Uri.fromFile(targetDir);
This question might have been asked several times (about returning value from alert dialog) but i just couldn't get this thing to work (the flow in android application was fine but it just couldn't save the data to the excel files), I've tried several methods posted in SO but still no luck and in a deep frustration atm.
I have some suspicion though. I think it's because i accessed both etOne and etTwo from within the inner class that makes it somewhat unreadable?
The snippet of my code:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Enter the data below");
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialog = inflater.inflate(R.layout.alertdialog, null);
//I think the problem comes from here?
final EditText etOne = (EditText) dialog.findViewById(R.id.etOne);
final EditText etTwo = (EditText) dialog.findViewById(R.id.etTwo);
//----------------------------------------------------------------
alertDialog.setView(dialog)
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Save One and Two to excel file
try {
FileInputStream file;
HSSFWorkbook workbook;
file = new FileInputStream(new File(fileName));
workbook = new HSSFWorkbook(file);
HSSFSheet sheet2 = workbook.getSheetAt(2);
int row;
Cell cell;
row = ((KaryawanActivity) getActivity()).position;
cell = sheet2.getRow(row).getCell(1);
cell.setCellValue(etOne.getText().toString());
cell = sheet2.getRow(row).getCell(2);
cell.setCellValue(etTwo.getText().toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Open Semasa Activity
Intent intent = new Intent(getActivity().getBaseContext(), SemasaActivity.class);
intent.putExtra("filepath", fileName);
intent.putExtra("evaluator", evaluator);
intent.putExtra(THEME, theme);
intent.putExtra("KaryawanNo", KaryawanNo);
intent.putExtra("KaryawanPos", ((KaryawanActivity) getActivity()).position);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialog.show();
Thanks in advance.
Ah forget it, it's my own mistake anyway. I forgot to set the write the workbook of course it'll never save. My bad -_-
For those who need it, the complete code goes this way, and accessing the EditText from within inner class is doable (although i doubt this is a good way of doing it).
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Enter the data below");
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialog = inflater.inflate(R.layout.alertdialog, null);
//I think the problem comes from here?
final EditText etOne = (EditText) dialog.findViewById(R.id.etOne);
final EditText etTwo = (EditText) dialog.findViewById(R.id.etTwo);
//----------------------------------------------------------------
alertDialog.setView(dialog)
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Save One and Two to excel file
try {
FileInputStream file;
HSSFWorkbook workbook;
file = new FileInputStream(new File(fileName));
workbook = new HSSFWorkbook(file);
HSSFSheet sheet2 = workbook.getSheetAt(2);
int row;
Cell cell;
row = ((KaryawanActivity) getActivity()).position;
cell = sheet2.getRow(row).getCell(1);
cell.setCellValue(etOne.getText().toString());
cell = sheet2.getRow(row).getCell(2);
cell.setCellValue(etTwo.getText().toString());
file.close();
FileOutputStream outFile = new FileOutputStream(new File(fileName));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Open Semasa Activity
Intent intent = new Intent(getActivity().getBaseContext(), SemasaActivity.class);
intent.putExtra("filepath", fileName);
intent.putExtra("evaluator", evaluator);
intent.putExtra(THEME, theme);
intent.putExtra("KaryawanNo", KaryawanNo);
intent.putExtra("KaryawanPos", ((KaryawanActivity) getActivity()).position);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialog.show();
I have an application that saves data to a file called 'sensorLog.txt'. I am not sure where exactly this is stored but I know this is only accessible by the applicationand it is in the internal memory.
I want to be able to write a copy the current file to an external storage when I click on a button "export". I have pasted a small bit of my program, But i am not sure how to copy sensorLog.txt file to the external storage.
public class MainActivity extends Activity {
private static final String DEBUG_TAG = "MainActivity";
private Button buttonStartService;
private Button buttonStopService;
private Button buttonSettings;
private Button buttonExport;
private TextView textStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
setContentView(R.layout.activity_main);
buttonStartService = (Button) findViewById(R.id.button_start_service);
buttonStopService = (Button) findViewById(R.id.button_stop_service);
buttonSettings = (Button) findViewById(R.id.button_settings);
buttonExport = (Button) findViewById(R.id.button_export);
textStatus = (TextView) findViewById(R.id.text_status);
buttonStartService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startSensorService();
}
});
buttonStopService.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopSensorService();
}
});
//export button listener
buttonExport.setOnClickListener(export_handler);
}
public void startSensorService() {
// Schedule
AlarmManager scheduler = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), SensorService.class);
PendingIntent scheduledIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 30 seconds
long interval = 30 * 1000;
scheduler.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, scheduledIntent);
Log.d(DEBUG_TAG, "Service started");
}
public void stopSensorService() {
// Cancel
AlarmManager scheduler = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, SensorService.class);
PendingIntent scheduledIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
scheduler.cancel(scheduledIntent);
Log.d(DEBUG_TAG, "Service stopped");
}
View.OnClickListener export_handler = new View.OnClickListener() {
public void onClick(View v)
{
// Here is the part I am not sure what to do. I want to copy a file sensorLog.txt that has all my sensor information to sd card
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
Log.d(DEBUG_TAG, "SD card detected");
stopSensorService();
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS),"SensorLog.txt");
// delete file from the internal storage once exported
context.deleteFile("SensorLog.txt");
startSensorService();
}
else
{
Log.d(DEBUG_TAG, "No external storage detected(cannot copy file)");
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Part where I create sensorLog.txt***(I dont think it is necessary to read for this question but just in case someone needs it)*:
private class SensorServiceLoggerTask extends AsyncTask<SensorFrame, Void, Void> {
#Override
protected Void doInBackground(SensorFrame... frames) {
SensorFrame frame = frames[0];
BufferedWriter bufWr = null;
try {
File file = new File(getApplicationContext().getFilesDir(), "SensorLog.txt");
if (file.exists()) {
// Write to new file
bufWr = new BufferedWriter(new FileWriter(file, true));
} else {
file.createNewFile();
Log.d(DEBUG_TAG, "New log file created");
// Append to existing file
bufWr = new BufferedWriter(new FileWriter(file, false));
// Write header
bufWr.append(sensorHeader.toString());
}
// Write frame
bufWr.append(sensorFrame.toString());
bufWr.flush();
Log.d(DEBUG_TAG, "Added frame to log");
} catch (IOException ex) {
// TODO: useful error handling
} finally {
// Cleanup
if (bufWr != null) {
try {
bufWr.close();
} catch (IOException ex) {
// TODO: useful error handling
}
}
}
return null;
}
}
I also have 2 more queries:
Lets say I want to append some information at the top of the file just before moving it how can I do that?
My aim is to transfer the sensorLog.txt file from internal to external storage when the export button is pressed. delete or empty the internal sensorLog.txt file and then the same thing happens again if i press export again, then I would have to rename my file when I export it right? would there not be a name clash? How do I handle that? could I give a name dynamically?
Thank you.
EDIT: Some corrections
View.OnClickListener export_handler = new View.OnClickListener() {
public void onClick(View v)
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
Log.d(DEBUG_TAG, "SD card detected");
stopSensorService();
Log.d(DEBUG_TAG, "stopSensorService for file transfer");
//make the timestamp the file name
long TS = System.currentTimeMillis();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(TS);
stringBuilder.append(".txt");
String file_name = stringBuilder.toString();
//file name stored in file_name
File file_ext = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS),file_name);
// attempt to create this new directory
//read from sensorLog.txt file
try
{
file_ext.createNewFile();
File file = getBaseContext().getFileStreamPath("sensorLog.txt");
if(file.exists())
{
FileInputStream read_file = openFileInput("sensorLog.txt");
//read contents of internal file
InputStreamReader inputStreamReader = new InputStreamReader(read_file);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
sb.append("Timestamp of export to SD"+TS+"/n");
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
BufferedWriter bufWr = null;
bufWr = new BufferedWriter(new FileWriter(file_ext, false));
// Write header
bufWr.append(sb.toString());
inputStreamReader.close();
bufWr.close();
read_file.close();
//delete sensor file once exported
getApplicationContext().deleteFile("sensorLog.txt");
}
}
catch(Exception e){}
But for some reason my file is not getting stored in the SD card.
Check out the Android documentation. If you can read your sensorLog.txt file, then you can save it in a String and then save the string to a file in the external storage.
I have a file list with a longclicklistener that brings up a context menu with delete and rename options. These launch either a deleteDialog() or renameDialog(). These call either delete() or rename(). The delete works but rename is giving:
05-05 10:26:44.105: W/System.err(19017884): java.io.FileNotFoundException: Failed to rename file: /sdcard/My Webs/new/index.php
Even thought I can see this file on the filesystem at this location.
Here is my code for the Alerts:
void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
delete(c);
}
if (!f.delete())
throw new FileNotFoundException("Failed to delete file: " + f);
}
void rename(File f, String newName) throws IOException {
File newFile = new File(newName);
f.renameTo(newFile);
if (!f.renameTo(newFile))
throw new FileNotFoundException("Failed to rename file: " + f);
}
public void delDialog(int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.drawable.remove);
alertDialog.setTitle(getString(R.string.delete));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String selectedFileString = directoryEntries.get(pos).getText();
File tmpFile = new File(currentDirectory.toString()
+ selectedFileString);
try {
delete(tmpFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
directoryEntries.remove(pos);
itla.notifyDataSetChanged();
currentFile = null;
changed = false;
return;
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage("Are you sure you want to delete this file?");
alertDialog.show();
}
public void renameDialog(int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.drawable.renameicon);
alertDialog.setTitle(getString(R.string.rename));
alertDialog.setButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String selectedFileString = directoryEntries.get(pos).getText();
File tmpFile = new File(currentDirectory.toString()
+ selectedFileString);
try {
rename(tmpFile, "test.html");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
itla.notifyDataSetChanged();
return;
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage("Are you sure you want to rename this file?");
alertDialog.show();
}
public void Show_Context(Context context, String message, int position) {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.contextmenu, null);
final Button del = (Button) view.findViewById(R.id.delBtn);
final Button rename = (Button) view.findViewById(R.id.renameBtn);
final int pos = position;
customDialog.setView(del);
customDialog.setView(rename);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
delDialog(pos);
}
});
rename.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
renameDialog(pos);
}
});
customDialog.setView(view);
customDialog.show();
}
As you can see the code for the deleteDialog() and renameDialog() is the same yet the renameDialog() throws the FileNotFoundException
Have you tried fully qualifying the filename of the destination? You're currently attempting to rename to "test.html" from currentDirectory.toString()+selectedFileString.
You probably want to try currentDirectory.toString()+"test.html" as you might be running into permissions issues otherwise.
You call f.renameTo(newFile) two times! One time normally, and a second time within the if() condition. I guess it already gets renamed the first time, so when you do it a second time, it fails (either because the file doesn't have the same name anymore or because it already has the new filename).
f.renameTo(newFile);
if (!f.renameTo(newFile)) {...}
Try and remove the first .f.renameTo().
Also note, that renameTo() returning false can have all kinds of reasons, not just that the file cannot be found. And of course you get the FileNotFoundException because you throw it yourself in your code :-)