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:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public synchronized Uri insert(@NonNull Uri uri, ContentValues initialValues) {
    possiblyWaitForContentProviderDebugger();

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

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }/* w ww  .j a v  a  2s  .  c o  m*/

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

    HashMap<String, Object> values = new HashMap<String, Object>();
    if (initialValues != null) {
        for (String key : initialValues.keySet()) {
            values.put(key, initialValues.get(key));
        }
    }

    // force a scan from disk
    values.remove(FormsColumns.DATE);
    values.remove(FormsColumns.JSON_MD5_HASH);
    FormSpec formSpec = patchUpValues(appName, values);

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.TABLE_ID, FormsColumns.FORM_ID };
    String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?";
    String[] selectionArgs = { formSpec.tableId, formSpec.formId };
    Cursor c = null;

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null, null);
            if (c == null) {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- unable to query for existing records. tableId="
                                + formSpec.tableId + " formId=" + formSpec.formId);
            }
            c.moveToFirst();
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri + " -- row already exists for  tableId="
                        + formSpec.tableId + " formId=" + formSpec.formId);
            }
        } 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.insertOrThrow(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            // and notify listeners of the new row...
            Uri formUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                    (String) values.get(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());
            }
        }
    } catch (SQLException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException("FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                            dbHandleName);
                }
            }
        }
    }
}

From source file:edu.nd.darts.cimon.database.CimonDatabaseAdapter.java

/**
 * Delete metric group from MetricInfo table.
 * /* www . j a va 2s  .  c o  m*/
 * @param metric    id which identifies metric group to delete
 * @return    number of rows deleted (should be 0 or 1)
 * 
 * @see MetricInfoTable
 */
public synchronized int deleteMetricInfo(int metric) {
    if (DebugLog.DEBUG)
        Log.d(TAG, "CimonDatabaseAdapter.deleteInfo - delete from MetricInfo table: metric-" + metric);
    //      SQLiteDatabase sqlDB = database.getWritableDatabase();
    int rowsdeleted = database.delete(MetricInfoTable.TABLE_METRICINFO,
            MetricInfoTable.COLUMN_ID + " = " + metric, null);
    Uri uri = Uri.withAppendedPath(CimonContentProvider.INFO_URI, String.valueOf(metric));
    context.getContentResolver().notifyChange(uri, null);
    return rowsdeleted;
}

From source file:im.delight.android.baselib.Social.java

/**
 * Whether the given person (represented by phone number) is known on the current device (i.e. in the address book) or not
 *
 * @param context the Context reference to get the ContentResolver from
 * @param phoneNumber the phone number to look up
 * @return whether the phone number is in the contacts list (true) or not (false)
 *///from w  w w  . ja  v  a 2  s  . c  o  m
public static boolean isPersonKnown(Context context, String phoneNumber) {
    try {
        Uri phoneUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(phoneNumber));
        Cursor phoneEntries = context.getContentResolver().query(phoneUri,
                new String[] { android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
        return phoneEntries.getCount() > 0;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.navjagpal.fileshare.WebServer.java

private void handleUploadRequest(DefaultHttpServerConnection serverConnection, HttpRequest request,
        RequestLine requestLine) throws IOException, HttpException, UnsupportedEncodingException {
    HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 200, "OK");
    String folderId = getFolderId(requestLine.getUri());
    processUpload(folderId, request, serverConnection);
    String header = getHTMLHeader();
    String form = getUploadForm(folderId);
    String footer = getHTMLFooter();
    String listing = getFileListing(Uri.withAppendedPath(FileSharingProvider.Folders.CONTENT_URI, folderId));
    response.setEntity(new StringEntity(header + listing + form + footer));
    serverConnection.sendResponseHeader(response);
    serverConnection.sendResponseEntity(response);
}

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

public void testLoadContactWithContactLookupWithIncorrectIdUri() {
    // Use lookup-style Uris that contain incorrect Contact-ID
    // (we want to ensure that still the correct contact is chosen)
    final long wrongContactId = 2;
    final long wrongRawContactId = 12;

    final String wrongLookupKey = "ab%12%@!";
    final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, CONTACT_ID);
    final Uri wrongBaseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, wrongContactId);
    final Uri lookupUri = ContentUris
            .withAppendedId(Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, LOOKUP_KEY), CONTACT_ID);
    final Uri lookupWithWrongIdUri = ContentUris
            .withAppendedId(Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, LOOKUP_KEY), wrongContactId);
    final Uri entityUri = Uri.withAppendedPath(lookupWithWrongIdUri, Contacts.Entity.CONTENT_DIRECTORY);

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

    Contact contact = assertLoadContact(lookupWithWrongIdUri);

    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 ww  .j ava 2  s .c o m
}

