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:pl.selvin.android.syncframework.content.BaseContentProvider.java

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final int code = contentHelper.matchUri(uri);
    if (code != UriMatcher.NO_MATCH) {
        if (code == ContentHelper.uriSyncCode) {
            if (DEBUG) {
                Log.d(TAG, "CP-update-sync: " + uri.toString());
            }//from   w w w.  j  a va  2 s. c o m
            return (Sync(uri.getPathSegments().get(1), uri.getPathSegments().get(2), selection) ? 1 : 0);
        }
        final TableInfo tab = contentHelper.getTableFromCode(code & ContentHelper.uriCode);
        if (tab.readonly) {
            throw new IllegalArgumentException("Table " + tab.name + " is readonly.");
        }
        if (isItemCode(code)) {
            if (isItemRowIDCode(code)) {
                selection = "isDeleted=0 AND ROWID=" + uri.getPathSegments().get(2)
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
            } else {
                selection = "isDeleted=0" + tab.getSelection()
                        + (!TextUtils.isEmpty(selection) ? "(" + selection + ") AND " : "");
                int i = 0;
                final String[] old = selectionArgs;
                final int len = (old == null) ? 0 : old.length;
                selectionArgs = new String[len + tab.primaryKey.length];
                for (; i < tab.primaryKey.length; i++) {
                    selectionArgs[i] = uri.getPathSegments().get(i);
                }
                if (len > 0) {
                    for (; i < old.length; i++) {
                        selectionArgs[i] = old[i - tab.primaryKey.length];
                    }
                }
            }
        } else {
            selection = "isDeleted=0" + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
        }
        boolean syncToNetwork = checkSyncToNetwork(uri);
        values.put("isDirty", 1);
        int ret = getWritableDatabase().update(tab.name, values, selection, selectionArgs);
        if (ret > 0) {
            final ContentResolver cr = getContext().getContentResolver();
            cr.notifyChange(uri, null, syncToNetwork);
            for (String n : tab.notifyUris) {
                cr.notifyChange(Uri.parse(n), null, syncToNetwork);
            }
        }
        return ret;
    }
    throw new IllegalArgumentException("Unknown Uri " + uri);
}

From source file:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int count;/*ww  w . j  ava2 s . co  m*/
    switch (sUriMatcher.match(uri)) {
    case BOOKMARKS_URI:
        count = db.update(BOOKMARKS_TABLE_NAME, values, where, whereArgs);
        break;

    case BOOKMARK_ID_URI:
        String noteId = uri.getPathSegments().get(1);
        count = db.update(BOOKMARKS_TABLE_NAME, values,
                Bookmark.Columns._ID + "=" + noteId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
                whereArgs);
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

From source file:onion.chat.MainActivity.java

void handleIntent() {

    Intent intent = getIntent();//www . j  a v a 2 s .c  o m
    if (intent == null) {
        return;
    }

    Uri uri = intent.getData();
    if (uri == null) {
        return;
    }

    if (!uri.getHost().equals("chat.onion")) {
        return;
    }

    List<String> pp = uri.getPathSegments();
    String address = pp.size() > 0 ? pp.get(0) : null;
    String name = pp.size() > 1 ? pp.get(1) : "";
    if (address == null) {
        return;
    }

    addContact(address, name);
    inform();

}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

private void testOpportunisticConcurrencyOperationsFeatureHeader(
        OpportunisticConcurrencyTestOperation operation, final String expectedFeaturesHeader) {
    MobileServiceClient client = null;/*ww  w  .j ava2 s  . c  om*/
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    MobileServiceLocalStoreMock store = new MobileServiceLocalStoreMock();
    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
            String featuresHeaderName = "X-ZUMO-FEATURES";

            Header[] headers = request.getHeaders();
            String features = null;
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName() == featuresHeaderName) {
                    features = headers[i].getValue();
                }
            }

            if (features == null) {
                resultFuture.setException(new Exception("No " + featuresHeaderName + " header on API call"));
            } else if (!features.equals(expectedFeaturesHeader)) {
                resultFuture.setException(new Exception("Incorrect features header; expected "
                        + expectedFeaturesHeader + ", actual " + features));
            } else {
                ServiceFilterResponseMock response = new ServiceFilterResponseMock();
                Uri requestUri = Uri.parse(request.getUrl());
                String content = "{\"id\":\"the-id\",\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":33}";
                if (request.getMethod().equalsIgnoreCase("GET") && requestUri.getPathSegments().size() == 2) {
                    // GET which should return an array of results
                    content = "[" + content + "]";
                }
                response.setContent(content);
                resultFuture.set(response);
            }

            return resultFuture;
        }
    });

    try {
        Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
        tableDefinition.put("id", ColumnDataType.String);
        tableDefinition.put("firstName", ColumnDataType.String);
        tableDefinition.put("lastName", ColumnDataType.String);
        tableDefinition.put("age", ColumnDataType.Integer);
        store.defineTable("Person", tableDefinition);

        client.getSyncContext().initialize(store, new SimpleSyncHandler()).get();

        operation.executeOperation(client);
    } catch (Exception exception) {
        Throwable ex = exception;
        while (ex instanceof ExecutionException || ex instanceof MobileServiceException) {
            ex = ex.getCause();
        }
        fail(ex.getMessage());
    }
}

From source file:cm.aptoide.com.actionbarsherlock.widget.SuggestionsAdapter.java

