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:cz.maresmar.sfm.utils.ActionUtils.java

/**
 * Make edits in Actions for corresponding Menu entry. These action are saved as
 * {@link ProviderContract#ACTION_SYNC_STATUS_LOCAL} then.
 * <p>/* ww  w  .  j a v  a 2  s .  c  o  m*/
 * Handles menu group restrictions (like one order per group), in such cases creates
 * {@link ProviderContract#ACTION_ENTRY_TYPE_VIRTUAL} actions to override the
 * {@link ProviderContract#ACTION_SYNC_STATUS_SYNCED} ones. If an action reserves nothing,
 * the action is removed.
 * </p>
 *
 * @param context    Some valid context
 * @param userUri    User Uri prefix
 * @param relativeId Relative ID of corresponding Menu entry
 * @param portalId   Portal ID of corresponding Menu entry
 * @param reserved   New amount of reserved food
 * @param offered    New amount of offered food
 */
@WorkerThread
public static void makeEdit(@NonNull Context context, @NonNull Uri userUri, long relativeId, long portalId,
        int reserved, int offered) {
    // Load the corresponding menu entry
    @ProviderContract.PortalFeatures
    int portalFeatures;
    long menuGroupId;
    int price;
    long date;
    int syncedReserved, syncedOffered, syncedTaken;
    boolean hasLocal;
    int localReserved, localOffered;
    long portalGroupId;

    Uri menuUri = Uri.withAppendedPath(userUri, ProviderContract.MENU_ENTRY_PATH);
    ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    try (Cursor menuCursor = context.getContentResolver().query(menuUri, new String[] {
            ProviderContract.MenuEntry.PORTAL_FEATURES, ProviderContract.MenuEntry.GROUP_ID,
            ProviderContract.MenuEntry.PRICE, ProviderContract.MenuEntry.DATE,
            ProviderContract.MenuEntry.SYNCED_RESERVED_AMOUNT, ProviderContract.MenuEntry.SYNCED_OFFERED_AMOUNT,
            ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT, ProviderContract.MenuEntry.LOCAL_RESERVED_AMOUNT,
            ProviderContract.MenuEntry.LOCAL_OFFERED_AMOUNT, ProviderContract.MenuEntry.PORTAL_GROUP_ID },
            ProviderContract.MenuEntry.ME_RELATIVE_ID + " = " + relativeId + " AND "
                    + ProviderContract.MenuEntry.PORTAL_ID + " = " + portalId,
            null, null)) {

        if (BuildConfig.DEBUG) {
            Assert.isOne(menuCursor.getCount());
        }

        menuCursor.moveToFirst();

        // Info
        portalFeatures = menuCursor.getInt(0);
        menuGroupId = menuCursor.getLong(1);
        price = menuCursor.getInt(2);
        date = menuCursor.getLong(3);

        // Synced
        syncedReserved = menuCursor.getInt(4);
        syncedOffered = menuCursor.getInt(5);
        syncedTaken = menuCursor.getInt(6);

        // Local
        hasLocal = !menuCursor.isNull(7);
        localReserved = menuCursor.getInt(7);
        localOffered = menuCursor.getInt(8);

        // Portal group
        portalGroupId = menuCursor.getLong(9);

        // Insert changes
        Uri actionUri = Uri.withAppendedPath(userUri, ProviderContract.ACTION_PATH);
        // Insert virtual group changes
        boolean restrictToOneOrderPerGroup = (portalFeatures
                & ProviderContract.FEATURE_RESTRICT_TO_ONE_ORDER_PER_GROUP) == ProviderContract.FEATURE_RESTRICT_TO_ONE_ORDER_PER_GROUP;

        // Delete old edits as I want something new
        if (!restrictToOneOrderPerGroup) {
            // Delete action for this menu entry
            ops.add((ContentProviderOperation.newDelete(actionUri)
                    .withSelection(ProviderContract.Action.ME_RELATIVE_ID + " = " + relativeId + " AND "
                            + ProviderContract.Action.ME_PORTAL_ID + " = " + portalId + " AND "
                            + ProviderContract.Action.SYNC_STATUS + " = "
                            + ProviderContract.ACTION_SYNC_STATUS_EDIT, null)
                    .build()));
        } else {
            // Delete actions for whole menu entry group
            ops.add(ContentProviderOperation.newDelete(actionUri)
                    .withSelection(ProviderContract.Action.ME_PORTAL_ID + " IN " + "(SELECT "
                            + DbContract.Portal._ID + " FROM " + DbContract.Portal.TABLE_NAME + " WHERE "
                            + DbContract.Portal.COLUMN_NAME_PGID + " == " + portalGroupId + " ) AND "
                            + ProviderContract.Action.SYNC_STATUS + " = "
                            + ProviderContract.ACTION_SYNC_STATUS_EDIT + " AND " + "EXISTS ( SELECT * FROM "
                            + DbContract.MenuEntry.TABLE_NAME + " WHERE " + DbContract.MenuEntry.COLUMN_NAME_PID
                            + " == " + ProviderContract.Action.ME_PORTAL_ID + " AND "
                            + DbContract.MenuEntry.COLUMN_NAME_RELATIVE_ID + " == "
                            + ProviderContract.Action.ME_RELATIVE_ID + " AND "
                            + DbContract.MenuEntry.COLUMN_NAME_DATE + " == " + date + " AND "
                            + DbContract.MenuEntry.COLUMN_NAME_MGID + " == " + menuGroupId + " )", null)
                    .build());
        }

        // Insert new edits
        if ((hasLocal && !(reserved == localReserved && offered == localOffered))
                || (!hasLocal && !(reserved == syncedReserved && offered == syncedOffered))) {
            if (restrictToOneOrderPerGroup) {
                // Sets other actions in group to zeros
                try (Cursor groupCursor = context.getContentResolver().query(menuUri, new String[] {
                        ProviderContract.MenuEntry.ME_RELATIVE_ID, ProviderContract.MenuEntry.PRICE,
                        ProviderContract.MenuEntry.STATUS, ProviderContract.MenuEntry.SYNCED_RESERVED_AMOUNT,
                        ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT, ProviderContract.MenuEntry.PORTAL_ID },
                        ProviderContract.MenuEntry.PORTAL_ID + " IN " + "(SELECT " + DbContract.Portal._ID
                                + " FROM " + DbContract.Portal.TABLE_NAME + " WHERE "
                                + DbContract.Portal.COLUMN_NAME_PGID + " == " + portalGroupId + " ) AND "
                                + ProviderContract.MenuEntry.DATE + " = " + date + " AND "
                                + ProviderContract.MenuEntry.GROUP_ID + " = " + menuGroupId + " AND ("
                                + "(IFNULL(" + ProviderContract.MenuEntry.SYNCED_RESERVED_AMOUNT + ", 0)"
                                + " - IFNULL(" + ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT
                                + ", 0)) > 0 OR " + "(IFNULL("
                                + ProviderContract.MenuEntry.LOCAL_RESERVED_AMOUNT + ", 0)" + " - IFNULL("
                                + ProviderContract.MenuEntry.SYNCED_TAKEN_AMOUNT + ", 0)) > 0)",
                        null, null)) {
                    if (groupCursor != null) {
                        while (groupCursor.moveToNext()) {
                            // Skip main changed row
                            if (groupCursor.getLong(0) == relativeId) {
                                continue;
                            }

                            @ProviderContract.MenuStatus
                            int status = groupCursor.getInt(2);
                            boolean canCancel = (status
                                    & ProviderContract.MENU_STATUS_CANCELABLE) == ProviderContract.MENU_STATUS_CANCELABLE;
                            boolean canUseStock = (status
                                    & ProviderContract.FEATURE_FOOD_STOCK) == ProviderContract.FEATURE_FOOD_STOCK;

                            // Insert virtual actions
                            ContentValues newAction = new ContentValues();
                            newAction.put(ProviderContract.Action.ME_RELATIVE_ID, groupCursor.getLong(0));
                            newAction.put(ProviderContract.Action.ME_PORTAL_ID, groupCursor.getLong(5));
                            newAction.put(ProviderContract.Action.SYNC_STATUS,
                                    ProviderContract.ACTION_SYNC_STATUS_EDIT);
                            newAction.put(ProviderContract.Action.ENTRY_TYPE,
                                    ProviderContract.ACTION_ENTRY_TYPE_VIRTUAL);
                            newAction.put(ProviderContract.Action.PRICE, groupCursor.getInt(1));
                            if (canCancel) {
                                newAction.put(ProviderContract.Action.RESERVED_AMOUNT, 0);
                                newAction.put(ProviderContract.Action.OFFERED_AMOUNT, 0);
                            } else {
                                newAction.put(ProviderContract.Action.RESERVED_AMOUNT, groupCursor.getInt(3));
                                newAction.put(ProviderContract.Action.OFFERED_AMOUNT, groupCursor.getInt(3));

                                Toast.makeText(context, R.string.actions_food_stock_on_restricted_to_one,
                                        Toast.LENGTH_LONG).show();
                            }
                            newAction.put(ProviderContract.Action.TAKEN_AMOUNT, groupCursor.getInt(4));

                            ops.add(ContentProviderOperation.newInsert(actionUri).withValues(newAction)
                                    .build());
                        }
                    }
                }
            }

            // Insert main edit
            ContentValues newAction = new ContentValues();
            newAction.put(ProviderContract.Action.ME_RELATIVE_ID, relativeId);
            newAction.put(ProviderContract.Action.ME_PORTAL_ID, portalId);
            newAction.put(ProviderContract.Action.SYNC_STATUS, ProviderContract.ACTION_SYNC_STATUS_EDIT);
            newAction.put(ProviderContract.Action.ENTRY_TYPE, ProviderContract.ACTION_ENTRY_TYPE_STANDARD);
            newAction.put(ProviderContract.Action.PRICE, price);
            newAction.put(ProviderContract.Action.RESERVED_AMOUNT, reserved);
            newAction.put(ProviderContract.Action.OFFERED_AMOUNT, offered);
            newAction.put(ProviderContract.Action.TAKEN_AMOUNT, syncedTaken);

            ops.add(ContentProviderOperation.newInsert(actionUri).withValues(newAction).build());
        }

        // Apply changes at once (it boost the performance)
        try {
            context.getContentResolver().applyBatch(ProviderContract.AUTHORITY, ops);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.cordova.plugin.ExportVCFsToFilePlugin.java

private String getVcardString(String fileName, String fileExtension) throws IOException {
    contactsSet = new HashSet<String>();
    cursor = this.cordova.getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null);/*from  www. jav  a  2 s.c  om*/
    if (cursor != null && cursor.getCount() > 0) {
        int i;
        File outputDir = this.cordova.getActivity().getCacheDir();
        String fullFilePath = outputDir.getAbsolutePath() + "/" + fileName + "." + fileExtension;
        FileOutputStream mFileOutputStream = new FileOutputStream(fullFilePath, false);

        cursor.moveToFirst();

        for (i = 0; i < cursor.getCount(); i++) {
            Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI,
                    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)));
            AssetFileDescriptor fd;
            try {
                fd = this.cordova.getActivity().getContentResolver().openAssetFileDescriptor(uri, "r");
                FileInputStream fis = fd.createInputStream();
                byte[] buf = new byte[(int) fd.getDeclaredLength()];
                fis.read(buf);
                contactsSet.add(new String(buf));
            } catch (Exception e1) {
            }
            cursor.moveToNext();
        }
        Iterator it = contactsSet.iterator();
        while (it.hasNext()) {
            try {
                mFileOutputStream.write(it.next().toString().getBytes());
            } catch (IOException e) {
            }
        }
        mFileOutputStream.close();
        cursor.close();
        return fullFilePath;
    } else {
        Log.d("TAG", "No Contacts in Your Phone");
        return "";
    }
}

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

/**
 * Remove definitions from the Forms database that are no longer present on
 * disk.//from w w  w  . j  av  a 2 s.  c  o  m
 */
private final void removeStaleFormInfo() {
    Log.i(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " begin");
    ArrayList<Uri> badEntries = new ArrayList<Uri>();
    Cursor c = null;
    try {
        c = context.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                null, null, null);

        if (c == null) {
            Log.w(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName
                    + " null cursor returned from query.");
            return;
        }

        if (c.moveToFirst()) {
            do {
                String id = c.getString(c.getColumnIndex(FormsColumns.FORM_ID));
                Uri otherUri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);

                int appRelativeFormMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                if (appRelativeFormMediaPathIdx == -1) {
                    throw new IllegalStateException("Column " + FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                            + " missing from database table. Incompatible versions?");
                }
                String appRelativeFormMediaPath = c.getString(appRelativeFormMediaPathIdx);
                File f = ODKFileUtils.asAppFile(appName, appRelativeFormMediaPath);
                if (!f.exists() || !f.isDirectory()) {
                    // the form definition does not exist
                    badEntries.add(otherUri);
                }
            } while (c.moveToNext());
        }
    } catch (Exception e) {
        Log.e(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " exception: " + e.toString());
        e.printStackTrace();
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // delete the other entries (and directories)
    for (Uri badUri : badEntries) {
        Log.i(t, "[" + instanceCounter + "] removeStaleFormInfo: " + appName + " deleting: "
                + badUri.toString());
        try {
            context.getContentResolver().delete(badUri, null, null);
        } catch (Exception e) {
            Log.e(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " exception: "
                    + e.toString());
            e.printStackTrace();
            // and continue -- don't throw an error
        }
    }
    Log.i(t, "[" + instanceCounter + "] removeStaleFormInfo " + appName + " end");
}

