Android java : delete selected file / folder - java

How to delete the selected file / folder by using long pressed ?
I'm developing an File Explorer app and there are listed folder and file from my storage.
I want to have a delete function for the longpressed().
public void longpressed(){
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
new AlertDialog.Builder(ViewNoteActivity.this , AlertDialog.THEME_HOLO_DARK)
.setTitle("Delete Folder / File")
.setMessage("Are you sure you want to delete the selected folder / file ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which ) {
boolean success = true;
if (success) {
Toast.makeText(getBaseContext(), "You have successfully delete." , Toast.LENGTH_SHORT ).show();
} else {
Toast.makeText(getBaseContext(), "You have Failed to delete." , Toast.LENGTH_SHORT ).show();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(R.drawable.ic_launcher)
.show();
return true;
}
});
}
item select coding:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
FileInfo fileDescriptor = fileArrayListAdapter.getItem(position);
if (fileDescriptor.isFolder() || fileDescriptor.isParent()) {
currentFolder = new File(fileDescriptor.getPath());
fill(currentFolder);
} else {
fileSelected = new File(fileDescriptor.getPath());
Intent intent = new Intent();
intent.putExtra(Constants.KEY_FILE_SELECTED,
fileSelected.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
Log.i("FILE CHOOSER", "result ok");
}
}

See the File class API reference.
To delete a file:
new File(path).delete()
To delete a folder:
private void deleteFolderRecursive(File dir) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteFolderRecursive(file);
} else {
file.delete();
}
}
}
dir.delete();
}

Do this:
File dir =new File(getActivity().getApplicationContext().getFilesDir()+"/YourFOlderName");
boolean success = deleteDir(dir);
Where:
getActivity().getApplicationContext().getFilesDir()+"/YourFOlderName"
is the path to the folder.
And:
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
The above will delete all the children inside the directory.
if your folder is on the External SD Card the path should be mounted like:
Never hardcode the sdcard, you must use
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
will let you know if the memory is loaded. Then use:
Environment.getExternalStorageDirectory().getAbsolutePath()

Related

How can save call History in phone storage?like as a backup

