Example usage for android.net Uri toString

List of usage examples for android.net Uri toString

Introduction

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

Prototype

public abstract String toString();

Source Link

Document

Returns the encoded string representation of this URI.

Usage

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    int nbRowsUpdated;

    switch (URI_MATCHER.match(uri)) {

    // Update a data
    case CatalogContract.Provider.CODE_DATA_ID:
        if (selection != null && selectionArgs != null) {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase()
                    .update(CatalogContract.DataBaseDataSimple.TABLE_NAME, values, selection, selectionArgs);
        } else {/*  www. j  a v  a2  s  .c o m*/
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseDataSimple.TABLE_NAME, values,
                    CatalogContract.DataBaseData.ATT_DATA_ID + "=?", new String[] { uri.getLastPathSegment() });
        }
        break;

    // Update a data details
    case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
        if (selection != null && selectionArgs != null) {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase()
                    .update(CatalogContract.DataBaseDataDetails.TABLE_NAME, values, selection, selectionArgs);
        } else {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseDataDetails.TABLE_NAME, values,
                    CatalogContract.DataBaseData.ATT_DATA_ID + "=?", new String[] { uri.getLastPathSegment() });
        }
        break;

    // Update a group sync status
    case CatalogContract.Provider.CODE_SYNC_GROUP:

        if (selection != null && selectionArgs != null) {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, values, selection, selectionArgs);
        } else {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, values,
                    CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID + "=?",
                    new String[] { uri.getLastPathSegment() });
        }

        break;

    default:
        Log.e(TAG, "URI not recognized" + uri.toString());
        throw new IllegalArgumentException("URI not recognized" + uri.toString());

    }

    Log.i(TAG, "Notify changes for " + uri);

    // Notify watchers of the change
    getContext().getContentResolver().notifyChange(uri, null);

    return nbRowsUpdated;
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

private void cameraSucess(Intent intent) {
    try {/*from  w ww  .j  a v  a  2 s.com*/
        Bitmap bitmap = null;
        try {
            //???imagebitmap
            if (mAllowEdit) {
                //??????Android???
                //???URI
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    bitmap = extras.getParcelable("data");
                }

                //?????URI
                if ((bitmap == null) || (extras == null)) {
                    bitmap = getCroppedBitmap(intent);
                }
            } else { // ????
                bitmap = android.provider.MediaStore.Images.Media.getBitmap(getContext().getContentResolver(),
                        mImageUri);
            }
        } catch (FileNotFoundException e) {
            Uri uri = intent.getData();
            android.content.ContentResolver resolver = getContext().getContentResolver();
            bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
        } catch (IOException e) {
            mCallbackCtx.error("Can't open image");
        } catch (OutOfMemoryError e) {
            XNotification notification = new XNotification(mExtensionContext.getSystemContext());
            notification.alert("Size of Image is too large!", "Save Image Error", "OK", null, DURATION);
            mCallbackCtx.error("Size of image is too large");
            return;
        }

        // ???
        Bitmap scaleBitmap = scaleBitmap(bitmap);
        Uri uri = null;
        if (mDestType == DATA_URL) {
            processPicture(scaleBitmap);
            checkForDuplicateImage(DATA_URL);
        } else if (mDestType == FILE_URI || mDestType == NATIVE_URI) {
            if (!this.mSaveToPhotoAlbum) {
                String suffixName = null;
                if (mEncodingType == JPEG) {
                    suffixName = ".jpg";
                } else if (mEncodingType == PNG) {
                    suffixName = ".png";
                } else {
                    throw new IllegalArgumentException("Invalid Encoding Type: " + mEncodingType);
                }
                String photoName = System.currentTimeMillis() + suffixName;
                uri = Uri.fromFile(new File(mWebContext.getWorkSpace(), photoName));
            } else {
                uri = getUriFromMediaStore();
            }
            if (uri == null) {
                mCallbackCtx.error("Error capturing image - no media storage found.");
            }

            // ?
            OutputStream os = getContext().getContentResolver().openOutputStream(uri);
            scaleBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os);
            os.close();

            // ??success callback
            XPathResolver pathResolver = new XPathResolver(uri.toString(), "", getContext());
            mCallbackCtx.success(XConstant.FILE_SCHEME + pathResolver.resolve());
        }
        scaleBitmap.recycle();
        scaleBitmap = null;
        cleanup(FILE_URI, mImageUri, uri, bitmap);
    } catch (IOException e) {
        mCallbackCtx.error("Error capturing image.");
    }
}

From source file:com.tuxpan.foregroundcameragalleryplugin.ForegroundCameraLauncher.java