From source file:edu.nd.darts.cimon.MonitorReport.java

public MonitorReport(Context context, int metricId, int monitorId, Handler handler, AdminObserver observer,
        boolean metadata, boolean email, boolean dropbox, boolean box, boolean drive) {
    this.context = context;
    this.metricId = metricId;
    this.monitorId = monitorId;
    this.adminObserver = observer;
    this.metadata = metadata;
    this.email = email;
    this.dropbox = dropbox;
    this.box = box;
    this.drive = drive;
    this.metricName = "Metric" + metricId;

    if (DebugLog.DEBUG)
        Log.d(TAG, "MonitorReport - ID:" + monitorId + " metric:" + metricId);
    Uri uri = Uri.withAppendedPath(CimonContentProvider.MONITOR_DATA_URI, String.valueOf(monitorId));
    contentObserver = new MyContentObserver(handler);
    context.getContentResolver().registerContentObserver(uri, false, contentObserver);
}

From source file:com.misczak.joinmybridge.CalendarFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Uri baseUri;//from w w  w. j a v a  2 s .  c o m
    if (mCurFilter != null) {
        baseUri = Uri.withAppendedPath(CalendarContract.Calendars.CONTENT_URI, Uri.encode(mCurFilter));
    } else {
        baseUri = CalendarContract.Calendars.CONTENT_URI;
    }

    String select = "((" + CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " NOTNULL))";

    return new CursorLoader(getActivity(), baseUri, CALENDARS_SUMMARY_PROJECTION, select, null,
            CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " COLLATE LOCALIZED ASC");

}

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