I want to make a calls log backup and recovery Application.
I have done some initial work. like call the CallLog API and show in ListView. but now How can save in internal or external storage.after that we can recover this call history through theses backup file.
enter image description here enter code here
enter image description here
public class Backup_Activity extends AppCompatActivity {
private static final int READ_LOGS = 725;
private ListView logList;
private Runnable logsRunnable;
private String[] requiredPermissions = {Manifest.permission.READ_CALL_LOG, Manifest.permission.READ_CONTACTS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_backup);
logList = findViewById(R.id.listview_id);
logsRunnable = new Runnable() {
#Override
public void run() {
loadLogs();
}
};
// Checking for permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermissionToExecute(requiredPermissions, READ_LOGS, logsRunnable);
} else {
logsRunnable.run();
}
}
// This is to be run only when READ_CONTACTS and READ_CALL_LOG permission are granted
private void loadLogs() {
LogsManager logsManager = new LogsManager(this);
List<LogObject> callLogs = logsManager.getLogs(LogsManager.ALL_CALLS);
LogsAdapter logsAdapter = new LogsAdapter(Backup_Activity.this, R.layout.log_layout, callLogs);
logList.setAdapter(logsAdapter);
}
// A method to check if a permission is granted then execute tasks depending on that particular permission
#TargetApi(Build.VERSION_CODES.M)
private void checkPermissionToExecute(String permissions[], int requestCode, Runnable runnable) {
boolean logs = ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED;
boolean contacts = ContextCompat.checkSelfPermission(this, permissions[1]) != PackageManager.PERMISSION_GRANTED;
if (logs || contacts) {
requestPermissions(permissions, requestCode);
} else {
// runnable.run();
}
}
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == READ_LOGS && permissions[0].equals(Manifest.permission.READ_CALL_LOG) && permissions[1].equals(Manifest.permission.READ_CONTACTS)) {
if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED && grantResults[1] == PermissionChecker.PERMISSION_GRANTED) {
logsRunnable.run();
} else {
new AlertDialog.Builder(Backup_Activity.this)
.setMessage("The app needs these permissions to work, Exit?")
.setTitle("Permission Denied")
.setCancelable(false)
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
checkPermissionToExecute(requiredPermissions, READ_LOGS, logsRunnable);
}
})
.setNegativeButton("Exit App", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).show();
}
}
}
public void backup(View view) {
LogsManager logsManager = new LogsManager(this);
List<LogObject> callLogs = logsManager.getLogs(LogsManager.ALL_CALLS);
LogsAdapter logsAdapter = new LogsAdapter(Backup_Activity.this, R.layout.log_layout, callLogs);
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + "/text/");
dir.mkdir();
File file = new File(dir, "back up calls log.VCF");
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(logsAdapter.toString().getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();}
}}
class LogsAdapter extends ArrayAdapter<LogObject> {
List<LogObject> logs;
Context context;
int resource;
public LogsAdapter(Context context, int resource, List<LogObject> callLogs) {
super(context, resource, callLogs);
this.logs = callLogs;
this.context = context;
this.resource = resource;
}
#Override
public Context getContext() {
return context;
}
#Override
public int getCount() {
return logs.size();
}
#Override
public LogObject getItem(int position) {
return logs.get(position);
}
#Override
#SuppressLint("ViewHolder")
#RequiresPermission(Manifest.permission.READ_CONTACTS)
public View getView(int position, View convertView, ViewGroup parent) {
View row = LayoutInflater.from(getContext()).inflate(resource, parent, false);
TextView phone = (TextView) row.findViewById(R.id.number_id);
TextView name=row.findViewById(R.id.name_id);
TextView duration = (TextView) row.findViewById(R.id.call_duration);
TextView date = (TextView) row.findViewById(R.id.call_time);
// ImageView profileView=row.findViewById(R.id.profile_id);
ImageView imageView = (ImageView) row.findViewById(R.id.calls_image_id);
LogObject log = getItem(position);
Date date1 = new Date(log.getDate());
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.ERA_FIELD, DateFormat.SHORT);
name.setText(log.getContactName());
phone.setText(log.getNumber());
duration.setText(log.getCoolDuration());
date.setText(dateFormat.format(date1));
// profileView.setImageResource(log.getDuration());
switch (log.getType()) {
case LogsManager.INCOMING:
imageView.setImageResource(R.drawable.received);
break;
case LogsManager.OUTGOING:
imageView.setImageResource(R.drawable.sent);
break;
case LogsManager.MISSED:
imageView.setImageResource(R.drawable.missed);
break;
default:
imageView.setImageResource(R.drawable.cancelled);
break;
}
return row;
}
}

Android DialogFramgment loads item from arrayList twice but only on Samsung