private void returnImageToProcess(Bitmap bitmap, int srcType, int destType, Intent intent, int rotate) {
    Uri uri = intent.getData();

    if (destType == DATA_URL) {
        processPicture(bitmap);/*from  w  ww  .  ja  v a  2  s. co  m*/
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        // Do we need to scale the returned file
        if (targetHeight > 0 && targetWidth > 0) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                String resizePath = getTempDirectoryPath() + "/resize.jpg";
                // Some content: URIs do not map to file paths (e.g. picasa).
                String realPath = FileHelper.getRealPath(uri, cordova);
                ExifHelper exif = new ExifHelper();
                if (realPath != null && encodingType == JPEG) {
                    try {
                        exif.createInFile(realPath);
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                OutputStream os = new FileOutputStream(resizePath);
                bitmap.compress(Bitmap.CompressFormat.JPEG, mQuality, os);
                os.close();

                // Restore exif data to file
                if (realPath != null && encodingType == JPEG) {
                    exif.createOutFile(resizePath);
                    exif.writeExifData();
                }

                // The resized image is cached by the app in order to get around this and not have to delete you
                // application cache I'm adding the current system time to the end of the file url.
                callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis());
            } catch (Exception e) {
                e.printStackTrace();
                failPicture("Error retrieving image.");
            }
        } else {
            callbackContext.success(uri.toString());
        }
    }
    if (bitmap != null) {
        bitmap.recycle();
        bitmap = null;
    }
    System.gc();
}