public static final int deleteImageFileFromMediaProvider(String imageFile) {
    ContentResolver cr = Collect.getInstance().getContentResolver();
    // images//from ww w  . ja  v a 2  s .c  o  m
    int count = 0;
    Cursor imageCursor = null;
    try {
        String select = Images.Media.DATA + "=?";
        String[] selectArgs = { imageFile };

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

                imagesToDelete.add(Uri
                        .withAppendedPath(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id));
            } while (imageCursor.moveToNext());

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

From source file:com.jaspersoft.android.jaspermobile.util.SavedItemHelper.java

public void deleteUnsavedItems() {
    String selection = SavedItemsTable.DOWNLOADED + " =?";
    Cursor cursor = context.getContentResolver().query(MobileDbProvider.SAVED_ITEMS_CONTENT_URI,
            new String[] { SavedItemsTable._ID, SavedItemsTable.FILE_PATH }, selection, new String[] { "0" },
            null);//  ww  w . j a  v  a  2  s . c  o m

    if (cursor == null)
        return;

    if (cursor.moveToFirst()) {
        do {
            int id = cursor.getInt(cursor.getColumnIndex(SavedItemsTable._ID));
            Uri uri = Uri.withAppendedPath(JasperMobileDbProvider.SAVED_ITEMS_CONTENT_URI, String.valueOf(id));
            deleteSavedItem(uri);
        } while (cursor.moveToNext());
    }

    cursor.close();
}

From source file:org.apache.cordova.contactVcardpicker.ContactVcardPicker.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d("customPlugin", "Calling onActivityResult");

    if (resultCode == Activity.RESULT_OK && requestCode == 5) {
        String vCard = null;/* w w  w .  ja v  a2  s  .c  o m*/
        try {
            Uri contactData = data.getData();

            @SuppressWarnings("deprecation")
            Cursor cursor = cordova.getActivity().getContentResolver().query(contactData, null, null, null,
                    null);

            cursor.moveToFirst();
            String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
            AssetFileDescriptor fd = cordova.getActivity().getContentResolver().openAssetFileDescriptor(uri,
                    "r");
            FileInputStream fis = fd.createInputStream();
            byte[] b = new byte[(int) fd.getDeclaredLength()];
            fis.read(b);
            vCard = new String(b);
            System.out.println("VACRD :" + vCard);

            String contactId = data.getData().getLastPathSegment();
            Cursor c = this.cordova.getActivity().getContentResolver().query(RawContacts.CONTENT_URI,
                    new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + " = " + contactId, null, null);
            if (!c.moveToFirst()) {
                this.callbackContext.error("Error occured while retrieving contact raw id");
                return;
            }
            String id = c.getString(c.getColumnIndex(RawContacts._ID));
            c.close();
            this.contactAccessor = new ContactAccessorSdk5(this.cordova);
            JSONObject contact = contactAccessor.getContactById(id);

            String returnText = "{\"contact\": {\"contactData\": \"" + contact.toString() + "\",\"vCard\": \""
                    + vCard + "\"}}";
            System.out.println("returnText :" + returnText);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, returnText);
            pluginResult.setKeepCallback(true);
            this.callbackContext.sendPluginResult(pluginResult);

            // readVCard(vCard);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.jamienicol.episodes.NextEpisodeFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.episode_details_fragment, container, false);

    rootView = view.findViewById(R.id.root);
    titleView = (TextView) view.findViewById(R.id.title);
    overviewView = (TextView) view.findViewById(R.id.overview);
    dateView = (TextView) view.findViewById(R.id.date);
    watchedCheckBox = (CheckBox) view.findViewById(R.id.watched);
    watchedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Make sure we have a next episode
            if (episodeId == -1) {
                Log.w(TAG, "Watched check changed but there is no next episode.");
                return;
            }// w w  w .j  a va  2s . co  m

            final ContentResolver contentResolver = getActivity().getContentResolver();
            final AsyncQueryHandler handler = new AsyncQueryHandler(contentResolver) {
            };

            final Uri episodeUri = Uri.withAppendedPath(ShowsProvider.CONTENT_URI_EPISODES,
                    String.valueOf(episodeId));

            final ContentValues episodeValues = new ContentValues();
            episodeValues.put(EpisodesTable.COLUMN_WATCHED, isChecked);

            handler.startUpdate(0, null, episodeUri, episodeValues, null, null);
        }
    });

    return view;
}

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

private int connectToMapping(int schedId) {
    int mappingId = 0;

    if (schedId == 0)
        return mappingId;

    // Mapping???????
    MappingDAO mappingDao = new MappingDAO(this);
    mappingId = mappingDao.searchMappingIdBySchedId(schedId);

    // Mapping????
    if (mappingId == 0) {
        // ??//  ww w.  j  a va 2  s . co m
        EcoDAO ecoDao = new EcoDAO(this);
        mEcoUri = ecoDao.insertDefaultEco();

        // Mapping??
        MappingModel mappingModel = new MappingModel();
        mappingModel.setEcoid(Integer.valueOf(mEcoUri.getLastPathSegment()));

        mappingModel.setSchedid(schedId);
        mappingModel.setBatteryid(0);
        mappingModel.setManualid(0);
        mappingId = Integer.valueOf(mappingDao.insertMapping(mappingModel).getLastPathSegment());

    } else {
        // Mapping???????
        mEcoUri = Uri.withAppendedPath(EcoTbl.CONTENT_URI,
                String.valueOf(mappingDao.searchEcoIdBySchedId(schedId)));
    }

    return mappingId;
}