I am cleaning up some code where a DialogFrament i supposed to diaplay items from an ArrayList (ref. "arr" in the code) and then the user can choose severeal items from it and then hit OK. This work fine, no problemo. But, only on Samsung Phones, the DialogFrament lists the item from the ArrayList twice. so, on all the other phone the list displays the values arr[0]->arr[n] but on Samsung(again ONLY on Samsung) the values are arr[0]->arr[n] + arr[0]->arr[n]. Since it's the same code for all android phones but the problem only occurs on Samsung Phones, im out of ideas.
A quick google search pointed me towards a difference in layout rules by Samsung depending on the resolution of their phone but it seeamed unlikely.
Have any of you heard about this before?
CODE FOR MY FRAGMENT
public ArrayList mSelectedItems;
public int type;
public boolean single = false;
int count;
boolean search;
public int single_item = -1;
public interface CategoriesDialogFragmentListener {
public void onOkay(ArrayList items, int type);
public void onCancel();
public void onSingleOkay(int item, int type);
}
CategoriesDialogFragmentListener mListener;
public void setType(int type_id) {
/*
1 = Category
2 = Genre
3 = Availability
*/
type = type_id;
}
public void setSearch(boolean isSearch) {
search = isSearch;
}
public void setList(ArrayList temp) {
mSelectedItems = temp;
}
public void isSingle(boolean is_single){
single = is_single;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (CategoriesDialogFragmentListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
CharSequence[] arr;
String title;
switch(type){
case 1:
title = "Välj kategori";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
single = true;
break;
case 2:
title = "Välj genre";
arr = MainActivity.GENRE_STRINGS.toArray(new CharSequence[MainActivity.GENRE_STRINGS.size()]);
single = false;
break;
case 3:
title = "Välj tillgängligheter";
arr = MainActivity.AVAIL_STRINGS.toArray(new CharSequence[MainActivity.AVAIL_STRINGS.size()]);
single = false;
break;
default:
title = "ett fel uppstod";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
}
if(!single) {
if(type == 2 && search == false) {
count = 0;
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
//Kod för att starta fragment med valda entiteter
/*
if(mSelectedItems != null || !mSelectedItems.isEmpty()){
for(Object e : mSelectedItems){
}
}
*/
if (isChecked) {
if (count < 5) {
mSelectedItems.add(which);
count++;
} else {
new android.app.AlertDialog.Builder(getActivity())
.setTitle(R.string.five)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
count--;
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}else{
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}
} else {
builder.setTitle(title).setSingleChoiceItems(arr, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
single_item = item;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onSingleOkay(single_item, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});;
}
return builder.create();
}
}

Android java :Passing with the path between two activity

I'm new in android developing and currently develop an CalendarNote app.
By pick the date to create a folder and the folder name is the date.
After pick the date and successfully created the date folder move to
text interface.
create folder and text interface are two different activity.
Now, the problem is I want to save the txt file to the folder that
I just created.
I try to getText from the date I picked to the text activity, but
not successful.
I did a lot of research and tried a lot related code, still not success.
Anyone can please help me or give me some guide so that I won't lost . Thanks.
The following bellow is the create folder code:
btn_cFolder.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String dateN = edit_date.getText().toString();
new AlertDialog.Builder(DatePickerActivity.this, AlertDialog.THEME_HOLO_DARK)
.setTitle("Create Folder")
.setMessage("Confirm to create " + dateN +" folder ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Environment.getExternalStorageDirectory();
String dateN = edit_date.getText().toString();
edit_date.setTypeface(edit_date.getTypeface(), Typeface.BOLD_ITALIC);
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CalendarNote/" + dateN);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Toast.makeText(getBaseContext(), "You have successfully created." , Toast.LENGTH_LONG ).show();
Intent w = new Intent(DatePickerActivity.this, SelectTypeActivity.class);
startActivity(w);
} else {
Toast.makeText(getBaseContext(), "You have Failed to create." , Toast.LENGTH_LONG ).show();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
});
And this is the create txt file code:
public void SaveListener() {
imb_savefile = (ImageButton) findViewById(R.id.imb_savefile);
imb_savefile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
edit_date = (EditText) findViewById(R.id.edit_date);
String t = edit_title.getText().toString();
new AlertDialog.Builder(WriteNoteActivity.this, AlertDialog.THEME_HOLO_DARK)
.setTitle("Save Note")
.setMessage("Confirm to save " + t +"?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String content = edit_content.getText().toString();
String title = edit_title.getText().toString();
String dateN = edit_date.getText().toString();
boolean success = true;
try {
File sdCardDir = Environment.getExternalStorageDirectory();
File targetFile;
targetFile = new File(sdCardDir.getCanonicalPath()
+ "/CalendarNote/"+ dateN);
File file=new File(targetFile + "/"+title+".txt");
if(!targetFile.exists()){
success = targetFile.mkdir();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(file.length());
raf.write(content.getBytes());
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getBaseContext(), "You have successfully created." , Toast.LENGTH_LONG ).show();
} else {
Toast.makeText(getBaseContext(), "You have Failed to create." , Toast.LENGTH_LONG ).show();
}
//Toast.makeText(getBaseContext(), "Note have successfully saved." , Toast.LENGTH_LONG ).show();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "Note Cancelled." , Toast.LENGTH_LONG ).show();
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
});
}
The dateN is the key to create folder .
[Updateted 15/3/2014]
Hi actually after pick the date (DatePickerActivity) >> select type of note (SelectTypeActivity) >> write the txt file (WriteNoteActivity). This is the process. So far i use #Hamid Shatu suggestion this is really helpful ! But I have to change the intent SelectTypeActivity.class to WriteNoteActivity.class like this it will success, how can I no need to skip the SelectTypeActivity also able to do that ? =)
Sorry for my broken English.
Pass your folder path to SelectTypeActivity through putExtra() method of Intent as below...
String folderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CalendarNote/" + dateN;
File folder = new File(folderPath);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Toast.makeText(getBaseContext(), "You have successfully created." , Toast.LENGTH_LONG ).show();
Intent w = new Intent(DatePickerActivity.this, SelectTypeActivity.class);
w..putExtra("folderpath", folderPath);
startActivity(w);
} else {
Toast.makeText(getBaseContext(), "You have Failed to create." , Toast.LENGTH_LONG ).show();
}
Retrieve that folder path from Extra using getStringExtra() method in SelectTypeActivity class as below...
//File sdCardDir = Environment.getExternalStorageDirectory();
//File targetFile;
//targetFile = new File(sdCardDir.getCanonicalPath()
+ "/CalendarNote/"+ dateN);
String folderPath = getIntent().getStringExtra("folderpath");
File file=new File(folderPath + "/"+title+".txt");

