Example usage for android.net Uri getPathSegments

List of usage examples for android.net Uri getPathSegments

Introduction

In this page you can find the example usage for android.net Uri getPathSegments.

Prototype

public abstract List<String> getPathSegments();

Source Link

Document

Gets the decoded path segments.

Usage

From source file:org.floens.chan.ui.activity.ChanActivity.java

/**
 * Handle opening from an external url./*from w w  w .j a v a 2  s.co  m*/
 *
 * @param startUri
 */
private void handleIntentURI(Uri startUri) {
    Logger.d(TAG, "Opening " + startUri.getPath());

    List<String> parts = startUri.getPathSegments();

    if (parts.size() == 1) {
        // Board mode
        String rawBoard = parts.get(0);
        if (ChanApplication.getBoardManager().getBoardExists(rawBoard)) {
            startLoadingBoard(new Loadable(rawBoard));
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else if (parts.size() >= 3) {
        // Thread mode
        String rawBoard = parts.get(0);
        int no = -1;

        try {
            no = Integer.parseInt(parts.get(2));
        } catch (NumberFormatException e) {
        }

        int post = -1;
        String fragment = startUri.getFragment();
        if (fragment != null) {
            int index = fragment.indexOf("p");
            if (index >= 0) {
                try {
                    post = Integer.parseInt(fragment.substring(index + 1));
                } catch (NumberFormatException e) {
                }
            }
        }

        if (no >= 0 && ChanApplication.getBoardManager().getBoardExists(rawBoard)) {
            startLoadingThread(new Loadable(rawBoard, no));
            if (post >= 0) {
                threadFragment.highlightPost(post);
            }
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else {
        showUrlOpenPicker(startUri.toString());
    }
}

From source file:im.ene.lab.attiq.ui.activities.ProfileActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    ButterKnife.bind(this);

    setSupportActionBar(mToolbar);/*from  w  ww  .  j a va2 s  .com*/

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    // empty title at start
    setTitle("");

    mAppBarLayout.addOnOffsetChangedListener(mOffsetChangedListener);
    TypedValue typedValue = new TypedValue();
    mToolbar.getContext().getTheme().resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
    int titleColorId = typedValue.resourceId;
    mTitleColorSpan = new AlphaForegroundColorSpan(ContextCompat.getColor(this, titleColorId));

    typedValue = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
    int accentColorId = typedValue.resourceId;
    mImageBorderColor = ContextCompat.getColor(this, accentColorId);

    mRealm = Attiq.realm();
    mRealm.addChangeListener(this);

    Uri data = getIntent().getData();
    if (data != null) {
        List<String> paths = data.getPathSegments();
        if (!UIUtil.isEmpty(paths)) {
            Iterator<String> iterator = paths.iterator();
            while (iterator.hasNext()) {
                if ("users".equals(iterator.next())) {
                    mUserId = iterator.next();
                    break;
                }
            }
        }
    }

    mRefUser = mRealm.where(Profile.class).equalTo("token", PrefUtil.getCurrentToken()).findFirst();

    mProfile = mRealm.where(RProfile.class).equalTo(RProfile.FIELD_USER_NAME, mUserId).findFirst();
    if (mProfile == null) {
        mRealm.beginTransaction();
        mProfile = mRealm.createObject(RProfile.class);
        mProfile.setUserName(mUserId);
        mRealm.commitTransaction();
    }

    if (getSupportFragmentManager().findFragmentById(R.id.profile_info_tags) == null) {
        mTagFragment = UserTagsFragment.newInstance(mUserId);
        getSupportFragmentManager().beginTransaction().replace(R.id.profile_info_tags, mTagFragment).commit();
    }

    mPagerAdapter = new ProfileViewPagerAdapter(getSupportFragmentManager(), mUserId);
    mViewPager.setAdapter(mPagerAdapter);
    mViewPager.setOffscreenPageLimit(mPagerAdapter.getCount());
    mTabLayout.setupWithViewPager(mViewPager);

    // find a local user, if there is one, update current profile
    User user = mRealm.where(User.class).equalTo("id", mUserId).findFirst();
    if (user != null) {
        EventBus.getDefault().post(new UserFetchedEvent(getClass().getSimpleName(), true, null, user));
    }
}

From source file:org.bohrmeista.chan.ui.activity.BoardActivity.java

/**
 * Handle opening from an external url.//  ww w.  ja  v  a2  s .c  o  m
 *
 * @param startUri
 */
private void handleIntentURI(Uri startUri) {
    Logger.d(TAG, "Opening " + startUri.getPath());

    List<String> parts = startUri.getPathSegments();

    if (parts.size() == 1) {
        // Board mode
        String rawBoard = parts.get(0);
        startLoadingBoard(new Loadable(rawBoard));
    } else if (parts.size() >= 3) {
        // Thread mode
        String rawBoard = parts.get(0);
        int no = -1;

        try {
            Matcher matcher = THREAD_URL_PATTERN.matcher(parts.get(2));
            if (matcher.find())
                no = Integer.parseInt(matcher.group(1));
        } catch (NumberFormatException e) {
        }

        int post = -1;
        String fragment = startUri.getFragment();
        if (fragment != null) {
            int index = fragment.indexOf("p");
            if (index >= 0) {
                try {
                    post = Integer.parseInt(fragment.substring(index + 1));
                } catch (NumberFormatException e) {
                }
            }
        }

        if (no >= 0) {
            startLoadingThread(new Loadable(rawBoard, no));
            if (post >= 0) {
                threadFragment.highlightPost(post);
            }
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else {
        showUrlOpenPicker(startUri.toString());
    }
}

From source file:org.mariotaku.twidere.provider.TweetStoreProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    final String table = getTableNameForContentUri(uri);
    if (table == null)
        return null;
    if (TABLE_DIRECT_MESSAGES_CONVERSATION.equals(table)) {
        final List<String> segments = uri.getPathSegments();
        if (segments.size() != 3)
            return null;
        final String query = Conversation.QueryBuilder.buildByConversationId(projection,
                Long.parseLong(segments.get(1)), Long.parseLong(segments.get(2)), selection, sortOrder);
        return mDatabase.rawQuery(query, selectionArgs);
    } else if (TABLE_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME.equals(table)) {
        final List<String> segments = uri.getPathSegments();
        if (segments.size() != 3)
            return null;
        final String query = Conversation.QueryBuilder.buildByScreenName(projection,
                Long.parseLong(segments.get(1)), segments.get(2), selection, sortOrder);
        return mDatabase.rawQuery(query, selectionArgs);
    } else if (TABLE_DIRECT_MESSAGES.equals(table)) {
        final String query = DirectMessages.QueryBuilder.build(projection, selection, sortOrder);
        return mDatabase.rawQuery(query, selectionArgs);
    } else if (TABLE_DIRECT_MESSAGES_CONVERSATIONS_ENTRY.equals(table))
        return mDatabase.rawQuery(ConversationsEntry.QueryBuilder.build(selection), null);
    return mDatabase.query(table, projection, selection, selectionArgs, null, null, sortOrder);
}

From source file:org.wingy.jp8chan.ui.activity.BoardActivity.java

/**
 * Handle opening from an external url.//from   w w  w . ja va  2s.  c om
 *
 * @param startUri
 */
private void handleIntentURI(Uri startUri) {
    Logger.d(TAG, "Opening " + startUri.getPath());

    List<String> parts = startUri.getPathSegments();

    if (parts.size() == 1) {
        // Board mode
        String rawBoard = parts.get(0);
        startLoadingBoard(new Loadable(rawBoard));
    } else if (parts.size() >= 3) {
        // Thread mode
        String rawBoard = parts.get(0);
        int no = -1;

        try {
            Matcher matcher = THREAD_URL_PATTERN.matcher(parts.get(2));
            if (matcher.find())
                no = Integer.parseInt(matcher.group(1));
        } catch (NumberFormatException e) {
        }

        int post = -1;
        String fragment = startUri.getFragment();
        if (fragment != null) {
            //int index = fragment.indexOf("q");
            //if (index >= 0) {
            try {
                post = Integer.parseInt(fragment);
            } catch (NumberFormatException e) {
            }
            //}
        }

        if (no >= 0) {
            startLoadingThread(new Loadable(rawBoard, no));
            if (post >= 0) {
                threadFragment.highlightPost(post);
            }
        } else {
            handleIntentURIFallback(startUri.toString());
        }
    } else {
        showUrlOpenPicker(startUri.toString());
    }
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs, String sortOrder) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }/*from   w ww. j  av a  2s .com*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    // Get the database and run the query
    SQLiteDatabase db = null;
    boolean success = false;
    Cursor c = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, whereId, whereIdArgs, null, null,
                sortOrder);
        success = true;
    } catch (Exception e) {
        log.w(t, "Unable to query database for appName: " + appName);
        return null;
    } finally {
        if (!success && db != null) {
            db.close();
        }
    }

    if (c == null) {
        log.w(t, "Unable to query database for appName: " + appName);
        return null;
    }
    // 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:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }/*from ww  w .ja  v a2  s. c  om*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    // ODK2: require FORM_MEDIA_PATH (different behavior -- ODK1 and
    // required FORM_FILE_PATH)
    if (!values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " must be specified.");
    }

    // Normalize path...
    File mediaPath = ODKFileUtils.asAppFile(appName,
            values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));

    // require that the form directory actually exists
    if (!mediaPath.exists()) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                + " directory does not exist: " + mediaPath.getAbsolutePath());
    }

    patchUpValues(appName, values);

    if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
        values.put(FormsColumns.DISPLAY_NAME, mediaPath.getName());
    }

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.FORM_ID, FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH };
    String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, mediaPath) };
    String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
    Cursor c = null;

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null);
            if (c == null) {
                throw new SQLException("FAILED Insert into " + uri
                        + " -- unable to query for existing records: " + mediaPath.getAbsolutePath());
            }
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri
                        + " -- row already exists for form directory: " + mediaPath.getAbsolutePath());
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        try {
            long rowId = db.insert(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            if (rowId > 0) {
                Uri formUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        values.getAsString(FormsColumns.FORM_ID));
                getContext().getContentResolver().notifyChange(formUri, null);
                Uri idUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        Long.toString(rowId));
                getContext().getContentResolver().notifyChange(idUri, null);

                return formUri;
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}//from  w  w w. j  a  v  a2 s.c o m
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    Cursor del = null;
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    try {
        del = this.query(uri, null, whereId, whereIdArgs, null);
        if (del == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }
        del.moveToPosition(-1);
        while (del.moveToNext()) {
            idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class,
                    del.getColumnIndex(FormsColumns._ID));
            tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.TABLE_ID));
            formIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.FORM_ID));
            File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)));
            mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
        }
    } catch (Exception e) {
        log.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (del != null && !del.isClosed()) {
            del.close();
        }
    }

    SQLiteDatabase db = null;
    int count;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform deletion " + e.toString());
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    // and attempt to move these directories to the stale forms location
    // so that they do not immediately get rescanned...

    for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
        try {
            moveDirectory(appName, entry.getValue(), entry.getKey());
        } catch (IOException e) {
            e.printStackTrace();
            log.e(t, "Unable to move directory " + e.toString());
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:org.rapidandroid.activity.FormReviewer.java

private void doRandomizedInjection() {
    Random random = new Random();

    // Debug.startMethodTracing("injection");
    for (int i = 0; i < 100; i++) {

        // first, let's get the
        String token = phones[random.nextInt(phones.length)];// Long.toString(Math.abs(r.nextLong()),
        // 36);/*from ww w.  j a  va 2 s  . co  m*/
        Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(this, token);

        Uri writeMessageUri = RapidSmsDBConstants.Message.CONTENT_URI;

        StringBuilder sb = this.generateRandomMessage();
        ContentValues messageValues = new ContentValues();
        messageValues.put(RapidSmsDBConstants.Message.MESSAGE, sb.toString());
        messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID());

        Date now = getRandomDate();

        messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(now));
        messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false);

        Uri msgUri = null;

        msgUri = getContentResolver().insert(writeMessageUri, messageValues);

        Vector<IParseResult> results = ParsingService.ParseMessage(mForm, sb.toString());
        ParsedDataTranslator.InsertFormData(this, mForm,
                Integer.valueOf(msgUri.getPathSegments().get(1)).intValue(), results);
    }

    Debug.stopMethodTracing();

}

From source file:org.opendatakit.services.instance.provider.InstanceProvider.java

@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {//from w  ww. ja  va 2s .  c  om
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    String tableId = segments.get(1);

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();

    boolean success = false;
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);

        Cursor c = db.query(tableId, projection, selection, selectionArgs, null, null, sortOrder, null);

        if (c == null) {
            return null;
        }

        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        c.registerDataSetObserver(new InvalidateMonitor(appName, dbHandleName));
        success = true;
        return c;
    } finally {
        if (db != null) {
            try {
                db.releaseReference();
            } finally {
                if (!success) {
                    // this closes the connection
                    // if it was successful, then the InvalidateMonitor will close the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                            dbHandleName);
                }
            }
        }
    }
}