blob: a50c312659c0c7b754920b97cc80367eb6760d6a [file] [log] [blame]
Jeff Sharkeya5defe32013-08-05 17:56:48 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.documentsui;
18
19import static com.android.documentsui.DirectoryFragment.TYPE_NORMAL;
20import static com.android.documentsui.DirectoryFragment.TYPE_RECENT_OPEN;
21import static com.android.documentsui.DirectoryFragment.TYPE_SEARCH;
22
23import android.content.ContentResolver;
24import android.content.Context;
25import android.database.Cursor;
26import android.net.Uri;
27import android.os.CancellationSignal;
28
29import com.android.documentsui.model.Document;
30import com.android.internal.util.Predicate;
31import com.google.android.collect.Lists;
32
33import libcore.io.IoUtils;
34
35import java.util.ArrayList;
36import java.util.Collections;
37import java.util.Comparator;
38import java.util.List;
39
40public class DirectoryLoader extends UriDerivativeLoader<List<Document>> {
41
42 private final int mType;
43 private Predicate<Document> mFilter;
44 private Comparator<Document> mSortOrder;
45
46 public DirectoryLoader(Context context, Uri uri, int type, Predicate<Document> filter,
47 Comparator<Document> sortOrder) {
48 super(context, uri);
49 mType = type;
50 mFilter = filter;
51 mSortOrder = sortOrder;
52 }
53
54 @Override
55 public List<Document> loadInBackground(Uri uri, CancellationSignal signal) {
56 final ArrayList<Document> result = Lists.newArrayList();
57
58 // TODO: send selection and sorting hints to backend
59 final ContentResolver resolver = getContext().getContentResolver();
60 final Cursor cursor = resolver.query(uri, null, null, null, null, signal);
61 try {
62 while (cursor != null && cursor.moveToNext()) {
63 final Document doc;
64 switch (mType) {
65 case TYPE_NORMAL:
66 case TYPE_SEARCH:
67 doc = Document.fromDirectoryCursor(uri, cursor);
68 break;
69 case TYPE_RECENT_OPEN:
70 doc = Document.fromRecentOpenCursor(resolver, cursor);
71 break;
72 default:
73 throw new IllegalArgumentException("Unknown type");
74 }
75
76 if (mFilter == null || mFilter.apply(doc)) {
77 result.add(doc);
78 }
79 }
80 } finally {
81 IoUtils.closeQuietly(cursor);
82 }
83
84 if (mSortOrder != null) {
85 Collections.sort(result, mSortOrder);
86 }
87
88 return result;
89 }
90}