List of usage examples for android.database MatrixCursor MatrixCursor
public MatrixCursor(String[] columnNames)
From source file:monakhv.android.samlib.AuthorListFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { int sel = item.getItemId(); if (sel == android.R.id.home) { //mCallbacks.onOpenPanel(); if (getSelection() != null) { refresh(null, null);/*from w w w . j a va 2 s . c o m*/ mCallbacks.onTitleChange(getString(R.string.app_name)); } } if (sel == R.id.menu_refresh) { startRefresh(); } if (sel == R.id.sort_option_item_books) { mCallbacks.selectBookSortOrder(); } if (sel == R.id.sort_option_item) { AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SortOrder so = SortOrder.values()[position]; mCallbacks.onAuthorSelected(0); setSortOrder(so); sortDialog.dismiss(); } }; sortDialog = SingleChoiceSelectDialog.getInstance(SortOrder.getTitles(getActivity()), listener, this.getString(R.string.dialog_title_sort_author), getSortOrder().ordinal()); sortDialog.show(getActivity().getSupportFragmentManager(), "DoSortDialog"); } if (sel == R.id.add_option_item) { View v = getActivity().findViewById(R.id.add_author_panel); v.setVisibility(View.VISIBLE); String txt = null; try { txt = getClipboardText(getActivity()); } catch (Exception ex) { Log.e(DEBUG_TAG, "Clipboard Error!", ex); } if (txt != null) { if (SamLibConfig.getParsedUrl(txt) != null) { EditText editText = (EditText) getActivity().findViewById(R.id.addUrlText); editText.setText(txt); } } } if (sel == R.id.settings_option_item) { Log.d(DEBUG_TAG, "go to Settings"); Intent prefsIntent = new Intent(getActivity().getApplicationContext(), SamlibPreferencesActivity.class); //prefsIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); getActivity().startActivityForResult(prefsIntent, MainActivity.PREFS_ACTIVITY); } if (sel == R.id.archive_option_item) { Log.d(DEBUG_TAG, "go to Archive"); Intent prefsIntent = new Intent(getActivity().getApplicationContext(), ArchiveActivity.class); //prefsIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); //startActivityForResult must be called via getActivity direct call produce wrong requestCode getActivity().startActivityForResult(prefsIntent, MainActivity.ARCHIVE_ACTIVITY); } if (sel == R.id.selected_option_item) { Log.d(DEBUG_TAG, "go to Selected"); cleanSelection(); mCallbacks.onAuthorSelected(SamLibConfig.SELECTED_BOOK_ID); } if (sel == R.id.menu_filter) { Log.d(DEBUG_TAG, "go to Filter"); Cursor tags = getActivity().getContentResolver().query(AuthorProvider.TAG_URI, null, null, null, SQLController.COL_TAG_NAME); MatrixCursor extras = new MatrixCursor( new String[] { SQLController.COL_ID, SQLController.COL_TAG_NAME }); extras.addRow(new String[] { Integer.toString(SamLibConfig.TAG_AUTHOR_ALL), getText(R.string.filter_all).toString() }); extras.addRow(new String[] { Integer.toString(SamLibConfig.TAG_AUTHOR_NEW), getText(R.string.filter_new).toString() }); Cursor[] cursors = { extras, tags }; final Cursor extendedCursor = new MergeCursor(cursors); AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { extendedCursor.moveToPosition(position); int tag_id = extendedCursor.getInt(extendedCursor.getColumnIndex(SQLController.COL_ID)); String tg_name = extendedCursor .getString(extendedCursor.getColumnIndex(SQLController.COL_TAG_NAME)); filterDialog.dismiss(); selection = SQLController.TABLE_TAGS + "." + SQLController.COL_ID + "=" + tag_id; if (tag_id == SamLibConfig.TAG_AUTHOR_ALL) { selection = null; mCallbacks.onTitleChange(getActivity().getText(R.string.app_name).toString()); } else { mCallbacks.onTitleChange(tg_name); } if (tag_id == SamLibConfig.TAG_AUTHOR_NEW) { selection = SQLController.TABLE_AUTHOR + "." + SQLController.COL_isnew + "=1"; } Log.i(DEBUG_TAG, "WHERE " + selection); refresh(selection, null); mCallbacks.onAuthorSelected(0); } }; filterDialog = FilterSelectDialog.getInstance(extendedCursor, listener, getText(R.string.dialog_title_filtr).toString()); filterDialog.show(getActivity().getSupportFragmentManager(), "FilterDialogShow"); } return super.onOptionsItemSelected(item); }
From source file:com.example.android.vault.VaultProvider.java
@Override public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection)); try {//ww w .j a v a 2 s . com includeDocument(result, Long.parseLong(documentId)); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new IllegalStateException(e); } return result; }
From source file:com.esri.arcgisruntime.sample.findplace.MainActivity.java
/** * Sets up the proximity SearchView. Uses MatrixCursor to show suggestions to the user as the user inputs text. *//*from w ww . ja v a 2 s.c o m*/ private void setupProximity() { mProximitySuggestParameters = new SuggestParameters(); mProximitySuggestParameters.getCategories().add("Populated Place"); mProximityGeocodeParameters = new GeocodeParameters(); // get all attributes mProximityGeocodeParameters.getResultAttributeNames().add("*"); mProximitySearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String address) { geoCodeTypedAddress(address); // clear focus from search views mPoiSearchView.clearFocus(); mProximitySearchView.clearFocus(); return true; } @Override public boolean onQueryTextChange(String newText) { // as long as newText isn't empty, get suggestions from the locatorTask if (!newText.equals("")) { mProximitySearchViewEmpty = false; final ListenableFuture<List<SuggestResult>> suggestionsFuture = mLocatorTask .suggestAsync(newText, mProximitySuggestParameters); suggestionsFuture.addDoneListener(new Runnable() { @Override public void run() { try { // get the list of suggestions List<SuggestResult> suggestResults = suggestionsFuture.get(); MatrixCursor suggestionsCursor = new MatrixCursor(mColumnNames); int key = 0; // add each SuggestResult to a new row for (SuggestResult result : suggestResults) { suggestionsCursor.addRow(new Object[] { key++, result.getLabel() }); } // define SimpleCursorAdapter String[] cols = new String[] { COLUMN_NAME_ADDRESS }; int[] to = new int[] { R.id.suggestion_address }; final SimpleCursorAdapter suggestionAdapter = new SimpleCursorAdapter( MainActivity.this, R.layout.suggestion, suggestionsCursor, cols, to, 0); mProximitySearchView.setSuggestionsAdapter(suggestionAdapter); mProximitySearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionSelect(int position) { return false; } @Override public boolean onSuggestionClick(int position) { // get the selected row MatrixCursor selectedRow = (MatrixCursor) suggestionAdapter .getItem(position); // get the row's index int selectedCursorIndex = selectedRow.getColumnIndex(COLUMN_NAME_ADDRESS); // get the string from the row at index final String address = selectedRow.getString(selectedCursorIndex); mLocatorTask.addDoneLoadingListener(new Runnable() { @Override public void run() { if (mLocatorTask.getLoadStatus() == LoadStatus.LOADED) { // geocode the selected address to get location of address final ListenableFuture<List<GeocodeResult>> geocodeFuture = mLocatorTask .geocodeAsync(address, mProximityGeocodeParameters); geocodeFuture.addDoneListener(new Runnable() { @Override public void run() { try { // Get the results of the async operation List<GeocodeResult> geocodeResults = geocodeFuture .get(); if (geocodeResults.size() > 0) { // use geocodeResult to focus search area GeocodeResult geocodeResult = geocodeResults .get(0); // update preferred search area to the geocode result mPreferredSearchProximity = geocodeResult .getDisplayLocation(); mPoiGeocodeParameters.setSearchArea( mPreferredSearchProximity); // set the address string to the SearchView, but don't submit as a query mProximitySearchView.setQuery(address, false); // call POI search query mPoiSearchView.setQuery(mPoiAddress, true); // clear focus from search views mProximitySearchView.clearFocus(); mPoiSearchView.clearFocus(); } else { Toast.makeText(getApplicationContext(), getString(R.string.location_not_found) + address, Toast.LENGTH_LONG).show(); } } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "Geocode error: " + e.getMessage()); Toast.makeText(getApplicationContext(), getString(R.string.geo_locate_error), Toast.LENGTH_LONG).show(); } } }); } } }); return true; } }); } catch (Exception e) { Log.e(TAG, "Geocode suggestion error: " + e.getMessage()); } } }); // if search view is empty, set flag } else { mProximitySearchViewEmpty = true; } return true; } }); }
From source file:saschpe.birthdays.service.CalendarSyncService.java
private static Cursor getContactsEvents(Context context, ContentResolver contentResolver) { // Account blacklist from our provider List<Account> accountBlacklist = AccountProviderHelper.getAccountList(context); List<String> addedEventsIdentifiers = new ArrayList<>(); /* 1. Get all raw contacts with their corresponding Account name and type (only raw * contacts get Account affiliation) */ Uri rawContactsUri = ContactsContract.RawContacts.CONTENT_URI; String[] rawContactsProjection = new String[] { ContactsContract.RawContacts._ID, ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY, ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE }; Cursor rawContacts = contentResolver.query(rawContactsUri, rawContactsProjection, null, null, null); /* 2. Go over all raw contacts and check if the Account is allowed. If account is allowed, * get display name and lookup key and all events for this contact. Build a new * MatrixCursor out of this data that can be used. */ String[] columns = new String[] { BaseColumns._ID, ContactsContract.Data.DISPLAY_NAME, ContactsContract.Data.LOOKUP_KEY, ContactsContract.CommonDataKinds.Event.START_DATE, ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.LABEL, }; MatrixCursor mc = new MatrixCursor(columns); int mcIndex = 0; try {// w w w.j a va 2 s .c o m while (rawContacts != null && rawContacts.moveToNext()) { long rawId = rawContacts.getLong(rawContacts.getColumnIndex(ContactsContract.RawContacts._ID)); String accountType = rawContacts .getString(rawContacts.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)); String accountName = rawContacts .getString(rawContacts.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)); // 2a. Check if Account is allowed (not in blacklist) boolean addEvent; if (TextUtils.isEmpty(accountType) || TextUtils.isEmpty(accountName)) { // Workaround: Simply add events without proper Account addEvent = true; } else { Account account = new Account(accountName, accountType); addEvent = !accountBlacklist.contains(account); } if (addEvent) { String displayName = null; String lookupKey = null; // 2b. Get display name and lookup key from normal contact table String[] displayProjection = new String[] { ContactsContract.Data.RAW_CONTACT_ID, ContactsContract.Data.DISPLAY_NAME, ContactsContract.Data.LOOKUP_KEY }; String displayWhere = ContactsContract.Data.RAW_CONTACT_ID + "= ?"; String[] displaySelectionArgs = new String[] { String.valueOf(rawId) }; Cursor displayCursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, displayProjection, displayWhere, displaySelectionArgs, null); try { if (displayCursor != null && displayCursor.moveToNext()) { displayName = displayCursor .getString(displayCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); lookupKey = displayCursor .getString(displayCursor.getColumnIndex(ContactsContract.Data.LOOKUP_KEY)); } } finally { if (displayCursor != null && !displayCursor.isClosed()) { displayCursor.close(); } } /* 2c. Get all events for this raw contact. We don't get this information for * the (merged) contact table, but from the raw contact. If we would query * this information from the contact table, we would also get events that * should have been filtered. */ Uri thisRawContactUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rawId); Uri entityUri = Uri.withAppendedPath(thisRawContactUri, ContactsContract.RawContacts.Entity.CONTENT_DIRECTORY); String[] eventsProjection = new String[] { ContactsContract.RawContacts._ID, ContactsContract.RawContacts.Entity.DATA_ID, ContactsContract.CommonDataKinds.Event.START_DATE, ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.LABEL }; String eventsWhere = ContactsContract.RawContacts.Entity.MIMETYPE + " = ? AND " + ContactsContract.RawContacts.Entity.DATA_ID + " IS NOT NULL"; String[] eventsSelectionArgs = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE }; Cursor eventsCursor = contentResolver.query(entityUri, eventsProjection, eventsWhere, eventsSelectionArgs, null); try { while (eventsCursor != null && eventsCursor.moveToNext()) { String startDate = eventsCursor.getString( eventsCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)); int type = eventsCursor.getInt( eventsCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE)); String label = eventsCursor.getString( eventsCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.LABEL)); /* 2d. Add this information to our MatrixCursor if not already added * previously. If two Event Reminder accounts have the same contact * with duplicated events, the event will already be in the HashSet * addedEventsIdentifiers. * * eventIdentifier does not include startDate, because the * String formats of startDate differ between accounts. */ //String eventIdentifier = lookupKey + type + label; String eventIdentifier = lookupKey + type; if (addedEventsIdentifiers.contains(eventIdentifier)) { Log.d(TAG, "Duplicate event was not added!"); } else { Log.d(TAG, "Event was added with identifier " + eventIdentifier); addedEventsIdentifiers.add(eventIdentifier); mc.newRow().add(mcIndex).add(displayName).add(lookupKey).add(startDate).add(type) .add(label); mcIndex++; } } } finally { if (eventsCursor != null && !eventsCursor.isClosed()) { eventsCursor.close(); } } } } } finally { if (rawContacts != null && !rawContacts.isClosed()) { rawContacts.close(); } } /*if (BuildConfig.DEBUG) { DatabaseUtils.dumpCursor(mc); }*/ return mc; }
From source file:com.android.music.PlaylistBrowserFragment.java
private Cursor mergedCursor(Cursor c) { if (c == null) { return null; }//from w ww . j av a2 s. c o m if (c instanceof MergeCursor) { // this shouldn't happen, but fail gracefully Log.d("PlaylistBrowserActivity", "Already wrapped"); return c; } MatrixCursor autoplaylistscursor = new MatrixCursor(mCols); if (mCreateShortcut) { ArrayList<Object> all = new ArrayList<Object>(2); all.add(ALL_SONGS_PLAYLIST); all.add(getString(R.string.play_all)); autoplaylistscursor.addRow(all); } ArrayList<Object> recent = new ArrayList<Object>(2); recent.add(RECENTLY_ADDED_PLAYLIST); recent.add(getString(R.string.recentlyadded)); autoplaylistscursor.addRow(recent); // check if there are any podcasts Cursor counter = MusicUtils.query(getActivity(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { "count(*)" }, "is_podcast=1", null, null); if (counter != null) { counter.moveToFirst(); int numpodcasts = counter.getInt(0); counter.close(); if (numpodcasts > 0) { ArrayList<Object> podcasts = new ArrayList<Object>(2); podcasts.add(PODCASTS_PLAYLIST); podcasts.add(getString(R.string.podcasts_listitem)); autoplaylistscursor.addRow(podcasts); } } Cursor cc = new MergeCursor(new Cursor[] { autoplaylistscursor, c }); return cc; }
From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java
@Override public Cursor query(final Uri uri, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) { try {/*from www .j a v a2 s .co m*/ final int tableId = getTableId(uri); final String table = getTableNameById(tableId); switch (tableId) { case VIRTUAL_TABLE_ID_DATABASE_READY: { if (mDatabaseWrapper.isReady()) return new MatrixCursor(projection != null ? projection : new String[0]); return null; } case VIRTUAL_TABLE_ID_ALL_PREFERENCES: { return getPreferencesCursor(mPreferences, null); } case VIRTUAL_TABLE_ID_PREFERENCES: { return getPreferencesCursor(mPreferences, uri.getLastPathSegment()); } case VIRTUAL_TABLE_ID_DNS: { return getDNSCursor(uri.getLastPathSegment()); } case VIRTUAL_TABLE_ID_CACHED_IMAGES: { return getCachedImageCursor(uri.getQueryParameter(QUERY_PARAM_URL)); } case VIRTUAL_TABLE_ID_NOTIFICATIONS: { final List<String> segments = uri.getPathSegments(); if (segments.size() == 2) return getNotificationsCursor(ParseUtils.parseInt(segments.get(1), -1)); else return getNotificationsCursor(); } case VIRTUAL_TABLE_ID_UNREAD_COUNTS: { final List<String> segments = uri.getPathSegments(); if (segments.size() == 2) return getUnreadCountsCursor(ParseUtils.parseInt(segments.get(1), -1)); else return getUnreadCountsCursor(); } case VIRTUAL_TABLE_ID_UNREAD_COUNTS_BY_TYPE: { final List<String> segments = uri.getPathSegments(); if (segments.size() != 3) return null; return getUnreadCountsCursorByType(segments.get(2)); } case TABLE_ID_DIRECT_MESSAGES_CONVERSATION: { final List<String> segments = uri.getPathSegments(); if (segments.size() != 4) return null; final long accountId = ParseUtils.parseLong(segments.get(2)); final long conversationId = ParseUtils.parseLong(segments.get(3)); final SQLSelectQuery query = ConversationQueryBuilder.buildByConversationId(projection, accountId, conversationId, selection, sortOrder); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, DirectMessages.CONTENT_URI); return c; } case TABLE_ID_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME: { final List<String> segments = uri.getPathSegments(); if (segments.size() != 4) return null; final long accountId = ParseUtils.parseLong(segments.get(2)); final String screenName = segments.get(3); final SQLSelectQuery query = ConversationQueryBuilder.buildByScreenName(projection, accountId, screenName, selection, sortOrder); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, DirectMessages.CONTENT_URI); return c; } case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_RELATIONSHIP: { final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1); final SQLSelectQuery query = CachedUsersQueryBuilder.buildWithRelationship(projection, selection, sortOrder, accountId); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, CachedUsers.CONTENT_URI); return c; } case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_SCORE: { final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1); final SQLSelectQuery query = CachedUsersQueryBuilder.buildWithScore(projection, selection, sortOrder, accountId); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, CachedUsers.CONTENT_URI); return c; } case VIRTUAL_TABLE_ID_DRAFTS_UNSENT: { final TwittnukerApplication app = TwittnukerApplication.getInstance(getContext()); final AsyncTwitterWrapper twitter = app.getTwitterWrapper(); final RawItemArray sendingIds = new RawItemArray(twitter.getSendingDraftIds()); final Expression where; if (selection != null) { where = Expression.and(new Expression(selection), Expression.notIn(new Column(Drafts._ID), sendingIds)); } else { where = Expression.and(Expression.notIn(new Column(Drafts._ID), sendingIds)); } final Cursor c = mDatabaseWrapper.query(Drafts.TABLE_NAME, projection, where.getSQL(), selectionArgs, null, null, sortOrder); setNotificationUri(c, getNotificationUri(tableId, uri)); return c; } } if (table == null) return null; final Cursor c = mDatabaseWrapper.query(table, projection, selection, selectionArgs, null, null, sortOrder); setNotificationUri(c, getNotificationUri(tableId, uri)); return c; } catch (final SQLException e) { throw new IllegalStateException(e); } }
From source file:ch.blinkenlights.android.vanilla.MediaUtils.java
/** * Returns a (possibly empty) Cursor for given file path * @param path The path to the file to be queried * @return A new Cursor object/*from ww w .jav a 2 s .c o m*/ * */ public static Cursor getCursorForFileQuery(String path) { MatrixCursor matrixCursor = new MatrixCursor(Song.FILLED_PROJECTION); MediaMetadataExtractor tags = new MediaMetadataExtractor(path); String title = tags.getFirst(MediaMetadataExtractor.TITLE); String album = tags.getFirst(MediaMetadataExtractor.ALBUM); String artist = tags.getFirst(MediaMetadataExtractor.ARTIST); String duration = tags.getFirst(MediaMetadataExtractor.DURATION); if (duration != null) { // looks like we will be able to play this file // Vanilla requires each file to be identified by its unique id in the media database. // However: This file is not in the database, so we are going to roll our own // using the negative crc32 sum of the path value. While this is not perfect // (the same file may be accessed using various paths) it's the fastest method // and far good enough. long songId = MediaLibrary.hash63(path) * -1; if (songId > -2) songId = -2; // must be less than -1 (-1 defines an empty song object) // Build minimal fake-database entry for this file Object[] objData = new Object[] { songId, path, "", "", "", 0, 0, 0, 0, 0 }; if (title != null) objData[2] = title; if (album != null) objData[3] = album; if (artist != null) objData[4] = artist; if (duration != null) objData[7] = Long.parseLong(duration, 10); matrixCursor.addRow(objData); } return matrixCursor; }
From source file:bf.io.openshop.ux.MainActivity.java
/** * Show user search whisperer with generated suggestions. * * @param query actual search query * @param searchView corresponding search action view. *//*from w w w. j a v a 2 s . c o m*/ private void showSearchSuggestions(String query, SearchView searchView) { if (searchSuggestionsAdapter != null && searchSuggestionsList != null) { Timber.d("Populate search adapter - mySuggestions.size(): %d", searchSuggestionsList.size()); final MatrixCursor c = new MatrixCursor(new String[] { BaseColumns._ID, "categories" }); for (int i = 0; i < searchSuggestionsList.size(); i++) { if (searchSuggestionsList.get(i) != null && searchSuggestionsList.get(i).toLowerCase().startsWith(query.toLowerCase())) c.addRow(new Object[] { i, searchSuggestionsList.get(i) }); } searchView.setSuggestionsAdapter(searchSuggestionsAdapter); searchSuggestionsAdapter.changeCursor(c); } else { Timber.e("Search adapter is null or search data suggestions missing"); } }
From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java
@Override public Cursor query(final Uri uri, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) { try {// w w w . java 2s .c o m final int tableId = getTableId(uri); final String table = getTableNameById(tableId); checkReadPermission(tableId, table, projection); switch (tableId) { case VIRTUAL_TABLE_ID_DATABASE_READY: { if (mDatabaseWrapper.isReady()) return new MatrixCursor(projection != null ? projection : new String[0]); return null; } case VIRTUAL_TABLE_ID_PERMISSIONS: { final MatrixCursor c = new MatrixCursor(FiretweetDataStore.Permissions.MATRIX_COLUMNS); final Map<String, String> map = mPermissionsManager.getAll(); for (final Map.Entry<String, String> item : map.entrySet()) { c.addRow(new Object[] { item.getKey(), item.getValue() }); } return c; } case VIRTUAL_TABLE_ID_ALL_PREFERENCES: { return getPreferencesCursor(mPreferences, null); } case VIRTUAL_TABLE_ID_PREFERENCES: { return getPreferencesCursor(mPreferences, uri.getLastPathSegment()); } case VIRTUAL_TABLE_ID_DNS: { return getDNSCursor(uri.getLastPathSegment()); } case VIRTUAL_TABLE_ID_CACHED_IMAGES: { return getCachedImageCursor(uri.getQueryParameter(QUERY_PARAM_URL)); } case VIRTUAL_TABLE_ID_NOTIFICATIONS: { final List<String> segments = uri.getPathSegments(); if (segments.size() == 2) return getNotificationsCursor(ParseUtils.parseInt(segments.get(1), -1)); else return getNotificationsCursor(); } case VIRTUAL_TABLE_ID_UNREAD_COUNTS: { final List<String> segments = uri.getPathSegments(); if (segments.size() == 2) return getUnreadCountsCursor(ParseUtils.parseInt(segments.get(1), -1)); else return getUnreadCountsCursor(); } case VIRTUAL_TABLE_ID_UNREAD_COUNTS_BY_TYPE: { final List<String> segments = uri.getPathSegments(); if (segments.size() != 3) return null; return getUnreadCountsCursorByType(segments.get(2)); } case TABLE_ID_DIRECT_MESSAGES_CONVERSATION: { final List<String> segments = uri.getPathSegments(); if (segments.size() != 4) return null; final long accountId = ParseUtils.parseLong(segments.get(2)); final long conversationId = ParseUtils.parseLong(segments.get(3)); final SQLSelectQuery query = ConversationQueryBuilder.buildByConversationId(projection, accountId, conversationId, selection, sortOrder); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, DirectMessages.CONTENT_URI); return c; } case TABLE_ID_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME: { final List<String> segments = uri.getPathSegments(); if (segments.size() != 4) return null; final long accountId = ParseUtils.parseLong(segments.get(2)); final String screenName = segments.get(3); final SQLSelectQuery query = ConversationQueryBuilder.buildByScreenName(projection, accountId, screenName, selection, sortOrder); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, DirectMessages.CONTENT_URI); return c; } case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_RELATIONSHIP: { final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1); final SQLSelectQuery query = CachedUsersQueryBuilder.withRelationship(projection, selection, sortOrder, accountId); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, CachedUsers.CONTENT_URI); return c; } case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_SCORE: { final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1); final SQLSelectQuery query = CachedUsersQueryBuilder.withScore(projection, selection, sortOrder, accountId); final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs); setNotificationUri(c, CachedUsers.CONTENT_URI); return c; } case VIRTUAL_TABLE_ID_DRAFTS_UNSENT: { final FiretweetApplication app = FiretweetApplication.getInstance(getContext()); final AsyncTwitterWrapper twitter = app.getTwitterWrapper(); final RawItemArray sendingIds = new RawItemArray(twitter.getSendingDraftIds()); final Expression where; if (selection != null) { where = Expression.and(new Expression(selection), Expression.notIn(new Column(Drafts._ID), sendingIds)); } else { where = Expression.and(Expression.notIn(new Column(Drafts._ID), sendingIds)); } final Cursor c = mDatabaseWrapper.query(Drafts.TABLE_NAME, projection, where.getSQL(), selectionArgs, null, null, sortOrder); setNotificationUri(c, getNotificationUri(tableId, uri)); return c; } } if (table == null) return null; final Cursor c = mDatabaseWrapper.query(table, projection, selection, selectionArgs, null, null, sortOrder); setNotificationUri(c, getNotificationUri(tableId, uri)); return c; } catch (final SQLException e) { Crashlytics.logException(e); throw new IllegalStateException(e); } }
From source file:com.seafile.seadroid2.provider.SeafileProvider.java
/** * Create a MatrixCursor with the option to enable the extraLoading flag. * * @param netProjection column list// ww w. j a v a2s. c o m * @param extraLoading if true, the client will expect that more entries will arrive shortly. * @return the Cursor object */ private static MatrixCursor createCursor(String[] netProjection, final boolean extraLoading, final boolean isReachable) { return new MatrixCursor(netProjection) { @Override public Bundle getExtras() { Bundle b = new Bundle(); b.putBoolean(DocumentsContract.EXTRA_LOADING, extraLoading); if (!extraLoading && !isReachable) { b.putString(DocumentsContract.EXTRA_ERROR, "Could not connect with server"); } return b; } }; }