Android java : How to auto refresh list view

I currently develop a File Explorer app and I need to have a auto refresh for my listview.
Because when I delete the item I still can see the item , I need to back the folder and go inside the folder again only see it disappear. How to auto refresh so when I deleted the item it disappear itself.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
FileInfo fileDescriptor = fileArrayListAdapter.getItem(position);
if (fileDescriptor.isFolder() || fileDescriptor.isParent()) {
currentFolder = new File(fileDescriptor.getPath());
fill(currentFolder);
//
} else {
fileSelected = new File(fileDescriptor.getPath());
Intent intent = new Intent();
intent.putExtra(Constants.KEY_FILE_SELECTED,
fileSelected.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
Log.i("FILE CHOOSER", "result ok");
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(fileSelected.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null){
type = "*/.jpeg*";
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileSelected), "image/*");
// intent.setDataAndType(data, type);
}else {
type = "*/.txt*";
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileSelected), "text/*");
// intent.setDataAndType(data, type);
}
//finish();
// intent.setAction(android.content.Intent.ACTION_VIEW);
startActivity(intent);
// Intent intent = new Intent();
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
new AlertDialog.Builder(ViewNoteActivity.this) .setTitle("Delete File")
.setMessage("Do You Want To Delete this file ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int button){
fileSelected.delete();
Toast.makeText(getBaseContext(), "File has been deleted." , Toast.LENGTH_SHORT ).show();
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int button){
}
}).show();
return true;
}
});
}
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
Delete item from the datasource that populates listview and call notifyDataSetChanged on the adapter to refresh listView
You need to delete ListItem from ArrayList from Adapter and call notifyDatasetChanged() ,
When you call notifyDatasetChanged() method it will refresh your listview with ArrayList with updated data so, you have to first delete item from ArrayList onClick of Delete Button.
And then you have to call notifyDatasetChanged().

