List of usage examples for android.net Uri getPathSegments
public abstract List<String> getPathSegments();
From source file:com.owncloud.android.datamodel.FileDataStorageManager.java
public boolean saveFile(OCFile file) { boolean overriden = false; ContentValues cv = new ContentValues(); cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp()); cv.put(ProviderTableMeta.FILE_MODIFIED_AT_LAST_SYNC_FOR_DATA, file.getModificationTimestampAtLastSyncForData()); cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp()); cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength()); cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype()); cv.put(ProviderTableMeta.FILE_NAME, file.getFileName()); cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId()); cv.put(ProviderTableMeta.FILE_PATH, file.getRemotePath()); if (!file.isFolder()) cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath()); cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name); cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE, file.getLastSyncDateForProperties()); cv.put(ProviderTableMeta.FILE_LAST_SYNC_DATE_FOR_DATA, file.getLastSyncDateForData()); cv.put(ProviderTableMeta.FILE_ETAG, file.getEtag()); cv.put(ProviderTableMeta.FILE_TREE_ETAG, file.getTreeEtag()); cv.put(ProviderTableMeta.FILE_SHARED_VIA_LINK, file.isSharedViaLink() ? 1 : 0); cv.put(ProviderTableMeta.FILE_SHARED_WITH_SHAREE, file.isSharedWithSharee() ? 1 : 0); cv.put(ProviderTableMeta.FILE_PERMISSIONS, file.getPermissions()); cv.put(ProviderTableMeta.FILE_REMOTE_ID, file.getRemoteId()); cv.put(ProviderTableMeta.FILE_UPDATE_THUMBNAIL, file.needsUpdateThumbnail()); cv.put(ProviderTableMeta.FILE_IS_DOWNLOADING, file.isDownloading()); cv.put(ProviderTableMeta.FILE_ETAG_IN_CONFLICT, file.getEtagInConflict()); cv.put(ProviderTableMeta.FILE_PRIVATE_LINK, file.getPrivateLink()); boolean sameRemotePath = fileExists(file.getRemotePath()); if (sameRemotePath || fileExists(file.getFileId())) { // for renamed files; no more delete and create OCFile oldFile;/*from w w w. j av a 2 s . c om*/ if (sameRemotePath) { oldFile = getFileByPath(file.getRemotePath()); file.setFileId(oldFile.getFileId()); } else { oldFile = getFileById(file.getFileId()); } overriden = true; if (getContentResolver() != null) { getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, ProviderTableMeta._ID + "=?", new String[] { String.valueOf(file.getFileId()) }); } else { try { getContentProviderClient().update(ProviderTableMeta.CONTENT_URI, cv, ProviderTableMeta._ID + "=?", new String[] { String.valueOf(file.getFileId()) }); } catch (RemoteException e) { Log_OC.e(TAG, "Fail to insert insert file to database " + e.getMessage()); } } } else { // new file setInitialAvailableOfflineStatus(file, cv); Uri result_uri = null; if (getContentResolver() != null) { result_uri = getContentResolver().insert(ProviderTableMeta.CONTENT_URI_FILE, cv); } else { try { result_uri = getContentProviderClient().insert(ProviderTableMeta.CONTENT_URI_FILE, cv); } catch (RemoteException e) { Log_OC.e(TAG, "Fail to insert insert file to database " + e.getMessage()); } } if (result_uri != null) { long new_id = Long.parseLong(result_uri.getPathSegments().get(1)); file.setFileId(new_id); } } return overriden; }
From source file:com.owncloud.android.datamodel.FileDataStorageManager.java
public OCCapability saveCapabilities(OCCapability capability) { // Prepare capabilities data ContentValues cv = new ContentValues(); cv.put(ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME, mAccount.name); cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MAYOR, capability.getVersionMayor()); cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MINOR, capability.getVersionMinor()); cv.put(ProviderTableMeta.CAPABILITIES_VERSION_MICRO, capability.getVersionMicro()); cv.put(ProviderTableMeta.CAPABILITIES_VERSION_STRING, capability.getVersionString()); cv.put(ProviderTableMeta.CAPABILITIES_VERSION_EDITION, capability.getVersionEdition()); cv.put(ProviderTableMeta.CAPABILITIES_CORE_POLLINTERVAL, capability.getCorePollinterval()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_API_ENABLED, capability.getFilesSharingApiEnabled().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_ENABLED, capability.getFilesSharingPublicEnabled().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_PASSWORD_ENFORCED, capability.getFilesSharingPublicPasswordEnforced().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENABLED, capability.getFilesSharingPublicExpireDateEnabled().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_DAYS, capability.getFilesSharingPublicExpireDateDays()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_EXPIRE_DATE_ENFORCED, capability.getFilesSharingPublicExpireDateEnforced().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SEND_MAIL, capability.getFilesSharingPublicSendMail().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_UPLOAD, capability.getFilesSharingPublicUpload().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_MULTIPLE, capability.getFilesSharingPublicMultiple().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_PUBLIC_SUPPORTS_UPLOAD_ONLY, capability.getFilesSharingPublicSupportsUploadOnly().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_USER_SEND_MAIL, capability.getFilesSharingUserSendMail().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_RESHARING, capability.getFilesSharingResharing().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_OUTGOING, capability.getFilesSharingFederationOutgoing().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_SHARING_FEDERATION_INCOMING, capability.getFilesSharingFederationIncoming().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_FILES_BIGFILECHUNKING, capability.getFilesBigFileChuncking().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_FILES_UNDELETE, capability.getFilesUndelete().getValue()); cv.put(ProviderTableMeta.CAPABILITIES_FILES_VERSIONING, capability.getFilesVersioning().getValue()); if (capabilityExists(mAccount.name)) { if (getContentResolver() != null) { getContentResolver().update(ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv, ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=?", new String[] { mAccount.name }); } else {/*from w w w . j a v a 2 s .co m*/ try { getContentProviderClient().update(ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv, ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME + "=?", new String[] { mAccount.name }); } catch (RemoteException e) { Log_OC.e(TAG, "Fail to insert insert file to database " + e.getMessage()); } } } else { Uri result_uri = null; if (getContentResolver() != null) { result_uri = getContentResolver().insert(ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv); } else { try { result_uri = getContentProviderClient().insert(ProviderTableMeta.CONTENT_URI_CAPABILITIES, cv); } catch (RemoteException e) { Log_OC.e(TAG, "Fail to insert insert capability to database " + e.getMessage()); } } if (result_uri != null) { long new_id = Long.parseLong(result_uri.getPathSegments().get(1)); capability.setId(new_id); capability.setAccountName(mAccount.name); } } return capability; }
From source file:org.path.episample.android.activities.MainMenuActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // android.os.Debug.waitForDebugger(); mPropertyManager = new PropertyManager(this); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); // must be at the beginning of any activity that can be called from an // external intent setAppName("survey"); Uri uri = getIntent().getData(); Uri formUri = null;/* w w w. jav a 2s .c o m*/ if (uri != null) { // initialize to the URI, then we will customize further based upon the // savedInstanceState... final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI; final Uri uriWebView = UrlUtils.getWebViewContentUri(this); if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme()) && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else if (segments != null && segments.size() >= 2) { String appName = segments.get(0); setAppName(appName); formUri = Uri.withAppendedPath(Uri.withAppendedPath(uriFormsProvider, appName), segments.get(1)); } else { assignContentView(); createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2), EXIT); return; } } else if (uri.getScheme().equals(uriWebView.getScheme()) && uri.getAuthority().equals(uriWebView.getAuthority()) && uri.getPort() == uriWebView.getPort()) { List<String> segments = uri.getPathSegments(); if (segments != null && segments.size() == 1) { String appName = segments.get(0); setAppName(appName); } else { assignContentView(); createErrorDialog(getString(R.string.invalid_uri_expecting_one_segment, uri.toString()), EXIT); return; } } else { assignContentView(); createErrorDialog(getString(R.string.unrecognized_uri, uri.toString(), uriWebView.toString(), uriFormsProvider.toString()), EXIT); return; } } if (savedInstanceState != null) { // if appName is explicitly set, use it... setAppName(savedInstanceState.containsKey(APP_NAME) ? savedInstanceState.getString(APP_NAME) : getAppName()); if (savedInstanceState.containsKey(CONFLICT_TABLES)) { mConflictTables = savedInstanceState.getBundle(CONFLICT_TABLES); } } WebLogger.getLogger(getAppName()).i(t, "Starting up, creating directories"); try { String appName = getAppName(); if (appName != null && appName.length() != 0) { ODKFileUtils.verifyExternalStorageAvailability(); ODKFileUtils.assertDirectoryStructure(appName); } } catch (RuntimeException e) { assignContentView(); createErrorDialog(e.getMessage(), EXIT); return; } if (savedInstanceState != null) { // if we are restoring, assume that initialization has already occurred. pageWaitingForData = savedInstanceState.containsKey(PAGE_WAITING_FOR_DATA) ? savedInstanceState.getString(PAGE_WAITING_FOR_DATA) : null; pathWaitingForData = savedInstanceState.containsKey(PATH_WAITING_FOR_DATA) ? savedInstanceState.getString(PATH_WAITING_FOR_DATA) : null; actionWaitingForData = savedInstanceState.containsKey(ACTION_WAITING_FOR_DATA) ? savedInstanceState.getString(ACTION_WAITING_FOR_DATA) : null; currentFragment = ScreenList.valueOf(savedInstanceState.containsKey(CURRENT_FRAGMENT) ? savedInstanceState.getString(CURRENT_FRAGMENT) : currentFragment.name()); if (savedInstanceState.containsKey(FORM_URI)) { FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), Uri.parse(savedInstanceState.getString(FORM_URI))); if (newForm != null) { setAppName(newForm.appName); setCurrentForm(newForm); } } setInstanceId(savedInstanceState.containsKey(INSTANCE_ID) ? savedInstanceState.getString(INSTANCE_ID) : getInstanceId()); setUploadTableId( savedInstanceState.containsKey(UPLOAD_TABLE_ID) ? savedInstanceState.getString(UPLOAD_TABLE_ID) : getUploadTableId()); String tmpScreenPath = savedInstanceState.containsKey(SCREEN_PATH) ? savedInstanceState.getString(SCREEN_PATH) : getScreenPath(); String tmpControllerState = savedInstanceState.containsKey(CONTROLLER_STATE) ? savedInstanceState.getString(CONTROLLER_STATE) : getControllerState(); setSectionScreenState(tmpScreenPath, tmpControllerState); setAuxillaryHash( savedInstanceState.containsKey(AUXILLARY_HASH) ? savedInstanceState.getString(AUXILLARY_HASH) : getAuxillaryHash()); if (savedInstanceState.containsKey(SESSION_VARIABLES)) { sessionVariables = savedInstanceState.getBundle(SESSION_VARIABLES); } if (savedInstanceState.containsKey(SECTION_STATE_SCREEN_HISTORY)) { sectionStateScreenHistory = savedInstanceState.getParcelableArrayList(SECTION_STATE_SCREEN_HISTORY); } } else if (formUri != null) { // request specifies a specific formUri -- try to open that FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri); if (newForm == null) { // can't find it -- launch the initialization dialog to hopefully // discover it. WebLogger.getLogger(getAppName()).i(t, "onCreate -- calling setRunInitializationTask"); Survey.getInstance().setRunInitializationTask(getAppName()); currentFragment = ScreenList.WEBKIT; } else { transitionToFormHelper(uri, newForm); } } assignContentView(); }
From source file:com.ichi2.anki.provider.CardContentProvider.java
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Timber.d("CardContentProvider.query"); Collection col = CollectionHelper.getInstance().getCol(getContext()); if (col == null) { return null; }/*from ww w . j av a 2 s. c o m*/ // Find out what data the user is requesting int match = sUriMatcher.match(uri); switch (match) { case NOTES: { /* Search for notes */ // TODO: Allow sort order, then also update description in FlashCardContract String columnsStr = proj2str(projection); String query = (selection != null) ? selection : ""; List<Long> noteIds = col.findNotes(query); if ((noteIds != null) && (!noteIds.isEmpty())) { String selectedIds = "id in " + Utils.ids2str(noteIds); Cursor cur; try { cur = col.getDb().getDatabase() .rawQuery("select " + columnsStr + " from notes where " + selectedIds, null); } catch (SQLException e) { throw new IllegalArgumentException("Not possible to query for data for IDs " + selectedIds, e); } return cur; } else { return null; } } case NOTES_ID: { /* Direct access note */ long noteId; noteId = Long.parseLong(uri.getPathSegments().get(1)); String columnsStr = proj2str(projection); String selectedIds = "id = " + noteId; Cursor cur; try { cur = col.getDb().getDatabase() .rawQuery("select " + columnsStr + " from notes where " + selectedIds, null); } catch (SQLException e) { throw new IllegalArgumentException("Not possible to query for data for ID \"" + noteId + "\"", e); } return cur; } case NOTES_ID_CARDS: { Note currentNote = getNoteFromUri(uri, col); String[] columns = ((projection != null) ? projection : FlashCardsContract.Card.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); for (Card currentCard : currentNote.cards()) { addCardToCursor(currentCard, rv, col, columns); } return rv; } case NOTES_ID_CARDS_ORD: { Card currentCard = getCardFromUri(uri, col); String[] columns = ((projection != null) ? projection : FlashCardsContract.Card.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); addCardToCursor(currentCard, rv, col, columns); return rv; } case MODELS: { HashMap<Long, JSONObject> models = col.getModels().getModels(); String[] columns = ((projection != null) ? projection : FlashCardsContract.Model.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); for (Long modelId : models.keySet()) { addModelToCursor(modelId, models, rv, columns); } return rv; } case MODELS_ID: { long modelId = getModelIdFromUri(uri, col); String[] columns = ((projection != null) ? projection : FlashCardsContract.Model.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); HashMap<Long, JSONObject> models = col.getModels().getModels(); addModelToCursor(modelId, models, rv, columns); return rv; } case MODELS_ID_TEMPLATES: { /* Direct access model templates */ JSONObject currentModel = col.getModels().get(getModelIdFromUri(uri, col)); String[] columns = ((projection != null) ? projection : CardTemplate.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); try { JSONArray templates = currentModel.getJSONArray("tmpls"); for (int idx = 0; idx < templates.length(); idx++) { JSONObject template = templates.getJSONObject(idx); addTemplateToCursor(template, currentModel, idx + 1, rv, columns); } } catch (JSONException e) { throw new IllegalArgumentException("Model is malformed", e); } return rv; } case MODELS_ID_TEMPLATES_ID: { /* Direct access model template with specific ID */ int ord = Integer.parseInt(uri.getLastPathSegment()); JSONObject currentModel = col.getModels().get(getModelIdFromUri(uri, col)); String[] columns = ((projection != null) ? projection : CardTemplate.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); try { JSONObject template = getTemplateFromUri(uri, col); addTemplateToCursor(template, currentModel, ord + 1, rv, columns); } catch (JSONException e) { throw new IllegalArgumentException("Model is malformed", e); } return rv; } case SCHEDULE: { String[] columns = ((projection != null) ? projection : FlashCardsContract.ReviewInfo.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); long selectedDeckBeforeQuery = col.getDecks().selected(); long deckIdOfTemporarilySelectedDeck = -1; int limit = 1; //the number of scheduled cards to return int selectionArgIndex = 0; //parsing the selection arguments if (selection != null) { String[] args = selection.split(","); //split selection to get arguments like "limit=?" for (String arg : args) { String[] keyAndValue = arg.split("="); //split arguments into key ("limit") and value ("?") try { //check if value is a placeholder ("?"), if so replace with the next value of selectionArgs String value = keyAndValue[1].trim().equals("?") ? selectionArgs[selectionArgIndex++] : keyAndValue[1]; if (keyAndValue[0].trim().equals("limit")) { limit = Integer.valueOf(value); } else if (keyAndValue[0].trim().equals("deckID")) { deckIdOfTemporarilySelectedDeck = Long.valueOf(value); if (!selectDeckWithCheck(col, deckIdOfTemporarilySelectedDeck)) { return rv; //if the provided deckID is wrong, return empty cursor. } } } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } } //retrieve the number of cards provided by the selection parameter "limit" col.getSched().reset(); for (int k = 0; k < limit; k++) { Card currentCard = col.getSched().getCard(); if (currentCard != null) { int buttonCount = col.getSched().answerButtons(currentCard); JSONArray buttonTexts = new JSONArray(); for (int i = 0; i < buttonCount; i++) { buttonTexts.put(col.getSched().nextIvlStr(getContext(), currentCard, i + 1)); } addReviewInfoToCursor(currentCard, buttonTexts, buttonCount, rv, col, columns); } else { break; } } if (deckIdOfTemporarilySelectedDeck != -1) {//if the selected deck was changed //change the selected deck back to the one it was before the query col.getDecks().select(selectedDeckBeforeQuery); } return rv; } case DECKS: { List<Sched.DeckDueTreeNode> allDecks = col.getSched().deckDueList(); String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, allDecks.size()); for (Sched.DeckDueTreeNode deck : allDecks) { long id = deck.did; String name = deck.names[0]; addDeckToCursor(id, name, getDeckCountsFromDueTreeNode(deck), rv, col, columns); } return rv; } case DECKS_ID: { /* Direct access deck */ String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); List<Sched.DeckDueTreeNode> allDecks = col.getSched().deckDueList(); long deckId; deckId = Long.parseLong(uri.getPathSegments().get(1)); for (Sched.DeckDueTreeNode deck : allDecks) { if (deck.did == deckId) { addDeckToCursor(deckId, deck.names[0], getDeckCountsFromDueTreeNode(deck), rv, col, columns); return rv; } } return rv; } case DECK_SELECTED: { long id = col.getDecks().selected(); String name = col.getDecks().name(id); String[] columns = ((projection != null) ? projection : FlashCardsContract.Deck.DEFAULT_PROJECTION); MatrixCursor rv = new MatrixCursor(columns, 1); JSONArray counts = new JSONArray(Arrays.asList(col.getSched().counts())); addDeckToCursor(id, name, counts, rv, col, columns); return rv; } default: // Unknown URI type throw new IllegalArgumentException("uri " + uri + " is not supported"); } }
From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java
private void doResolveIntent(Intent intent) { if (requireOpenDashboardOnStart(intent)) { long providerId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, -1L); mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L); if (providerId == -1L || mLastAccountId == -1L) { finish();//from w ww .j a v a2 s . c o m } else { // mChatSwitcher.open(); } return; } if (ImServiceConstants.ACTION_MANAGE_SUBSCRIPTION.equals(intent.getAction())) { long providerId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, -1); mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L); String from = intent.getStringExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS); if ((providerId == -1) || (from == null)) { finish(); } else { showSubscriptionDialog(providerId, from); } } else if (intent != null) { Uri data = intent.getData(); if (intent.getBooleanExtra("showaccounts", false)) mDrawer.openDrawer(GravityCompat.START); if (data != null) { if (data.getScheme() != null && data.getScheme().equals("immu")) { String user = data.getUserInfo(); String host = data.getHost(); String path = null; if (data.getPathSegments().size() > 0) path = data.getPathSegments().get(0); if (host != null && path != null) { IImConnection connMUC = findConnectionForGroupChat(user, host); if (connMUC != null) { startGroupChat(path, host, user, connMUC); setResult(RESULT_OK); } else { mHandler.showAlert("Connection Error", "Unable to find a connection to join a group chat from. Please sign in and try again."); setResult(Activity.RESULT_CANCELED); finish(); } } } else { String type = getContentResolver().getType(data); if (Imps.Chats.CONTENT_ITEM_TYPE.equals(type)) { long requestedContactId = ContentUris.parseId(data); Cursor cursorChats = mChatPagerAdapter.getCursor(); if (cursorChats != null) { cursorChats.moveToPosition(-1); int posIdx = 1; boolean foundChatView = false; while (cursorChats.moveToNext()) { long chatId = cursorChats.getLong(ChatView.CONTACT_ID_COLUMN); if (chatId == requestedContactId) { mChatPager.setCurrentItem(posIdx); foundChatView = true; break; } posIdx++; } if (!foundChatView) { Uri.Builder builder = Imps.Contacts.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, requestedContactId); Cursor cursor = getContentResolver().query(builder.build(), ChatView.CHAT_PROJECTION, null, null, null); try { if (cursor.getCount() > 0) { cursor.moveToFirst(); openExistingChat(cursor); } } finally { cursor.close(); } } } } else if (Imps.Invitation.CONTENT_ITEM_TYPE.equals(type)) { //chatView.bindInvitation(ContentUris.parseId(data)); } } } else if (intent.hasExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID)) { //set the current account id mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L); //move the pager back to the first page if (mChatPager != null) mChatPager.setCurrentItem(0); } else { // refreshConnections(); } } }
From source file:org.awesomeapp.messenger.ui.ConversationView.java
private void sendStickerCode(Uri assetUri) { StringBuffer stickerCode = new StringBuffer(); stickerCode.append(":"); stickerCode.append(assetUri.getPathSegments().get(assetUri.getPathSegments().size() - 2)); stickerCode.append("-"); stickerCode.append(assetUri.getLastPathSegment().split("\\.")[0]); stickerCode.append(":"); sendMessageAsync(stickerCode.toString()); }
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 {//from w w w .j a v a 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:im.vector.activity.RoomActivity.java
/** * Send a list of images from their URIs * @param mediaUris the media URIs//from w ww . ja v a 2 s. c o m */ private void sendMedias(final ArrayList<Uri> mediaUris) { final View progressBackground = findViewById(R.id.medias_processing_progress_background); final View progress = findViewById(R.id.medias_processing_progress); progressBackground.setVisibility(View.VISIBLE); progress.setVisibility(View.VISIBLE); final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread"); handlerThread.start(); final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper()); Runnable r = new Runnable() { @Override public void run() { handler.post(new Runnable() { public void run() { final int mediaCount = mediaUris.size(); for (Uri anUri : mediaUris) { // crash from Google Analytics : null URI on a nexus 5 if (null != anUri) { final Uri mediaUri = anUri; String filename = null; if (mediaUri.toString().startsWith("content://")) { Cursor cursor = null; try { cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { filename = cursor .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } catch (Exception e) { Log.e(LOG_TAG, "cursor.getString " + e.getMessage()); } finally { cursor.close(); } if (TextUtils.isEmpty(filename)) { List uriPath = mediaUri.getPathSegments(); filename = (String) uriPath.get(uriPath.size() - 1); } } else if (mediaUri.toString().startsWith("file://")) { // try to retrieve the filename from the file url. try { filename = anUri.getLastPathSegment(); } catch (Exception e) { } if (TextUtils.isEmpty(filename)) { filename = null; } } final String fFilename = filename; ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this, mediaUri); if (null == resource) { RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { handlerThread.quit(); progressBackground.setVisibility(View.GONE); progress.setVisibility(View.GONE); Toast.makeText(RoomActivity.this, getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG) .show(); } ; }); return; } // save the file in the filesystem String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null, resource.mimeType); String mimeType = resource.mimeType; Boolean isManaged = false; if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) { // manage except if there is an error isManaged = true; // try to retrieve the gallery thumbnail // if the image comes from the gallery.. Bitmap thumbnailBitmap = null; try { ContentResolver resolver = getContentResolver(); List uriPath = mediaUri.getPathSegments(); long imageId = -1; String lastSegment = (String) uriPath.get(uriPath.size() - 1); // > Kitkat if (lastSegment.startsWith("image:")) { lastSegment = lastSegment.substring("image:".length()); } imageId = Long.parseLong(lastSegment); thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null); } catch (Exception e) { Log.e(LOG_TAG, "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage()); } double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith(); double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight(); // no thumbnail has been found or the mimetype is unknown if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight) || (thumbnailBitmap.getWidth() > thumbnailWidth)) { // need to decompress the high res image BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; resource = ResourceUtils.openResource(RoomActivity.this, mediaUri); // get the full size bitmap Bitmap fullSizeBitmap = null; if (null == thumbnailBitmap) { fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream, null, options); } if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) { double imageWidth; double imageHeight; if (null == thumbnailBitmap) { imageWidth = fullSizeBitmap.getWidth(); imageHeight = fullSizeBitmap.getHeight(); } else { imageWidth = thumbnailBitmap.getWidth(); imageHeight = thumbnailBitmap.getHeight(); } if (imageWidth > imageHeight) { thumbnailHeight = thumbnailWidth * imageHeight / imageWidth; } else { thumbnailWidth = thumbnailHeight * imageWidth / imageHeight; } try { thumbnailBitmap = Bitmap.createScaledBitmap( (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap, (int) thumbnailWidth, (int) thumbnailHeight, false); } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage()); } } // the valid mimetype is not provided if ("image/*".equals(mimeType)) { // make a jpg snapshot. mimeType = null; } // unknown mimetype if ((null == mimeType) || (mimeType.startsWith("image/"))) { try { // try again if (null == fullSizeBitmap) { System.gc(); fullSizeBitmap = BitmapFactory .decodeStream(resource.contentStream, null, options); } if (null != fullSizeBitmap) { Uri uri = Uri.parse(mediaUrl); if (null == mimeType) { // the images are save in jpeg format mimeType = "image/jpeg"; } resource.contentStream.close(); resource = ResourceUtils.openResource(RoomActivity.this, mediaUri); try { mMediasCache.saveMedia(resource.contentStream, uri.getPath(), mimeType); } catch (OutOfMemoryError ex) { Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage()); } } else { isManaged = false; } resource.contentStream.close(); } catch (Exception e) { isManaged = false; Log.e(LOG_TAG, "sendMedias " + e.getMessage()); } } // reduce the memory consumption if (null != fullSizeBitmap) { fullSizeBitmap.recycle(); System.gc(); } } String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null); if (null != thumbnailBitmap) { thumbnailBitmap.recycle(); } // if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType)) && (null != mediaUrl)) { Uri imageUri = Uri.parse(mediaUrl); // get the exif rotation angle final int rotationAngle = ImageUtils .getRotationAngleForBitmap(RoomActivity.this, imageUri); if (0 != rotationAngle) { // always apply the rotation to the image ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle, mMediasCache); // the high res media orientation should be not be done on uploading //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache)) } } // is the image content valid ? if (isManaged && (null != thumbnailURL)) { final String fThumbnailURL = thumbnailURL; final String fMediaUrl = mediaUrl; final String fMimeType = mimeType; RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { // if there is only one image if (mediaCount == 1) { // display an image preview before sending it mPendingThumbnailUrl = fThumbnailURL; mPendingMediaUrl = fMediaUrl; mPendingMimeType = fMimeType; mPendingFilename = fFilename; mConsoleMessageListFragment.scrollToBottom(); manageSendMoreButtons(); } else { mConsoleMessageListFragment.uploadImageContent(fThumbnailURL, fMediaUrl, fFilename, fMimeType); } } }); } } // default behaviour if ((!isManaged) && (null != mediaUrl)) { final String fMediaUrl = mediaUrl; final String fMimeType = mimeType; RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mConsoleMessageListFragment.uploadMediaContent(fMediaUrl, fMimeType, fFilename); } }); } } } RoomActivity.this.runOnUiThread(new Runnable() { @Override public void run() { handlerThread.quit(); progressBackground.setVisibility(View.GONE); progress.setVisibility(View.GONE); }; }); } }); } }; Thread t = new Thread(r); t.start(); }
From source file:org.thomnichols.android.gmarks.GmarksProvider.java
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); // Log.d(TAG, "Managed query: " + uri); String groupBy = null;/*from w w w.j a v a 2 s. com*/ String orderBy = null; String limit = null; switch (sUriMatcher.match(uri)) { case BOOKMARKS_URI: qb.setTables(BOOKMARKS_TABLE_NAME); qb.setProjectionMap(bookmarksProjectionMap); String labelID = uri.getQueryParameter("label_id"); if (labelID != null) { qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id"); qb.appendWhere("bookmark_labels.label_id=?"); selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelID }); } break; case BOOKMARK_SEARCH_URI: case BOOKMARK_SEARCH_SUGGEST_URI: String query = null; if (sUriMatcher.match(uri) == BOOKMARK_SEARCH_SUGGEST_URI) { qb.setProjectionMap(searchSuggestProjectionMap); // path looks like "search_suggest_query/[query]?limit=50 query = uri.getLastPathSegment(); limit = uri.getQueryParameter("limit"); if (sortOrder == null) sortOrder = Bookmark.Columns.SORT_MODIFIED; } else query = uri.getQueryParameter("q"); if (query != null) { qb.setTables("bookmarks join bookmarks_FTS on bookmarks._id = bookmarks_FTS.docid"); qb.appendWhere("bookmarks_FTS MATCH ?"); if (selectionArgs == null) selectionArgs = new String[] { query }; else selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { query }); } else if (selectionArgs == null || selectionArgs.length < 1) throw new IllegalArgumentException("No search criteria given for query!"); break; case BOOKMARK_ID_URI: qb.setTables(BOOKMARKS_TABLE_NAME); qb.setProjectionMap(bookmarksProjectionMap); qb.appendWhere(Bookmark.Columns._ID + "=" + uri.getPathSegments().get(1)); break; case LABELS_URI: qb.setTables("labels join bookmark_labels on labels._id = bookmark_labels.label_id"); groupBy = "label"; if (sortOrder == null) sortOrder = Label.Columns.DEFAULT_SORT_ORDER; qb.setProjectionMap(labelsProjectionMap); break; case LIVE_FOLDER_BOOKMARKS_URI: qb.setTables(BOOKMARKS_TABLE_NAME); qb.setProjectionMap(sLiveFolderProjectionMap); String labelId = uri.getQueryParameter("label_id"); if (labelId != null) { qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id"); qb.appendWhere("bookmark_labels.label_id=?"); selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelId }); } sortOrder = "modified DESC"; // for some reason this gets set to 'name ASC' break; case BOOKMARK_LISTS_URI: qb.setTables(BookmarkList.TABLE_NAME); qb.setProjectionMap(listsProjectionMap); if (sortOrder == null) sortOrder = BookmarkList.Columns.DEFAULT_SORT_ORDER; String type = uri.getQueryParameter(BookmarkList.PARAM_CATEGORY); if (BookmarkList.LISTS_PRIVATE.equals(type)) qb.appendWhere("owned=1"); else if (BookmarkList.LISTS_SHARED.equals(type)) qb.appendWhere("shared=1"); else if (BookmarkList.LISTS_PUBLIC.equals(type)) qb.appendWhere("publshed=1"); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // If no sort order is specified use the default if (TextUtils.isEmpty(sortOrder)) { orderBy = Bookmark.Columns.DEFAULT_SORT_ORDER; } else { orderBy = sortOrder; } // Get the database and run the query SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy, limit); // Tell the cursor what uri to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; }
From source file:androidVNC.VncCanvasActivity.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); database = new VncDatabase(this); connection = new ConnectionBean(); Intent i = getIntent();//from w ww . jav a2 s. c o m Uri data = i.getData(); if ((data != null) && (data.getScheme().equals("vnc"))) { String host = data.getHost(); // This should not happen according to Uri contract, but bug introduced in Froyo (2.2) // has made this parsing of host necessary int index = host.indexOf(':'); int port; if (index != -1) { try { port = Integer.parseInt(host.substring(index + 1)); } catch (NumberFormatException nfe) { port = 0; } host = host.substring(0, index); } else { port = data.getPort(); } if (host.equals(VncConstants.CONNECTION)) { if (connection.Gen_read(database.getReadableDatabase(), port)) { MostRecentBean bean = androidVNC.getMostRecent(database.getReadableDatabase()); if (bean != null) { bean.setConnectionId(connection.get_Id()); bean.Gen_update(database.getWritableDatabase()); } } } else { connection.setAddress(host); connection.setNickname(connection.getAddress()); connection.setPort(port); List<String> path = data.getPathSegments(); if (path.size() >= 1) { connection.setColorModel(path.get(0)); } if (path.size() >= 2) { connection.setPassword(path.get(1)); } connection.save(database.getWritableDatabase()); } } else { Bundle extras = i.getExtras(); if (extras != null) { connection.Gen_populate((ContentValues) extras.getParcelable(VncConstants.CONNECTION)); } if (connection.getPort() == 0) connection.setPort(5900); // Parse a HOST:PORT entry String host = connection.getAddress(); if (host.indexOf(':') > -1) { String p = host.substring(host.indexOf(':') + 1); try { connection.setPort(Integer.parseInt(p)); } catch (Exception e) { } connection.setAddress(host.substring(0, host.indexOf(':'))); } } try { setContentView(fi.aalto.openoranges.project1.mcc.R.layout.canvas); vncCanvas = (VncCanvas) findViewById(fi.aalto.openoranges.project1.mcc.R.id.vnc_canvas); zoomer = (ZoomControls) findViewById(R.id.zoomer); } catch (Exception e) { e.printStackTrace(); } vncCanvas.initializeVncCanvas(connection, new Runnable() { public void run() { setModes(); } }); vncCanvas.setOnGenericMotionListener(this); zoomer.hide(); zoomer.setOnZoomInClickListener(new View.OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { showZoomer(true); vncCanvas.scaling.zoomIn(VncCanvasActivity.this); } }); zoomer.setOnZoomOutClickListener(new View.OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { showZoomer(true); vncCanvas.scaling.zoomOut(VncCanvasActivity.this); } }); zoomer.setOnZoomKeyboardClickListener(new View.OnClickListener() { /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMgr.toggleSoftInput(0, 0); } }); panner = new Panner(this, vncCanvas.handler); inputHandler = getInputHandlerById(fi.aalto.openoranges.project1.mcc.R.id.itemInputFitToScreen); mToken = getIntent().getStringExtra("token"); mId = getIntent().getStringExtra("id"); mName = getIntent().getStringExtra("name"); //listener for the back-button registerClickCallback(); //Notification in status bar NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(VncCanvasActivity.this) .setSmallIcon(R.drawable.icon_white).setContentTitle(mName + " running") .setContentText("Click to open the application screen"); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(VncCanvasActivity.this, VncCanvasActivity.class); resultIntent.setAction(Long.toString(System.currentTimeMillis())); mBuilder.setContentIntent(PendingIntent.getActivity(VncCanvasActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)); NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // mNotifyID allows you to update the notification later on. mNotificationManager.notify(mNotifyId, mBuilder.build()); startService(); }