Search code examples
androidandroid-dialogandroid-file

Renaming a file in directory which is in android internal memory?


I have a some application specific file which are stored in a directory in internal memory.I want user to be able to rename these files through dialog box.I am using following code to rename a selected file by user:

final File dir = context.getDir(UtilityFuctions.USER_LISTS,
                Context.MODE_PRIVATE);
        final File myFile = new File(dir, filename);

        AlertDialog.Builder fileDialog = new AlertDialog.Builder(context);
        fileDialog.setTitle("Rename file");

        // Set an EditText view to get user input
        final EditText input = new EditText(context);
        input.setText(filename);
        fileDialog.setView(input);
        fileDialog.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String fileName = input.getText().toString();

                            myFile.renameTo(new File(dir,filename));
                            UtilityFuctions.createToast(context, "file rename successfully", 0);
                        }
                    }
                });
        fileDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                        dialog.dismiss();
                    }
                });
        fileDialog.create();
        fileDialog.show();

But the above code is not working and the file is not getting new name.I guess renameTo won't work for this, it will work only for externalmemory. I have a solution in which I can made a copy of exisiting file with new name and delete the old file but that will consume resources and I dont want to do that.Please help me if I am doing something wrong..


Solution

  • This should work - the issue you have created is you have TWO variables called filename and fileName.

    I'm pretty sure the basic problem is that you are want this line:

    myFile.renameTo(new File(dir,filename));
    

    to actually read

    myFile.renameTo(new File(dir,fileName));
    

    specifically you want to do the rename with the new returned file name (in the local fileName) as opposed to the original (unchanged) file name stored in filename.