Example usage for android.net Uri withAppendedPath

List of usage examples for android.net Uri withAppendedPath

Introduction

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

Prototype

public static Uri withAppendedPath(Uri baseUri, String pathSegment) 

Source Link

Document

Creates a new Uri by appending an already-encoded path segment to a base Uri.

Usage

From source file:com.android.contacts.common.model.ContactLoaderTest.java

public void testLoadContactWithContactLookupUri() {
    // Use lookup-style Uris that do not contain the Contact-ID
    final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, CONTACT_ID);
    final Uri lookupNoIdUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, LOOKUP_KEY);
    final Uri lookupUri = ContentUris.withAppendedId(lookupNoIdUri, CONTACT_ID);
    final Uri entityUri = Uri.withAppendedPath(lookupNoIdUri, Contacts.Entity.CONTENT_DIRECTORY);

    ContactQueries queries = new ContactQueries();
    mContactsProvider.expectTypeQuery(lookupNoIdUri, Contacts.CONTENT_ITEM_TYPE);
    queries.fetchAllData(entityUri, CONTACT_ID, RAW_CONTACT_ID, DATA_ID, LOOKUP_KEY);

    Contact contact = assertLoadContact(lookupNoIdUri);

    assertEquals(CONTACT_ID, contact.getId());
    assertEquals(RAW_CONTACT_ID, contact.getNameRawContactId());
    assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource());
    assertEquals(LOOKUP_KEY, contact.getLookupKey());
    assertEquals(lookupUri, contact.getLookupUri());
    assertEquals(1, contact.getRawContacts().size());
    assertEquals(1, contact.getStatuses().size());
    mContactsProvider.verify();/*w w  w  .ja v a  2  s  . co m*/
}

From source file:com.piusvelte.sonet.core.StatusDialog.java

private void showDialog() {
    if (mService == SMS) {
        // if mRect go straight to message app...
        if (mRect != null)
            QuickContact.showQuickContact(this, mRect,
                    Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, mEsid),
                    QuickContact.MODE_LARGE, null);
        else {/* w w w  . j  a  v a  2  s . c  o m*/
            startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + mEsid)));
            finish();
        }
    } else if (mService == RSS) {
        if (mEsid != null) {
            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(mEsid)));
            finish();
        } else {
            (Toast.makeText(StatusDialog.this, "RSS item has no link", Toast.LENGTH_LONG)).show();
            finish();
        }
    } else if (items != null) {
        // offer options for Comment, Post, Settings and Refresh
        // loading the likes/retweet and other options takes too long, so load them in the SonetCreatePost.class
        mDialog = (new AlertDialog.Builder(this)).setItems(items, this).setCancelable(true)
                .setOnCancelListener(new OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface arg0) {
                        finish();
                    }

                }).create();
        mDialog.show();
    } else {
        if (mAppWidgetId != Sonet.INVALID_ACCOUNT_ID) {
            // informational messages go to settings
            mFinish = true;
            startActivity(Sonet.getPackageIntent(this, ManageAccounts.class)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId));
            finish();
        } else {
            (Toast.makeText(StatusDialog.this, R.string.widget_loading, Toast.LENGTH_LONG)).show();
            // force widgets rebuild
            startService(Sonet.getPackageIntent(this, SonetService.class).setAction(ACTION_REFRESH));
            finish();
        }
    }
}

From source file:nl.sogeti.android.gpstracker.actions.Statistics.java

@Override
protected void onRestoreInstanceState(Bundle load) {
    if (load != null) {
        super.onRestoreInstanceState(load);
    }/*from w ww. java2  s. c  o m*/
    if (load != null && load.containsKey(TRACKURI)) {
        mTrackUri = Uri.withAppendedPath(Tracks.CONTENT_URI, load.getString(TRACKURI));
    }
    if (load != null && load.containsKey("FLIP")) {
        mViewFlipper.setDisplayedChild(load.getInt("FLIP"));
    }
}

From source file:com.morphoss.acal.service.UpdateTimezones.java

