This repository has been archived by the owner on Feb 11, 2022. It is now read-only.
/
FilePickerFragment.java
355 lines (315 loc) · 11.4 KB
/
FilePickerFragment.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.nononsenseapps.filepicker;
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.FileObserver;
import android.support.annotation.NonNull;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.content.Loader;
import android.support.v7.util.SortedList;
import android.support.v7.widget.util.SortedListAdapterCallback;
import android.widget.Toast;
import java.io.File;
/**
* An implementation of the picker which allows you to select a file from the internal/external
* storage (SD-card) on a device.
*/
public class FilePickerFragment extends AbstractFilePickerFragment<File> {
protected static final int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
protected boolean showHiddenItems = false;
private File mRequestedPath = null;
public FilePickerFragment() {
}
/**
* This method is used to dictate whether hidden files and folders should be shown or not
*
* @param showHiddenItems whether hidden items should be shown or not
*/
public void showHiddenItems(boolean showHiddenItems){
this.showHiddenItems = showHiddenItems;
}
/**
* Returns if hidden items are shown or not
*
* @return true if hidden items are shown, otherwise false
*/
public boolean areHiddenItemsShown(){
return showHiddenItems;
}
/**
* @return true if app has been granted permission to write to the SD-card.
*/
@Override
protected boolean hasPermission(@NonNull File path) {
return PackageManager.PERMISSION_GRANTED ==
ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
/**
* Request permission to write to the SD-card.
*/
@Override
protected void handlePermission(@NonNull File path) {
// Should we show an explanation?
// if (shouldShowRequestPermissionRationale(
// Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need permission
// }
mRequestedPath = path;
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
/**
* This the method that gets notified when permission is granted/denied. By default,
* a granted request will result in a refresh of the list.
*
* @param requestCode the code you requested
* @param permissions array of permissions you requested. empty if process was cancelled.
* @param grantResults results for requests. empty if process was cancelled.
*/
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
// If arrays are empty, then process was cancelled
if (permissions.length == 0) {
// Treat this as a cancel press
if (mListener != null) {
mListener.onCancelled();
}
} else { // if (requestCode == PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
// Do refresh
if (mRequestedPath != null) {
refresh(mRequestedPath);
}
} else {
Toast.makeText(getContext(), R.string.nnf_permission_external_write_denied,
Toast.LENGTH_SHORT).show();
// Treat this as a cancel press
if (mListener != null) {
mListener.onCancelled();
}
}
}
}
/**
* Return true if the path is a directory and not a file.
*
* @param path either a file or directory
* @return true if path is a directory, false if file
*/
@Override
public boolean isDir(@NonNull final File path) {
return path.isDirectory();
}
/**
* @param path either a file or directory
* @return filename of path
*/
@NonNull
@Override
public String getName(@NonNull File path) {
return path.getName();
}
/**
* Return the path to the parent directory. Should return the root if
* from is root.
*
* @param from either a file or directory
* @return the parent directory
*/
@NonNull
@Override
public File getParent(@NonNull final File from) {
if (from.getPath().equals(getRoot().getPath())) {
// Already at root, we can't go higher
return from;
} else if (from.getParentFile() != null) {
return from.getParentFile();
} else {
return from;
}
}
/**
* Convert the path to the type used.
*
* @param path either a file or directory
* @return File representation of the string path
*/
@NonNull
@Override
public File getPath(@NonNull final String path) {
return new File(path);
}
/**
* @param path either a file or directory
* @return the full path to the file
*/
@NonNull
@Override
public String getFullPath(@NonNull final File path) {
return path.getPath();
}
/**
* Get the root path.
*
* @return the highest allowed path, which is "/" by default
*/
@NonNull
@Override
public File getRoot() {
return new File("/");
}
/**
* Convert the path to a URI for the return intent
*
* @param file either a file or directory
* @return a Uri
*/
@NonNull
@Override
public Uri toUri(@NonNull final File file) {
return FileProvider
.getUriForFile(getContext(),
getContext().getApplicationContext().getPackageName() + ".provider",
file);
}
/**
* Get a loader that lists the Files in the current path,
* and monitors changes.
*/
@NonNull
@Override
public Loader<SortedList<File>> getLoader() {
return new AsyncTaskLoader<SortedList<File>>(getActivity()) {
FileObserver fileObserver;
@Override
public SortedList<File> loadInBackground() {
File[] listFiles = mCurrentPath.listFiles();
final int initCap = listFiles == null ? 0 : listFiles.length;
SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {
@Override
public int compare(File lhs, File rhs) {
return compareFiles(lhs, rhs);
}
@Override
public boolean areContentsTheSame(File file, File file2) {
return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());
}
@Override
public boolean areItemsTheSame(File file, File file2) {
return areContentsTheSame(file, file2);
}
}, initCap);
files.beginBatchedUpdates();
if (listFiles != null) {
for (java.io.File f : listFiles) {
if (isItemVisible(f)) {
files.add(f);
}
}
}
files.endBatchedUpdates();
return files;
}
/**
* Handles a request to start the Loader.
*/
@Override
protected void onStartLoading() {
super.onStartLoading();
// handle if directory does not exist. Fall back to root.
if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
mCurrentPath = getRoot();
}
// Start watching for changes
fileObserver = new FileObserver(mCurrentPath.getPath(),
FileObserver.CREATE |
FileObserver.DELETE
| FileObserver.MOVED_FROM | FileObserver.MOVED_TO
) {
@Override
public void onEvent(int event, String path) {
// Reload
onContentChanged();
}
};
fileObserver.startWatching();
forceLoad();
}
/**
* Handles a request to completely reset the Loader.
*/
@Override
protected void onReset() {
super.onReset();
// Stop watching
if (fileObserver != null) {
fileObserver.stopWatching();
fileObserver = null;
}
}
};
}
/**
* Name is validated to be non-null, non-empty and not containing any
* slashes.
*
* @param name The name of the folder the user wishes to create.
*/
@Override
public void onNewFolder(@NonNull final String name) {
File folder = new File(mCurrentPath, name);
if (folder.mkdir()) {
refresh(folder);
} else {
Toast.makeText(getActivity(), R.string.nnf_create_folder_error,
Toast.LENGTH_SHORT).show();
}
}
/**
* Used by the list to determine whether a file should be displayed or not.
* Default behavior is to always display folders. If files can be selected,
* then files are also displayed. Set the showHiddenFiles property to show
* hidden file. Default behaviour is to hide hidden files. Override this method to enable other
* filtering behaviour, like only displaying files with specific extensions (.zip, .txt, etc).
*
* @param file to maybe add. Can be either a directory or file.
* @return True if item should be added to the list, false otherwise
*/
protected boolean isItemVisible(final File file) {
if (!showHiddenItems && file.isHidden()) {
return false;
}
return super.isItemVisible(file);
}
/**
* Compare two files to determine their relative sort order. This follows the usual
* comparison interface. Override to determine your own custom sort order.
* <p/>
* Default behaviour is to place directories before files, but sort them alphabetically
* otherwise.
*
* @param lhs File on the "left-hand side"
* @param rhs File on the "right-hand side"
* @return -1 if if lhs should be placed before rhs, 0 if they are equal,
* and 1 if rhs should be placed before lhs
*/
protected int compareFiles(@NonNull File lhs, @NonNull File rhs) {
if (lhs.isDirectory() && !rhs.isDirectory()) {
return -1;
} else if (rhs.isDirectory() && !lhs.isDirectory()) {
return 1;
} else {
return lhs.getName().compareToIgnoreCase(rhs.getName());
}
}
}