public Drawable getTheDrawable(Uri uri) throws FileNotFoundException {
    String authority = uri.getAuthority();
    Resources r;//from  w  w  w .  j av  a2s.c om
    if (TextUtils.isEmpty(authority)) {
        throw new FileNotFoundException("No authority: " + uri);
    } else {
        try {
            r = mContext.getPackageManager().getResourcesForApplication(authority);
        } catch (NameNotFoundException ex) {
            throw new FileNotFoundException("No package found for authority: " + uri);
        }
    }
    List<String> path = uri.getPathSegments();
    if (path == null) {
        throw new FileNotFoundException("No path: " + uri);
    }
    int len = path.size();
    int id;
    if (len == 1) {
        try {
            id = Integer.parseInt(path.get(0));
        } catch (NumberFormatException e) {
            throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
        }
    } else if (len == 2) {
        id = r.getIdentifier(path.get(1), path.get(0), authority);
    } else {
        throw new FileNotFoundException("More than two path segments: " + uri);
    }
    if (id == 0) {
        throw new FileNotFoundException("No resource found for: " + uri);
    }
    return r.getDrawable(id);
}

From source file:android.support.v7.widget.SuggestionsAdapter.java

/**
 * Import of hidden method: ContentResolver.getResourceId(Uri).
 * Modified to return a drawable, rather than a hidden type.
 *///from  w  w w . java 2s  .co m
Drawable getDrawableFromResourceUri(Uri uri) throws FileNotFoundException {
    String authority = uri.getAuthority();
    Resources r;
    if (TextUtils.isEmpty(authority)) {
        throw new FileNotFoundException("No authority: " + uri);
    } else {
        try {
            r = mContext.getPackageManager().getResourcesForApplication(authority);
        } catch (NameNotFoundException ex) {
            throw new FileNotFoundException("No package found for authority: " + uri);
        }
    }
    List<String> path = uri.getPathSegments();
    if (path == null) {
        throw new FileNotFoundException("No path: " + uri);
    }
    int len = path.size();
    int id;
    if (len == 1) {
        try {
            id = Integer.parseInt(path.get(0));
        } catch (NumberFormatException e) {
            throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
        }
    } else if (len == 2) {
        id = r.getIdentifier(path.get(1), path.get(0), authority);
    } else {
        throw new FileNotFoundException("More than two path segments: " + uri);
    }
    if (id == 0) {
        throw new FileNotFoundException("No resource found for: " + uri);
    }
    return r.getDrawable(id);
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device./*from  www  . j ava 2 s  .c o  m*/
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceFeaturesTests.java

private void testSyncTableOperationsFeatureHeader(OfflineTableTestOperation operation,
        final String expectedFeaturesHeader) {
    MobileServiceClient client = null;// www.j  a va 2  s  .c  om
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    boolean fistPullPage = false;

    MobileServiceLocalStoreMock store = new MobileServiceLocalStoreMock();
    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
            String featuresHeaderName = "X-ZUMO-FEATURES";

            Header[] headers = request.getHeaders();
            String features = null;
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName() == featuresHeaderName) {
                    features = headers[i].getValue();
                }
            }

            if (features == null) {
                resultFuture.setException(new Exception("No " + featuresHeaderName + " header on API call"));
            } else if (!features.equals(expectedFeaturesHeader)) {
                resultFuture.setException(new Exception("Incorrect features header; expected "
                        + expectedFeaturesHeader + ", actual " + features));
            } else {
                ServiceFilterResponseMock response = new ServiceFilterResponseMock();
                Uri requestUri = Uri.parse(request.getUrl());

                String content = "[]";

                //if (fistPullPage) {
                content = "{\"id\":\"the-id\",\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":33}";

                if (request.getMethod().equalsIgnoreCase("GET") && requestUri.getPathSegments().size() == 2) {
                    // GET which should return an array of results
                    content = "[" + content + "]";
                }

                //fistPullPage = false;
                //}

                response.setContent(content);
                resultFuture.set(response);
            }

            return resultFuture;
        }
    });

    try {
        Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
        tableDefinition.put("id", ColumnDataType.String);
        tableDefinition.put("firstName", ColumnDataType.String);
        tableDefinition.put("lastName", ColumnDataType.String);
        tableDefinition.put("age", ColumnDataType.Integer);
        store.defineTable("Person", tableDefinition);

        client.getSyncContext().initialize(store, new SimpleSyncHandler()).get();

        MobileServiceSyncTable<PersonTestObjectWithStringId> typedTable = client
                .getSyncTable(PersonTestObjectWithStringId.class);
        MobileServiceJsonSyncTable jsonTable = client.getSyncTable("Person");
        operation.executeOperation(client, typedTable, jsonTable);
    } catch (Exception exception) {
        Throwable ex = exception;
        while (ex instanceof ExecutionException || ex instanceof MobileServiceException) {
            ex = ex.getCause();
        }
        fail(ex.getMessage());
    }
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    Timber.d("CardContentProvider.delete");
    Collection col = CollectionHelper.getInstance().getCol(getContext());
    if (col == null) {
        return 0;
    }//w w  w.  j a v  a2s.com
    switch (sUriMatcher.match(uri)) {
    case NOTES_ID:
        col.remNotes(new long[] { Long.parseLong(uri.getPathSegments().get(1)) });
        return 1;
    default:
        throw new UnsupportedOperationException();
    }
}

From source file:com.nononsenseapps.notepad.MainActivity.java

protected void createList(String title) {
    // I will not allow empty names for lists
    if (!title.equals("")) {
        ContentValues values = new ContentValues();
        values.put(NotePad.Lists.COLUMN_NAME_TITLE, title);
        // Add list
        Uri listUri = getContentResolver().insert(NotePad.Lists.CONTENT_URI, values);
        listIdToSelect = Long.parseLong(listUri.getPathSegments().get(NotePad.Lists.ID_PATH_POSITION));
        UpdateNotifier.notifyChangeList(getApplicationContext());
    }/*w  w  w .ja v  a  2s.  c o m*/
}