From source file:io.ingame.squarecamera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *///from   w  w  w.  j a  v a  2  s . c  o m
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
            exif.readExifData();
            rotate = exif.getOrientation();
        } else if (this.encodingType == PNG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.png");
            exif.readExifData();
            rotate = exif.getOrientation();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        if (this.saveToPhotoAlbum) {
            Uri inputUri = getUriFromMediaStore();
            try {
                //Just because we have a media URI doesn't mean we have a real file, we need to make it
                uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
            } catch (NullPointerException e) {
                uri = null;
            }
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
            return;
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                if (this.saveToPhotoAlbum) {
                    exifPath = FileHelper.getRealPath(uri, this.cordova);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }
            if (this.allowEdit) {
                performCrop(uri);
            } else {
                // Send Uri back to JavaScript for viewing image
                this.callbackContext.success(uri.toString());
            }
        }
    } else {
        throw new IllegalStateException();
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:de.quist.app.errorreporter.ExceptionReportService.java

private void sendReport(Intent intent) throws UnsupportedEncodingException, NameNotFoundException {
    Log.v(TAG, "Got request to report error: " + intent.toString());
    Uri server = getTargetUrl();

    boolean isManualReport = intent.getBooleanExtra(EXTRA_MANUAL_REPORT, false);
    boolean isReportOnFroyo = isReportOnFroyo();
    boolean isFroyoOrAbove = isFroyoOrAbove();
    if (isFroyoOrAbove && !isManualReport && !isReportOnFroyo) {
        // We don't send automatic reports on froyo or above
        Log.d(TAG, "Don't send automatic report on froyo");
        return;//ww  w  .j  ava  2  s  .c o  m
    }

    Set<String> fieldsToSend = getFieldsToSend();

    String stacktrace = intent.getStringExtra(EXTRA_STACK_TRACE);
    String exception = intent.getStringExtra(EXTRA_EXCEPTION_CLASS);
    String message = intent.getStringExtra(EXTRA_MESSAGE);
    long availableMemory = intent.getLongExtra(EXTRA_AVAILABLE_MEMORY, -1l);
    long totalMemory = intent.getLongExtra(EXTRA_TOTAL_MEMORY, -1l);
    String dateTime = intent.getStringExtra(EXTRA_EXCEPTION_TIME);
    String threadName = intent.getStringExtra(EXTRA_THREAD_NAME);
    String extraMessage = intent.getStringExtra(EXTRA_EXTRA_MESSAGE);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    addNameValuePair(params, fieldsToSend, "exStackTrace", stacktrace);
    addNameValuePair(params, fieldsToSend, "exClass", exception);
    addNameValuePair(params, fieldsToSend, "exDateTime", dateTime);
    addNameValuePair(params, fieldsToSend, "exMessage", message);
    addNameValuePair(params, fieldsToSend, "exThreadName", threadName);
    if (extraMessage != null)
        addNameValuePair(params, fieldsToSend, "extraMessage", extraMessage);
    if (availableMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devAvailableMemory", availableMemory + "");
    if (totalMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devTotalMemory", totalMemory + "");

    PackageManager pm = getPackageManager();
    try {
        PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
        addNameValuePair(params, fieldsToSend, "appVersionCode", packageInfo.versionCode + "");
        addNameValuePair(params, fieldsToSend, "appVersionName", packageInfo.versionName);
        addNameValuePair(params, fieldsToSend, "appPackageName", packageInfo.packageName);
    } catch (NameNotFoundException e) {
    }
    addNameValuePair(params, fieldsToSend, "devModel", android.os.Build.MODEL);
    addNameValuePair(params, fieldsToSend, "devSdk", android.os.Build.VERSION.SDK);
    addNameValuePair(params, fieldsToSend, "devReleaseVersion", android.os.Build.VERSION.RELEASE);

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(server.toString());
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    Log.d(TAG, "Created post request");

    try {
        httpClient.execute(post);
        Log.v(TAG, "Reported error: " + intent.toString());
    } catch (ClientProtocolException e) {
        // Ignore this kind of error
        Log.e(TAG, "Error while sending an error report", e);
    } catch (SSLException e) {
        Log.e(TAG, "Error while sending an error report", e);
    } catch (IOException e) {
        if (e instanceof SocketException && e.getMessage().contains("Permission denied")) {
            Log.e(TAG, "You don't have internet permission", e);
        } else {
            int maximumRetryCount = getMaximumRetryCount();
            int maximumExponent = getMaximumBackoffExponent();
            // Retry at a later point in time
            AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
            int exponent = intent.getIntExtra(EXTRA_CURRENT_RETRY_COUNT, 0);
            intent.putExtra(EXTRA_CURRENT_RETRY_COUNT, exponent + 1);
            PendingIntent operation = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (exponent >= maximumRetryCount) {
                // Discard error
                Log.w(TAG, "Error report reached the maximum retry count and will be discarded.\nStacktrace:\n"
                        + stacktrace);
                return;
            }
            if (exponent > maximumExponent) {
                exponent = maximumExponent;
            }
            long backoff = (1 << exponent) * 1000; // backoff in ms
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + backoff, operation);
        }
    }
}

From source file:com.remobile.camera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType In which form should we return the image
 * @param intent   An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*  ww  w .  j  a va  2s  .co  m*/
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    String sourcePath;
    try {
        if (allowEdit && croppedUri != null) {
            sourcePath = FileHelper.stripFileProtocol(croppedUri.toString());
        } else {
            sourcePath = getTempDirectoryPath() + "/.Pic.jpg";
        }

        //We don't support PNG, so let's not pretend we do
        exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
        exif.readExifData();
        rotate = exif.getOrientation();

    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        if (croppedUri != null) {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(croppedUri.toString()));
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        }
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));

        if (this.saveToPhotoAlbum) {
            //Create a URI on the filesystem so that we can write the file.
            uri = Uri.fromFile(new File(getPicutresPath()));
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
            return;
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                exifPath = uri.getPath();
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }

            //Broadcast change to File System on MediaStore
            if (this.saveToPhotoAlbum) {
                refreshGallery(uri);
            }

            // Send Uri back to JavaScript for viewing image
            this.callbackContext.success(uri.toString());

        }
    } else {
        throw new IllegalStateException();
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *///w  w  w .  j a v  a 2  s. c  o m
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
            exif.readExifData();
            rotate = exif.getOrientation();
        } else if (this.encodingType == PNG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.png");
            exif.readExifData();
            rotate = exif.getOrientation();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        if (imageUri != null)
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            if (intent != null && intent.getExtras() != null) {
                bitmap = (Bitmap) intent.getExtras().get("data");
            }
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        if (this.saveToPhotoAlbum) {
            Uri inputUri = getUriFromMediaStore();
            try {
                //Just because we have a media URI doesn't mean we have a real file, we need to make it
                uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.activity)));
            } catch (NullPointerException e) {
                uri = null;
            }
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
            return;
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.activity.getContentResolver().openOutputStream(uri);
            bitmap.compress(CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                if (this.saveToPhotoAlbum) {
                    exifPath = FileHelper.getRealPath(uri, this.activity);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }
            if (this.allowEdit) {
                performCrop(uri);
            } else {
                // Send Uri back to JavaScript for viewing image
                this.callbackContext.success(uri.toString());
            }
        }
    } else {
        throw new IllegalStateException();
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteDatabase sqLiteDatabase = mDatabaseHelper.getWritableDatabase();
    String tableName;/*from  www . j  a va  2  s  . c om*/
    String where;
    String order = "";
    Bundle bundleSyncAdapter = new Bundle();
    String lastPathSegment = uri.getLastPathSegment();

    if (StringUtils.isNotBlank(sortOrder)) {
        order = " ORDER BY " + sortOrder;
    }

    switch (URI_MATCHER.match(uri)) {

    // Getting the content for a group (list of simple data)
    case CatalogContract.Provider.CODE_GROUP_ID:
        tableName = CatalogContract.DataBaseDataSimple.TABLE_NAME;
        where = CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + "."
                + CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID + "='" + lastPathSegment + "'";

        // Limit for the query on the sync adapter
        String currentPage = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_CURRENT_PAGE);
        String pageSize = uri.getQueryParameter(CatalogContract.Provider.QUERY_PARAM_PAGE_SIZE);

        // Bundle information for the syncing part
        bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_GROUP_ID, lastPathSegment);

        if (StringUtils.isNotBlank(currentPage) && StringUtils.isNotBlank(pageSize)) {
            bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_CURRENT_PAGE,
                    Integer.valueOf(currentPage));
            bundleSyncAdapter.putInt(CatalogSyncConstants.SYNC_PARAM_PAGE_SIZE, Integer.valueOf(pageSize));
        }

        break;

    // Getting a specific data detail
    case CatalogContract.Provider.CODE_DATA_ID:
    case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
        tableName = CatalogContract.DataBaseDataDetails.TABLE_NAME;
        where = CatalogContract.DataBaseDataDetails.TABLE_NAME + "."
                + CatalogContract.DataBaseDataDetails.ATT_DATA_ID + "='" + lastPathSegment + "'";

        // Bundle information for the syncing part
        bundleSyncAdapter.putString(CatalogSyncConstants.SYNC_PARAM_DATA_ID, lastPathSegment);

        // We don't load the variants for a specific data
        bundleSyncAdapter.putBoolean(CatalogSyncConstants.SYNC_PARAM_LOAD_VARIANTS, false);
        break;

    default:
        Log.e(TAG, "URI not recognized" + uri.toString());
        throw new IllegalArgumentException("URI not recognized" + uri.toString());

    }

    // We do the query by joining the data to the group
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + tableName + " INNER JOIN "
            + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME + " ON " + tableName + "."
            + CatalogContract.DataBaseData.ATT_DATA_ID + "=" + CatalogContract.DataBaseDataLinkGroup.TABLE_NAME
            + "." + CatalogContract.DataBaseDataLinkGroup.ATT_DATA_ID + " WHERE " + where + order, null);

    // Register the cursor to watch the uri for changes
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    // Existing data
    if (cursor.getCount() > 0) {
        // TODO - For now we check if one the items is out-of-sync and we sync all of them if this is the case
        // Future - Check every out-of-date items and sync them
        cursor.moveToLast();
        int status = cursor.getInt(cursor.getColumnIndex(CatalogContract.DataBaseData.ATT_STATUS));
        cursor.moveToFirst();

        // Data expired, we request a sync
        if (status == CatalogContract.SyncStatus.OUTOFDATE.getValue()) {
            Log.i(TAG, "Data for " + uri.toString() + " is out-of-date, requesting a sync");
            requestSync(bundleSyncAdapter);

            // TODO - the uptodate/outofdate should be done in the sync adapter
            // We up-to-date all the data in case the sync does not return any results (we base our out of sync on the last item of the cursor)
            if (URI_MATCHER.match(uri) == CatalogContract.Provider.CODE_GROUP_ID) {
                updateInternalDataSyncStatus(cursor, tableName, SyncStatus.UPTODATE);
            }
        }
        // Data updated, we invalidate the data
        else {
            Log.i(TAG, "Data for " + uri.toString() + " is up-of-date, invalidating it");
            updateInternalDataSyncStatus(cursor, tableName, SyncStatus.OUTOFDATE);
        }

    }
    // No data found, we request a sync if it's not already up-to-date
    else {
        boolean triggerSyncAdapter;

        switch (URI_MATCHER.match(uri)) {

        // Saving the sync info for the group
        case CatalogContract.Provider.CODE_GROUP_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriSyncGroup(authority),
                    CatalogContract.DataBaseSyncStatusGroup.ATT_GROUP_ID,
                    CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, lastPathSegment);

            break;

        // Saving the sync info for the data
        case CatalogContract.Provider.CODE_DATA_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriData(authority),
                    CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataSimple.TABLE_NAME,
                    lastPathSegment);
            break;

        // Saving the sync info for the data details
        case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
            triggerSyncAdapter = updateTrackSyncStatus(CatalogContract.Provider.getUriDataDetails(authority),
                    CatalogContract.DataBaseData.ATT_DATA_ID, CatalogContract.DataBaseDataDetails.TABLE_NAME,
                    lastPathSegment);
            break;

        default:
            Log.e(TAG, "URI not recognized" + uri.toString());
            throw new IllegalArgumentException("URI not recognized" + uri.toString());

        }

        // Trigger the sync adapter
        if (triggerSyncAdapter) {
            Log.i(TAG, "No data found for " + uri.toString() + " and data out-of-date, requesting a sync");
            requestSync(bundleSyncAdapter);
        } else {
            Log.i(TAG, "No data found for " + uri.toString() + " and data up-to-date");
        }

    }

    return cursor;
}

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * Uploads any unpublished casts./*from  ww w . jav a 2 s . c o  m*/
 *
 * This is the method that does all the hard work.
 *
 * @param toSync
 * @param provider
 * @param syncMap
 * @param syncResult
 * @return the number of casts uploaded.
 * @throws JSONException
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws NoPublicPath
 * @throws RemoteException
 * @throws OperationApplicationException
 * @throws SyncException
 * @throws InterruptedException
 */
