Search code examples
androiduriandroid-contentprovider

How to get everything except the fragment (row number) from an android content provider uri?


I would like to retrieve a ContentURI with appended id and be able to strip the id out.

In other words, I have a Content URI such as:

   org.mycontentproviderAuthority/path1/path2/3 

and I would like to get

   org.mycontentproviderAuthority/path1/path2/

Is it possible to do that preferably with Uri methods? I mean I guess I could use a String tokenizer to remove the last digit, but Id assume that a uri api for that would be safer.

I tried uri.getAuthority() + uri.getPath() but that gives me back the whole ContentUri.


Solution

  • You might use the following:

    static public Uri getUriWithoutLastNPathParts(final Uri uri, final int n) {
        final List<String> segments = uri.getPathSegments();
        final String[] newSegments = new String[segments.size() - n];
    
        final Uri.Builder builder = new Uri.Builder();
        builder.encodedAuthority(uri.getAuthority());
        builder.encodedPath(uri.getPath());
        builder.encodedQuery(uri.getQuery());
    
        // no "appendPath", it messes up the thing
        for (int i = 0; i < newSegments.length; i++) {
            newSegments[i] = segments.get(i);
        }
        builder.encodedPath(TextUtils.join("/", newSegments));
    
        return builder.build();
    }
    

    Usage:

    Uri uri = Uri.parse("org.mycontentproviderAuthority/path1/path2/3");
    Log.i("Segments", uri + " " + getUriWithoutLastNPathParts(uri, 1));
    
    uri = Uri.parse("org.mycontentproviderAuthority/path1/path2/3?foo=bar");
    Log.i("Segments", uri + " " + getUriWithoutLastNPathParts(uri, 2));