How can I fix my save function? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have an file list and when a file is clicked its contents are displayed in an EditText. That file is set as currentFile. If the user tries to open a new file before saving the old one they are shown a save dialog. The OK button on the dialog should save the current working file but instead saves it as the file the user is trying to open. Where is the problem in my code that's causing the currentfile to be saved over the new one trying to be opened.
public boolean exists;
public File currentFile;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
et = (EditTextLineNumbers) findViewById(R.id.ide);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
File dir = new File(Environment.getExternalStorageDirectory() + "/My Webs");
currentDirectory = dir;
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
changed = false;
}
#Override
public void afterTextChanged(Editable s) {
changed=true;
}
});
changed=false;
if(dir.isDirectory()) {
browseToRoot();
}else{
dir.mkdir();
}
}
private void openFile(File aFile){
String nullChk = et.getText().toString();
exists = true;
currentFile = aFile;
if(!changed || nullChk.matches("")){
try {
et.setText(new Scanner(aFile).useDelimiter("\\Z").next());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save first?");
alert.setMessage("(Will be saved in the current working directory)");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String temptxt = et.getText().toString();
if(exists){
saveFile(currentFile.getPath(), temptxt);
}else{
saveAs();
}
}
});
final File tempFile = aFile;
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
et.setText(new Scanner(tempFile).useDelimiter("\\Z").next());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
changed=false;
}
});
alert.show();
}
}
private void saveFile(String sFileName, String sBody){
//Toast.makeText(this, exists +"", Toast.LENGTH_SHORT).show();
if (exists) {
try {
File tempfile = new File(sFileName);
FileWriter writer = new FileWriter(tempfile);
writer.write(sBody);
writer.flush();
writer.close();
changed=false;
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
}
}else{
Toast.makeText(this, "Save as", Toast.LENGTH_SHORT).show();
saveAs();
}
}
private void saveAs(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save as");
alert.setMessage("(Will be saved in the current working directory)");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
String tmpText = et.getText().toString();
try {
File tempfile = new File(currentDirectory, value);
FileWriter writer = new FileWriter(tempfile);
writer.write(tmpText);
writer.flush();
writer.close();
changed=false;
//itla.notifyDataSetChanged();
fill(currentDirectory.listFiles());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
/**
* This function browses up one level
* according to the field: currentDirectory
*/
private void upOneLevel(){
if(this.currentDirectory.getParent() != null && !this.currentDirectory.getPath().equals("/sdcard/My Webs")){
this.browseTo(this.currentDirectory.getParentFile());
}else{
//Do nothing
}
}
private void browseTo(final File aDirectory){
// On relative we display the full path in the title.
if(this.displayMode == DISPLAYMODE.RELATIVE)
this.setTitle(aDirectory.getAbsolutePath() + " :: " +
getString(R.string.app_name));
if (aDirectory.isDirectory()){
this.currentDirectory = aDirectory;
fill(aDirectory.listFiles());
}else{
openFile(aDirectory);
}
changed=false;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String selectedFileString = this.directoryEntries.get(position)
.getText();
if (selectedFileString.equals(getString(R.string.current_dir))) {
// Refresh
this.browseTo(this.currentDirectory);
} else if (selectedFileString.equals(getString(R.string.up_one_level))) {
this.upOneLevel();
} else {
File clickedFile = null;
switch (this.displayMode) {
case RELATIVE:
clickedFile = new File(this.currentDirectory
.getAbsolutePath()
+ this.directoryEntries.get(position)
.getText());
break;
case ABSOLUTE:
clickedFile = new File(this.directoryEntries.get(
position).getText());
break;
}
if (clickedFile != null)
currentFile=clickedFile;
this.browseTo(clickedFile);
}
}
}
Third line of openFile(): you change currentFile before you conditionally ask the user if he wants to save currentFile before opening the new file. Change currentFile when you actually open another file, rather than before, and you won't have this problem even accidentally.

Categories

Resources