private void refreshTimezoneData() {
    try {/*from www .  j a va 2  s .co m*/
        HashMap<String, Long> currentZones = new HashMap<String, Long>();
        HashMap<String, Long> updatedZones = new HashMap<String, Long>();
        HashMap<String, Long> insertedZones = new HashMap<String, Long>();
        Cursor allZones = cr.query(Timezones.CONTENT_URI,
                new String[] { Timezones.TZID, Timezones.LAST_MODIFIED }, null, null, null);
        Long maxModified = 0L;
        for (allZones.moveToFirst(); !allZones.isAfterLast(); allZones.moveToNext()) {
            if (Constants.LOG_VERBOSE)
                Log.println(Constants.LOGV, TAG, "Found existing zone of '" + allZones.getString(0)
                        + "' modified: " + AcalDateTime.fromMillis(allZones.getLong(1) * 1000L).toString());
            currentZones.put(allZones.getString(0), allZones.getLong(1));
            if (allZones.getLong(1) > maxModified)
                maxModified = allZones.getLong(1);
        }
        AcalDateTime mostRecentChange = AcalDateTime.getUTCInstance().setEpoch(maxModified);
        Log.println(Constants.LOGI, TAG, "Found " + allZones.getCount()
                + " existing timezones, most recent change on " + mostRecentChange.toString());
        if (allZones.getCount() > 350 && mostRecentChange.after(AcalDateTime.getUTCInstance().addDays(-30))) {
            Log.println(Constants.LOGI, TAG, "Skipping update - our database is pretty recent");
            return;
        }

        requestor.interpretUriString(tzUrl("list", null));
        JSONObject root = requestor.doJsonRequest("GET", null, null, null);
        if (requestor.wasRedirected()) {
            Uri tzUri = Uri.parse(requestor.fullUrl());
            String redirectedUrl = tzUri.getScheme() + "://" + tzUri.getAuthority() + tzUri.getPath();
            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Redirected to Timezone Server at " + redirectedUrl);
            tzServerBaseUrl = redirectedUrl;
            AcalApplication.setPreferenceString(PrefNames.tzServerBaseUrl, redirectedUrl);
        }
        if (requestor.getStatusCode() >= 399) {
            Log.println(Constants.LOGI, TAG, "Bad response " + requestor.getStatusCode()
                    + " from Timezone Server at " + tzUrl("list", null));
        }
        if (root == null) {
            Log.println(Constants.LOGI, TAG, "No JSON from GET " + tzUrl("list", null));
            return;
        }

        String tzid;
        String tzData = "";
        long lastModified;
        StringBuilder localNames;
        StringBuilder aliases;
        ContentValues zoneValues = new ContentValues();

        String tzDateStamp = root.getString("dtstamp");
        JSONArray tzArray = root.getJSONArray("timezones");
        for (int i = 0; i < tzArray.length(); i++) {
            JSONObject zoneNode = tzArray.getJSONObject(i);
            tzid = zoneNode.getString("tzid");
            if (updatedZones.containsKey(tzid) || insertedZones.containsKey(tzid))
                continue;

            if (Constants.debugTimeZone && Constants.LOG_DEBUG)
                Log.println(Constants.LOGD, TAG, "Working on " + tzid);

            lastModified = AcalDateTime.fromString(zoneNode.getString("last-modified")).getEpoch();
            if (currentZones.containsKey(tzid) && currentZones.get(tzid) <= lastModified) {
                currentZones.remove(tzid);
                continue;
            }

            tzData = getTimeZone(tzid);
            if (tzData == null)
                continue;

            localNames = new StringBuilder();
            try {
                JSONArray nameNodes = zoneNode.getJSONArray("local_names");
                for (int j = 0; j < nameNodes.length(); j++) {
                    if (localNames.length() > 0)
                        localNames.append("\n");
                    localNames.append(nameNodes.getJSONObject(j).getString("lang")).append('~')
                            .append(nameNodes.getJSONObject(j).getString("lname"));
                }
            } catch (JSONException je) {
            }

            aliases = new StringBuilder();
            try {
                JSONArray aliasNodes = zoneNode.getJSONArray("aliases");
                for (int j = 0; j < aliasNodes.length(); j++) {
                    if (aliases.length() > 0)
                        aliases.append("\n");
                    aliases.append(aliasNodes.getString(j));
                }
            } catch (JSONException je) {
            }

            zoneValues.put(Timezones.TZID, tzid);
            zoneValues.put(Timezones.ZONE_DATA, tzData);
            zoneValues.put(Timezones.LAST_MODIFIED, lastModified);
            zoneValues.put(Timezones.TZ_NAMES, localNames.toString());
            zoneValues.put(Timezones.TZID_ALIASES, aliases.toString());

            Uri tzUri = Uri.withAppendedPath(Timezones.CONTENT_URI,
                    "tzid/" + StaticHelpers.urlescape(tzid, false));

            if (currentZones.containsKey(tzid)) {
                if (cr.update(tzUri, zoneValues, null, null) != 1) {
                    Log.e(TAG, "Failed update for TZID '" + tzid + "'");
                }
                updatedZones.put(tzid, currentZones.get(tzid));
                currentZones.remove(tzid);
            } else {
                if (cr.insert(tzUri, zoneValues) == null)
                    Log.e(TAG, "Failed insert for TZID '" + tzid + "'");
                insertedZones.put(tzid, currentZones.get(tzid));
            }

            if (context.workWaiting()) {
                Log.println(Constants.LOGI, TAG, "Something is waiting - deferring timezone sync until later.");
                deferMe = true;
                break;
            }
            // Let other stuff have a chance
            Thread.sleep(350);
        }
        int removed = 0;

        if (currentZones.size() > 0) {
            StringBuilder s = new StringBuilder();
            for (String tz : currentZones.keySet()) {
                if (s.length() > 0)
                    s.append(',');
                s.append("'").append(tz).append("'");
            }
            removed = cr.delete(Timezones.CONTENT_URI, Timezones.TZID + " IN (" + s + ")", null);
        }

        Log.println(Constants.LOGI, TAG, "Updated data for " + updatedZones.size() + " zones, added data for "
                + insertedZones.size() + " new zones, removed data for " + removed);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:com.kyakujin.android.autoeco.ui.SchedFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arg) {
    switch (id) {
    case SchedQuery.LOADER_ID:
        return new CursorLoader(getActivity(),
                Uri.withAppendedPath(SchedTbl.CONTENT_URI, String.valueOf(mCurrentSchedId)),
                SchedQuery.PROJECTION, null, null, null);

    default://  w w w  . j a v  a 2 s . c  om
        break;
    }
    return null;
}

From source file:ca.rmen.android.scrumchatter.team.Teams.java

/**
 * Select the first team in our DB.//ww  w  .j  a va2  s .c  o  m
 */
private Team selectFirstTeam() {
    Cursor c = mActivity.getContentResolver().query(TeamColumns.CONTENT_URI,
            new String[] { TeamColumns._ID, TeamColumns.TEAM_NAME }, null, null, null);
    if (c != null) {
        try {
            if (c.moveToFirst()) {
                int teamId = c.getInt(0);
                String teamName = c.getString(1);
                Prefs.getInstance(mActivity).setTeamId(teamId);
                Uri teamUri = Uri.withAppendedPath(TeamColumns.CONTENT_URI, String.valueOf(teamId));
                return new Team(teamUri, teamName);
            }
        } finally {
            c.close();
        }
    }
    return null;
}

From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Get an image media or file Uri based on its document Uri.
 *
 * @param context The Context/*from w  w w .  java2 s . c  o m*/
 * @param uri     The Uri to convert
 * @return The image or file Uri or the original Uri if it could not be converted
 */
@NonNull
private static Uri getImageUri(@NonNull Context context, @NonNull Uri uri) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] parts = docId.split(":");
        if ("image".equals(parts[0])) {
            return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, parts[1]);
        } else if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
            return Uri.fromFile(new File(Environment.getExternalStorageDirectory(), parts[1]));
        }
    }
    return uri;
}

