Home > front end >  Saving and deleting file in Android Internal storage - deleting not working
Saving and deleting file in Android Internal storage - deleting not working

Time:11-19

I have been using this code to delete the file stored in internal storage. But the file isn't getting deleted.

editTextFileName = findViewById(R.id.editTextFileName);
    FileName = editTextFileName.getText().toString()   ".txt";
    buttonDeleteFile = findViewById(R.id.buttonDeleteFile);
    buttonDeleteFile.setOnClickListener(view -> {
        LayoutInflater layoutInflater = LayoutInflater.from(DeleteFile.this);
        View promptView = layoutInflater.inflate(R.layout.prompt, null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DeleteFile.this);
        alertDialogBuilder.setView(promptView);
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK", (dialog, id) -> {
                    Toast.makeText(this, "Deleting the file...", Toast.LENGTH_SHORT).show();
                    // get user input and set it to result
                    File dir = getFilesDir();
                    File file = context.getFileStreamPath(FileName);
                    if(file.exists()){
                        Toast.makeText(this, "temp" , Toast.LENGTH_SHORT).show();
                        try {
                            context.deleteFile(FileName);
                            Toast.makeText(this, "Successfully deleted", Toast.LENGTH_SHORT).show();
                        } catch (Exception e){
                            Toast.makeText(this, "Error "   e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                })

I am not able to figure out what the issue is.

CodePudding user response:

Try to use file.delete()

It should be definitely work.

CodePudding user response:

File dir = getFilesDir(); File file = context.getFileStreamPath(FileName);

You are not using dir.

File file = new File(dir, FileName);
  • Related