Certainly! To continue building our Android file manager, we will:
- Implement the move functionality.
- Handle file renaming.
- Refactor code for better exception handling.
- Optimize the file copy operation to avoid UI thread blocking.
- Modify UI for better user experience.
Let’s start by adding the functionalities mentioned.
Adding Move Functionality
We'll implement the move functionality similarly to copy, but with an additional step of deleting the source after the copy is complete.
MainActivity.java
Add the move and rename functionality:
package com.yourdomain.filemanager;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
private ListView listView;
private FileListAdapter adapter;
private Stack<File> directoryStack;
private ArrayList<File> fileList;
private File currentDir;
private File fileCopyBuffer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MaterialToolbar toolbar = findViewById(R.id.topAppBar);
setSupportActionBar(toolbar);
listView = findViewById(R.id.fileListView);
directoryStack = new Stack<>();
fileList = new ArrayList<>();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(view -> createNewFolder());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
} else {
initFileList();
}
} else {
initFileList();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initFileList();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void initFileList() {
currentDir = Environment.getExternalStorageDirectory();
updateFileList(currentDir);
listView.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
File selectedFile = fileList.get(position);
if (selectedFile.isDirectory()) {
directoryStack.push(currentDir);
currentDir = selectedFile;
updateFileList(currentDir);
} else {
// Handle file click
}
});
listView.setOnItemLongClickListener((parent, view, position, id) -> {
File selectedFile = fileList.get(position);
showFileOptions(selectedFile);
return true;
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(view -> {
if (!directoryStack.isEmpty()) {
currentDir = directoryStack.pop();
updateFileList(currentDir);
} else {
finish();
}
});
}
private void updateFileList(File dir) {
if (dir != null && dir.isDirectory()) {
File[] files = dir.listFiles();
fileList.clear();
if (files != null) {
fileList.addAll(Arrays.asList(files));
}
if (adapter == null) {
adapter = new FileListAdapter(this, fileList);
listView.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
private void showFileOptions(File file) {
PopupMenu popupMenu = new PopupMenu(this, listView);
popupMenu.getMenuInflater().inflate(R.menu.file_options_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
case R.id.action_copy:
fileCopyBuffer = file;
Toast.makeText(this, "Copied to buffer", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_move:
fileCopyBuffer = file;
Toast.makeText(this, "Ready to move", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_delete:
confirmDeleteFile(file);
return true;
case R.id.action_rename:
renameFile(file);
return true;
default:
return false;
}
});
popupMenu.show();
}
private void confirmDeleteFile(File file) {
new AlertDialog.Builder(this)
.setTitle("Delete File")
.setMessage("Are you sure you want to delete " + file.getName() + "?")
.setPositiveButton("Yes", (dialog, which) -> {
if (deleteFileOrDir(file)) {
updateFileList(currentDir);
Toast.makeText(this, "File deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Delete failed", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", null)
.show();
}
private boolean deleteFileOrDir(File fileOrDir) {
if (fileOrDir.isDirectory()) {
for (File file : fileOrDir.listFiles()) {
if (!deleteFileOrDir(file)) {
return false;
}
}
}
return fileOrDir.delete();
}
private void createNewFolder() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Create New Folder");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Create", (dialog, which) -> {
String folderName = input.getText().toString();
if (!folderName.trim().isEmpty()) {
File newFolder = new File(currentDir, folderName);
if (newFolder.mkdir()) {
updateFileList(currentDir);
Toast.makeText(this, "Folder created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to create folder", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Folder name cannot be empty", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
builder.show();
}
private void renameFile(File file) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Rename File");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setText(file.getName());
builder.setView(input);
builder.setPositiveButton("Rename", (dialog, which) -> {
String newName = input.getText().toString();
if (!newName.trim().isEmpty()) {
File newFile = new File(file.getParent(), newName);
if (file.renameTo(newFile)) {
updateFileList(currentDir);
Toast.makeText(this, "File renamed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Rename failed", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Name cannot be empty", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());
builder.show();
}
private void pasteFile() {
if (fileCopyBuffer != null) {
final File destinationFile = new File(currentDir, fileCopyBuffer.getName());
new Thread(() -> {
try {
if (fileCopyBuffer.isDirectory()) {
copyDirectory(fileCopyBuffer, destinationFile);
} else {
copyFile(fileCopyBuffer, destinationFile);
}
runOnUiThread(() -> {
updateFileList(currentDir);
Toast.makeText(MainActivity.this, "File pasted", Toast.LENGTH_SHORT).show();
});
} catch (IOException e) {
e.printStackTrace();
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to paste file", Toast.LENGTH_SHORT).show());
}
}).start();
}
}
private void moveFile() {
if (fileCopyBuffer != null) {
final File destinationFile = new File(currentDir, fileCopyBuffer.getName());
new Thread(() -> {
try {
if (!fileCopyBuffer.renameTo(destinationFile)) {
throw new IOException("Failed to move file");
}
runOnUiThread(() -> {
updateFileList(currentDir);
Toast.makeText(MainActivity.this, "File moved", Toast.LENGTH_SHORT).show();
});
} catch (IOException e) {
e.printStackTrace();
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to move file", Toast.LENGTH_SHORT).show());
}
}).start();
}
}
private void copyFile(File source, File destination) throws IOException {
try (FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(destination)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
}
}
private void copyDirectory(File sourceDir, File destDir) throws IOException {
if (!destDir.exists()) {
destDir.mkdir();
}
for (File file : sourceDir.listFiles()) {
File destFile = new File(destDir, file.getName());
if (file.isDirectory()) {
copyDirectory(file, destFile);
} else {
copyFile(file, destFile);
}
}
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (!directoryStack.isEmpty()) {
currentDir = directoryStack.pop();
updateFileList(currentDir);
} else {
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
Enhancing the Layout
Now, let's include an option to perform paste operation in the layout.
activity_main.xml
Add a FloatingActionButton for paste functionality:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/topAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="?attr/actionBarTheme"/>
<ListView
android:id="@+id/fileListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/topAppBar"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@drawable/ic_add"
tools:ignore="VectorDrawableCompat" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab_paste"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/fab"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:layout_marginTop="70dp"
android:src="@drawable/ic_paste"
tools:ignore="VectorDrawableCompat" />
</RelativeLayout>
Implement Paste Operation
Implement paste operation in MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
// existing code
FloatingActionButton fabPaste = findViewById(R.id.fab_paste);
fabPaste.setOnClickListener(view -> pasteFile());
}
Adding Drawable Resources
Add appropriate drawable resources for add, paste, and other icons:
res/drawable/ic_add.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"
android:pathData="M13 11h8v2h-8v8h-2v-8H3v-2h8V3h2v8z"/>
</vector>
res/drawable/ic_paste.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"
android:pathData="M19,2H14.82C14.4,0.84 13.3,0 12,0s-2.4,0.84-2.82,2H5C3.9,2 3,2.9 3,4v16c0,1.1 0.9,2 2,2h14c1.1,0 2-0.9 2-2V4C21,2.9 20.1,2 19,2zM12,2c0.55,0 1,0.45 1,1s-0.45,1-1,1-1-0.45-1-1S11.45,2 12,2zM15,20H9v-2h6V20zM17,16H7v-2h10V16zM17,12H7v-2h10V12zM17,8H7V6h10V8z"/>
</vector>
Enhancing Exception Handling
Make file operations robust by enhancing exception handling.
MainActivity.java Modifications
// Modify methods to include better exception handling
private void copyFile(File source, File destination) throws IOException {
try (FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = new FileOutputStream(destination)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
} catch (IOException e) {
throw new IOException("Failed to copy file: " + e.getMessage());
}
}
private void copyDirectory(File sourceDir, File destDir) throws IOException {
if (!destDir.exists() && !destDir.mkdir()) {
throw new IOException("Failed to create directory: " + destDir.getPath());
}
for (File file : sourceDir.listFiles()) {
File destFile = new File(destDir, file.getName());
if (file.isDirectory()) {
copyDirectory(file, destFile);
} else {
copyFile(file, destFile);
}
}
}
This should give you a fully functional starting point for an Android file manager app that adheres to Material Design guidelines and includes basic file operations like copy, move, delete, and rename. Ensure thorough testing across various devices and Android versions to handle edge cases and performance aspects. Experience with concurrency and background tasks handling will be crucial for a production-level solution.