From source file:org.kontalk.util.SystemUtils.java

public static Uri lookupPhoneNumber(Context context, String phoneNumber) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cur = context.getContentResolver().query(uri,
            new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.LOOKUP_KEY }, null,
            null, null);/*from w  w  w .j a  v a2s . co m*/
    if (cur != null) {
        try {
            if (cur.moveToNext()) {
                long id = cur.getLong(0);
                String lookupKey = cur.getString(1);
                return ContactsContract.Contacts.getLookupUri(id, lookupKey);
            }
        } finally {
            cur.close();
        }
    }

    return null;
}

From source file:name.zurell.kirk.apps.android.rhetolog.RhetologApplication.java

/** Generate (placeholder) report for numbered session */

String reportForSession(Uri session) {

    // Use own contentprovider streaming?

    Uri uri = Uri.withAppendedPath(RhetologContract.SESSIONSREPORT_URI, session.getLastPathSegment());
    try {//from  www.  j  av a  2 s.  co  m
        InputStream inputStream = getContentResolver().openInputStream(uri);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append("Report for session " + session.toString() + "\n\n");

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append("\n"); // oh well.
        }

        return stringBuilder.toString();

    } catch (IOException e) {
        return null;
    }

}

From source file:org.odk.collect.android.utilities.MediaUtils.java

public static final int deleteAudioInFolderFromMediaProvider(File folder) {
    ContentResolver cr = Collect.getInstance().getContentResolver();
    // audio/* w  ww .j a  v a  2 s.  c  o  m*/
    int count = 0;
    Cursor audioCursor = null;
    try {
        String select = Audio.Media.DATA + " like ? escape '!'";
        String[] selectArgs = { escapePath(folder.getAbsolutePath()) };

        String[] projection = { Audio.AudioColumns._ID };
        audioCursor = cr.query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, select,
                selectArgs, null);
        if (audioCursor.getCount() > 0) {
            audioCursor.moveToFirst();
            List<Uri> audioToDelete = new ArrayList<Uri>();
            do {
                String id = audioCursor.getString(audioCursor.getColumnIndex(Audio.AudioColumns._ID));

                audioToDelete.add(
                        Uri.withAppendedPath(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id));
            } while (audioCursor.moveToNext());

            for (Uri uri : audioToDelete) {
                Log.i(t, "attempting to delete: " + uri);
                count += cr.delete(uri, null, null);
            }
        }
    } catch (Exception e) {
        Log.e(t, e.toString());
    } finally {
        if (audioCursor != null) {
            audioCursor.close();
        }
    }
    return count;
}