From source file:com.ultramegasoft.flavordex2.fragment.ViewPhotosFragment.java

@SuppressWarnings("ConstantConditions")
@NonNull//from   w w  w.  jav a  2 s.c  o m
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    final Context context = getContext();
    if (context == null) {
        return null;
    }

    final Uri uri = Uri.withAppendedPath(Tables.Entries.CONTENT_ID_URI_BASE, mEntryId + "/photos");
    final String[] projection = new String[] { Tables.Photos._ID, Tables.Photos.HASH, Tables.Photos.PATH,
            Tables.Photos.POS };
    final String where = Tables.Photos.PATH + " NOT NULL";
    final String order = Tables.Photos.POS + " ASC";
    return new CursorLoader(context, uri, projection, where, null, order);
}

From source file:com.bydavy.card.receipts.fragments.ReceiptEditFragment.java

public boolean updateReceiptInDB() {
    // Edit receipt
    final String shop = mViewShop.getText().toString();
    final String tmpTotal = mViewTotal.getText().toString();
    float total = 0;
    try {/*from  w  w  w.  j av a 2  s  . c om*/
        total = Float.parseFloat(tmpTotal);
        // Should never happend because the view only allow float
    } catch (final NumberFormatException e) {
        /* Nothing */
    }
    // Not required fields
    final String description = mViewNote.getText().toString();
    final long date = mDate.getTimeInMillis() / 1000;

    final ContentValues receipt = ReceiptsHelper.toContentValues(shop, description, date, total, false, null);

    final Uri uri = Uri.withAppendedPath(Receipts.CONTENT_URI, String.valueOf(getReceiptId()));

    try {
        getActivity().getContentResolver().update(uri, receipt, null, null);
    } catch (final Exception e) {
        LogHelper.e(ErrorID.CONTENT_PROVIDER, "Canno't insert receipt in db: " + e, e);
        // TODO advert the user and ask if we can send a debug info to dev'
        return false;
    }
    return true;
}

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

public static final int deleteVideoFileFromMediaProvider(String videoFile) {
    ContentResolver cr = Collect.getInstance().getContentResolver();
    // video//from ww  w  .  j ava  2 s  .co  m
    int count = 0;
    Cursor videoCursor = null;
    try {
        String select = Video.Media.DATA + "=?";
        String[] selectArgs = { videoFile };

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

                videoToDelete.add(
                        Uri.withAppendedPath(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id));
            } while (videoCursor.moveToNext());

            for (Uri uri : videoToDelete) {
                Log.i(t, "attempting to delete: " + uri);
                count += cr.delete(uri, null, null);
            }
        }
    } catch (Exception e) {
        Log.e(t, e.toString());
    } finally {
        if (videoCursor != null) {
            videoCursor.close();
        }
    }
    File f = new File(videoFile);
    if (f.exists()) {
        f.delete();
    }
    return count;
}

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

/**
 * Generate a thumbnail image file and save it to the persistent cache. If no photos exist for
 * the entry, te current file is deleted.
 *
 * @param context The Context/*from   w  ww.  j a  va  2 s .c o m*/
 * @param id      Te ID for the entry
 */
private static void generateThumb(@NonNull Context context, long id) {
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        return;
    }

    final ContentResolver cr = context.getContentResolver();
    final Uri uri = Uri.withAppendedPath(Tables.Entries.CONTENT_ID_URI_BASE, id + "/photos");
    final String where = Tables.Photos.PATH + " NOT NULL";
    final Cursor cursor = cr.query(uri, new String[] { Tables.Photos.PATH }, where, null,
            Tables.Photos.POS + " ASC");
    if (cursor != null) {
        try {
            if (cursor.moveToFirst()) {
                generateThumb(context, parsePath(cursor.getString(0)), id);
            } else {
                generateThumb(context, null, id);
            }
        } finally {
            cursor.close();
        }
    }
}

From source file:at.flack.receiver.SmsReceiver.java

private Integer fetchThumbnailId(Context context, String address) {

    final Uri uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI,
            Uri.encode(address));//w w w  .  j  a  v  a  2s.co m
    final Cursor cursor = context.getContentResolver().query(uri, PHOTO_ID_PROJECTION, null, null,
            ContactsContract.Contacts.DISPLAY_NAME + " ASC");

    try {
        Integer thumbnailId = null;
        if (cursor.moveToFirst()) {
            thumbnailId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
        }
        return thumbnailId;
    } finally {
        cursor.close();
    }

}