Create a simple File Finder Dialog in Android
1. Objectives of the example
In this article I'm going to guide you to create a simple application, search for files in Android and display the results on a Dialog.
This application will search for files on the SD Card, so if you test this application on Android Emulator, you need to set up SD Card for it.
Use Device File Explorer to copy some files into Android Emulator whichis necessary for you to test the application.
2. Example of File Finder Dialog
No ADS
First, create a new project on Android Studio:
- File > New > New Project > Empty Activity
- Name: FileFinderDialogExample
- Package name: org.o7planning.filefinderdialogexample
- Language: Java
After the user clicks the search button, a list of found files will be displayed on a RecyclerView. It is an interface component which is not available on the Android SDK, so you have to install it into the project.
After the library was successfully installed, you will see it be declared in build.gradle (Module App):
dependencies {
...
implementation 'androidx.recyclerview:recyclerview:1.0.0'
}
Next, register with the system so that your application is allowed to get access to the files.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.o7planning.filefinderdialogexample">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And this is the application interface:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText_search"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:hint="File Name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/checkBox_isRegex"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="Regex?"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_search" />
<Button
android:id="@+id/button_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Search"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox_isRegex" />
</androidx.constraintlayout.widget.ConstraintLayout>
The FileFinder class includes methods for searching files in the system. Noting that with Android 6.0+ (API Level 23+), the application needs to ask the user for permission in order to get access to the files. But if it is not allowed by the user, these methods will always return an empty list.
FileFinder.java
package org.o7planning.filefinderdialogexample;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class FileFinder {
private static final String LOG_TAG_FILE_FINDER = "FileSelector";
private boolean enableLog;
public FileFinder(boolean enableLog) {
this.enableLog = enableLog;
}
public List<File> findByKeyword(File rootDir, String keywordFileName) {
if(keywordFileName==null || keywordFileName.isEmpty()) {
return new ArrayList<File>();
}
String regexFileName = keywordFileName.replace("*", ".*?");
List<File> resultList = this.listOfFile(rootDir, regexFileName);
return resultList;
}
public List<File> findByRegex(File rootDir, String regexFileName) {
List<File> resultList = this.listOfFile(rootDir, regexFileName);
return resultList;
}
public List<File> findInSDCardByKeyword(String keywordFileName) {
// (Example): /storage/emulated/0
String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
this.log("External Storage Directory: " + sdCardPath);
File sdCardDir = new File(sdCardPath);
return this.findByKeyword(sdCardDir, keywordFileName);
}
public List<File> findInSDCardByRegex(String regexFileName) {
// (Example): /storage/emulated/0
String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
this.log("External Storage Directory: " + sdCardPath);
File sdCardDir = new File(sdCardPath);
return this.findByRegex(sdCardDir, regexFileName);
}
private List<File> listOfFile(File dir, String regexFileName) {
Pattern patternFileName = Pattern.compile(regexFileName);
List<File> resultList = new ArrayList<File>();
this.listOfFile(dir, patternFileName, resultList);
return resultList;
}
private void listOfFile(File dir, Pattern patternFileName, List<File> resultList) {
this.log("LIST OF DIR " + dir.getAbsolutePath());
File[] list = dir.listFiles();
if(list == null) {
this.log("Directory" + dir.getAbsolutePath()+ " has no files");
return;
}
this.log("Directory" + dir.getAbsolutePath()+ " has " + list.length +" direct files");
for (File file : list) {
if (file.isDirectory()) {
if (!new File(file, ".nomedia").exists() && !file.getName().startsWith(".")) {
this.log( "IS DIR " + file);
listOfFile(file, patternFileName, resultList);
}
} else {
String path = file.getAbsolutePath();
this.log( "FILE PATH: " + path);
String fileName = file.getName();
if(patternFileName.matcher(fileName).find()) {
resultList.add(file);
this.log( "ADD " + path);
}
}
}
}
private void log(String message) {
if(enableLog) {
Log.i(LOG_TAG_FILE_FINDER, message);
}
}
}
OnFileSelectListener.java
package org.o7planning.filefinderdialogexample;
import java.io.File;
public interface OnFileSelectListener {
void onSelect(File file);
}
ResultDialog.java
package org.o7planning.filefinderdialogexample;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
import java.util.List;
public class ResultDialog extends Dialog {
public ResultDialog(@NonNull Context context, List<File> resultList, OnFileSelectListener listener) {
super(context);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//
LinearLayout linearLayout = new LinearLayout(this.getContext());
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
int p = convertToPixels(12);
linearLayout.setPadding(p, p, p, p);
linearLayout.setGravity(Gravity.CENTER);
TextView textView = new TextView(this.getContext());
textView.setLayoutParams(new LinearLayout.LayoutParams(screenWidth(), ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setText("~ Search Result ~");
RecyclerView recyclerView = new RecyclerView(this.getContext());
linearLayout.addView(textView);
linearLayout.addView(recyclerView);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this.getContext(), this, listener, resultList);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
//
// this.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
//
this.setContentView(linearLayout);
this.setCancelable(true);
}
private int convertToPixels(int dp) {
float scale = this.getContext().getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
private int screenWidth() {
return this.getContext().getResources().getDisplayMetrics().widthPixels;
}
// RecyclerViewAdapter
private class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private Context context;
private List<File> files;
private OnFileSelectListener listener;
private Dialog dialog;
public RecyclerViewAdapter(Context context, Dialog dialog, OnFileSelectListener listener, List<File> files) {
this.context = context;
this.files = files;
this.listener = listener;
this.dialog = dialog;
}
// Create new views (invoked by the layout manager)
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtName = new TextView(context);
TextView txtPath = new TextView(context);
txtPath.setTypeface(txtPath.getTypeface(), Typeface.ITALIC);
txtPath.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
linearLayout.addView(txtName);
linearLayout.addView(txtPath);
RecyclerViewAdapter.ViewHolder viewHolder = new RecyclerViewAdapter.ViewHolder(linearLayout);
return viewHolder;
}
// Inner class to hold a reference to each item of RecyclerView
public class ViewHolder extends RecyclerView.ViewHolder {
public LinearLayout linearLayout;
public TextView textViewFileName;
public TextView textViewPath;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
this.linearLayout = (LinearLayout) itemLayoutView;
this.textViewFileName = (TextView) linearLayout.getChildAt(0);
this.textViewPath = (TextView) linearLayout.getChildAt(1);
}
}
@Override
public int getItemCount() {
return files.size();
}
@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder viewHolder, final int position) {
final File selectedFile = files.get(position);
final String path = selectedFile.getAbsolutePath();
String[] split = path.split("/");
final String name = split[split.length - 1];
viewHolder.textViewFileName.setText(name);
viewHolder.textViewPath.setText(path);
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
listener.onSelect(selectedFile);
}
});
}
}
}
MainActivity.java
package org.o7planning.filefinderdialogexample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final int MY_REQUEST_CODE_PERMISSION = 1000;
private static final String LOG_TAG = "AndroidExample";
private Button buttonSearch;
private EditText editTextSearch;
private CheckBox checkBoxIsRegex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.editTextSearch = (EditText) this.findViewById(R.id.editText_search);
this.checkBoxIsRegex = (CheckBox) this.findViewById(R.id.checkBox_isRegex);
this.buttonSearch = (Button) this.findViewById(R.id.button_search);
this.buttonSearch.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
askPermissionAndSearchFile();
}
});
}
private void askPermissionAndSearchFile() {
// With Android Level >= 23, you have to ask the user
// for permission to access External Storage.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { // Level 23
// Check if we have Call permission
int permisson = ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permisson != PackageManager.PERMISSION_GRANTED) {
// If don't have permission so prompt the user.
this.requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_REQUEST_CODE_PERMISSION
);
return;
}
}
this.doSearchFile();
}
private void doSearchFile() {
FileFinder fileSelector = new FileFinder(true);
String searchText = this.editTextSearch.getText().toString();
boolean isRegex = this.checkBoxIsRegex.isChecked();
List<File> resultList = null;
if(isRegex) {
resultList = fileSelector.findInSDCardByRegex(searchText);
} else {
resultList = fileSelector.findInSDCardByKeyword(searchText);
}
ResultDialog dialog = new ResultDialog(this, resultList, new OnFileSelectListener() {
@Override
public void onSelect(File file) {
Toast.makeText(MainActivity.this, "Path: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
// When you have the request results
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
switch (requestCode) {
case MY_REQUEST_CODE_PERMISSION: {
// Note: If request is cancelled, the result arrays are empty.
// Permissions granted (CALL_PHONE).
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i( LOG_TAG,"Permission granted!");
Toast.makeText(this, "Permission granted!", Toast.LENGTH_SHORT).show();
this.doSearchFile();
}
// Cancelled or denied.
else {
Log.i(LOG_TAG,"Permission denied!");
Toast.makeText(this, "Permission denied!", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
No ADS
Android Programming Tutorials
- Format Credit Card Number with Android TextWatcher
- Android Networking Tutorial with Examples
- Android TextInputLayout Tutorial with Examples
- Create a simple File Finder Dialog in Android
- Android AutoCompleteTextView and MultiAutoCompleteTextView Tutorial with Examples
- Using image assets and icon assets of Android Studio
- Android AsyncTaskLoader Tutorial with Examples
- Android ImageSwitcher Tutorial with Examples
- Android TimePickerDialog Tutorial with Examples
- Android FrameLayout Tutorial with Examples
- Android TimePicker Tutorial with Examples
- How to disable the permissions already granted to the Android application?
- Android ContextMenu Tutorial with Examples
- Android Camera Tutorial with Examples
- Get Phone Number in Android using TelephonyManager
- Android Clipboard Tutorial with Examples
- Android DatePickerDialog Tutorial with Examples
- Android SMS Tutorial with Examples
- Android Space Tutorial with Examples
- Android ScrollView and HorizontalScrollView Tutorial with Examples
- Install Android Studio on Windows
- Android VideoView Tutorial with Examples
- Android ProgressBar Tutorial with Examples
- Android External Storage Tutorial with Examples
- Android 2D Game Tutorial for Beginners
- Enable USB Debugging on Android Device
- Android MediaPlayer Tutorial with Examples
- Android Phone Call Tutorial with Examples
- Example of an explicit Android Intent, calling another Intent
- Android TextWatcher Tutorial with Examples
- Configure Android Emulator in Android Studio
- Android PopupMenu Tutorial with Examples
- Android CharacterPickerDialog Tutorial with Examples
- Android ListView with Checkbox using ArrayAdapter
- Android RadioGroup and RadioButton Tutorial with Examples
- Android AsyncTask Tutorial with Examples
- Android SnackBar Tutorial with Examples
- Android Spinner Tutorial with Examples
- Android ListView Tutorial with Examples
- Android TextView Tutorial with Examples
- Android SeekBar Tutorial with Examples
- Android JSON Parser Tutorial with Examples
- How to know the phone number of Android Emulator and change it
- Android LinearLayout Tutorial with Examples
- Android ViewPager2 Tutorial with Examples
- Android Text to Speech Tutorial with Examples
- Android RatingBar Tutorial with Examples
- Android DialogFragment Tutorial with Examples
- Android Wifi Scanning Tutorial with Examples
- Android Fragments Tutorial with Examples
- Create a simple File Chooser in Android
- Android DatePicker Tutorial with Examples
- Example of implicit Android Intent, open a URL, send an email
- Using Android Device File Explorer
- Android ToggleButton Tutorial with Examples
- Google Maps Android API Tutorial with Examples
- How to add external libraries to Android Project in Android Studio?
- Android EditText Tutorial with Examples
- Android ImageButton Tutorial with Examples
- Android Notifications Tutorial with Examples
- Android CheckBox Tutorial with Examples
- Android Services Tutorial with Examples
- Android Dialog Tutorial with Examples
- Android Tutorial for Beginners - Basic examples
- Create a custom Android Toast
- Android Intents Tutorial with Examples
- Android WebView Tutorial with Examples
- Android Chip and ChipGroup Tutorial with Examples
- Android GridView Tutorial with Examples
- Android Switch Tutorial with Examples
- How to remove applications from Android Emulator?
- Android QuickContactBadge Tutorial with Examples
- Android Chronometer Tutorial with Examples
- Android OptionMenu Tutorial with Examples
- Install Intel® HAXM for Android Studio
- Playing Sound effects in Android with SoundPool
- Android Internal Storage Tutorial with Examples
- Android AlertDialog Tutorial with Examples
- Android SharedPreferences Tutorial with Examples
- ChipGroup and Chip Entry Example
- Android SQLite Database Tutorial with Examples
- Android Toast Tutorial with Examples
- Android TableLayout Tutorial with Examples
- Android Button Tutorial with Examples
- Android FloatingActionButton Tutorial with Examples
- What is needed to get started with Android?
- Android UI Layouts Tutorial with Examples
- Android CardView Tutorial with Examples
- Setting SD Card for Android Emulator
- Android ImageView Tutorial with Examples
- Android Tutorial for Beginners - Hello Android
- Android StackView Tutorial with Examples
- Android TextClock Tutorial with Examples
Show More