private int uploadUnpublished(Uri toSync, Account account, ContentProviderClient provider, SyncMap syncMap,
        HashMap<String, SyncEngine.SyncStatus> syncStatuses, SyncResult syncResult)
        throws JSONException, NetworkProtocolException, IOException, NoPublicPath, RemoteException,
        OperationApplicationException, SyncException, InterruptedException {
    int count = 0;

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final Cursor uploadMe = provider.query(toSync, null, SELECTION_UNPUBLISHED, null, null);

    if (uploadMe == null) {
        throw new SyncException("could not query " + toSync);
    }

    final int idCol = uploadMe.getColumnIndex(JsonSyncableItem._ID);

    try {
        for (uploadMe.moveToFirst(); !uploadMe.isAfterLast(); uploadMe.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = uploadMe.getLong(idCol);

            final Uri localUri = isDir ? ContentUris.withAppendedId(toSync, id) : toSync;
            final String postUri = MediaProvider.getPostPath(mContext, localUri);

            Intent intent = new Intent(SYNC_STATUS_CHANGED);
            intent.putExtra(EXTRA_SYNC_STATUS, "castBegin");
            intent.putExtra(EXTRA_SYNC_ID, id);
            mContext.sendStickyBroadcast(intent);

            try {
                final JSONObject jo = JsonSyncableItem.toJSON(mContext, localUri, uploadMe, syncMap);

                if (DEBUG) {
                    Log.d(TAG, "uploading " + localUri + " to " + postUri);
                }

                // Upload! Any non-successful responses are handled by
                // exceptions.
                final HttpResponse res = mNetworkClient.post(postUri, jo.toString());

                long serverTime;
                try {
                    serverTime = getServerTime(res);
                    // We should never get a corrupted date from the server,
                    // but if it does happen,
                    // using the local time is a sane fallback.
                } catch (final DateParseException e) {
                    serverTime = System.currentTimeMillis();
                }

                // newly-created items return the JSON serialization of the
                // object as the server
                // knows it, so the local database needs to be updated to
                // reflect that.
                final JSONObject newJo = NetworkClient.toJsonObject(res);
                try {
                    final SyncStatus ss = loadItemFromJsonObject(newJo, syncMap, serverTime);

                    // update immediately, so that any cancellation or
                    // interruption of the sync
                    // keeps the local state in sync with what's on the
                    // server
                    final int updates = provider.update(localUri, ss.remoteCVs, null, null);

                    final String locUriString = localUri.toString();

                    if (updates == 1) {
                        ss.state = SyncState.NOW_UP_TO_DATE;
                        ss.local = localUri;

                        // ensure that it's findable by local URI too
                        syncStatuses.put(locUriString, ss);

                        syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson, true);

                        count++;
                        syncResult.stats.numUpdates++;

                    } else {
                        Log.e(TAG, "error updating " + locUriString);

                        syncResult.stats.numSkippedEntries++;
                    }

                    syncResult.stats.numEntries++;

                } catch (final JSONException e) {
                    if (DEBUG) {
                        Log.e(TAG, "result was " + newJo.toString());
                    }
                    throw e;
                }
            } finally {
                intent = new Intent(SYNC_STATUS_CHANGED);
                intent.putExtra(EXTRA_SYNC_STATUS, "castEnd");
                intent.putExtra(EXTRA_SYNC_ID, id);
                mContext.sendStickyBroadcast(intent);
            }
        }
    } finally {
        uploadMe.close();
    }

    return count;
}