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.antew.redditinpictures.library.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    Uri action = intent.getData();
    Bundle extras = intent.getExtras();/*from   w ww . j a  va  2  s  .  c  o  m*/

    if (extras == null || action == null) {
        Ln.e("You did not pass extras or data with the Intent.");
        return;
    }

    // We default to GET if no verb was specified.
    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    RequestCode requestCode = (RequestCode) extras.getSerializable(EXTRA_REQUEST_CODE);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    String cookie = extras.getString(EXTRA_COOKIE);
    String userAgent = extras.getString(EXTRA_USER_AGENT);

    // Items in this bundle are simply passed on in onRequestComplete
    Bundle passThrough = extras.getBundle(EXTRA_PASS_THROUGH);

    HttpEntity responseEntity = null;
    Intent result = new Intent(Constants.Broadcast.BROADCAST_HTTP_FINISHED);
    result.putExtra(EXTRA_PASS_THROUGH, passThrough);
    Bundle resultData = new Bundle();

    try {
        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            DefaultHttpClient client = new DefaultHttpClient();

            // GZip requests
            // antew on 3/12/2014 - Disabling GZIP for now, need to figure this CloseGuard error:
            // 03-12 21:02:09.248    9674-9683/com.antew.redditinpictures.pro E/StrictMode A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
            //         java.lang.Throwable: Explicit termination method 'end' not called
            // at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            // at java.util.zip.Inflater.<init>(Inflater.java:82)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:96)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81)
            // at com.antew.redditinpictures.library.service.RESTService$GzipDecompressingEntity.getContent(RESTService.java:346)
            client.addRequestInterceptor(getGzipRequestInterceptor());
            client.addResponseInterceptor(getGzipResponseInterceptor());

            if (cookie != null) {
                request.addHeader("Cookie", cookie);
            }

            if (userAgent != null) {
                request.addHeader("User-Agent", Constants.Reddit.USER_AGENT);
            }

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Ln.d("Executing request: %s %s ", verbToString(verb), action.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this thread.
            HttpResponse response = client.execute(request);

            responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            if (responseEntity != null) {
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                resultData.putSerializable(EXTRA_REQUEST_CODE, requestCode);
                resultData.putInt(EXTRA_STATUS_CODE, statusCode);
                result.putExtra(EXTRA_BUNDLE, resultData);

                onRequestComplete(result);
            } else {
                onRequestFailed(result, statusCode);
            }
        }
    } catch (URISyntaxException e) {
        Ln.e(e, "URI syntax was incorrect. %s %s ", verbToString(verb), action.toString());
        onRequestFailed(result, 0);
    } catch (UnsupportedEncodingException e) {
        Ln.e(e, "A UrlEncodedFormEntity was created with an unsupported encoding.");
        onRequestFailed(result, 0);
    } catch (ClientProtocolException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } catch (IOException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } finally {
        if (responseEntity != null) {
            try {
                responseEntity.consumeContent();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.cloudstudio.camera.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits.//ww w  .  j a v  a 2 s  . com
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost
            // during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(
                    getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // Create entry in media store for image
            // (Don't use insertImage() because it uses default compression
            // setting of 50 - no way to change it)
            ContentValues values = new ContentValues();
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = null;
            try {
                Log.d("camera", "external_content_uri:"
                        + android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                uri = this.cordova.getActivity().getContentResolver()
                        .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } catch (UnsupportedOperationException e) {
                LOG.d(LOG_TAG, "Can't write to external media storage.");
                try {
                    uri = this.cordova.getActivity().getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException ex) {
                    LOG.d(LOG_TAG, "Can't write to internal media storage.");
                    this.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }
            Log.d("camera", "uri:" + uri.toString());
            // 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
            exif.createOutFile(getRealPathFromURI(uri, this.cordova));
            exif.writeExifData();

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

            bitmap.recycle();
            bitmap = null;
            System.gc();

            checkForDuplicateImage();
        } catch (IOException e) {
            e.printStackTrace();
            this.failPicture("Error capturing image.");
        }
    }

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}

From source file:com.karura.framework.plugins.utils.ContactAccessorSdk5.java

/**
 * Create a ContactField JSONObject//from w  w w  .ja v  a  2 s. c om
 * 
 * @param contactId
 * @return a JSONObject representing a ContactField
 */
private JSONObject photoQuery(Cursor cursor, String contactId) {
    JSONObject photo = new JSONObject();
    try {
        photo.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo._ID)));
        photo.put("pref", false);
        photo.put("type", "url");
        Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, (new Long(contactId)));
        Uri photoUri = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        photo.put("value", photoUri.toString());
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return photo;
}

From source file:com.remobile.contacts.ContactAccessorSdk5.java

/**
 * Create a ContactField JSONObject//from  w w  w.ja v  a 2 s .c  om
 * @param contactId
 * @return a JSONObject representing a ContactField
 */
private JSONObject photoQuery(Cursor cursor, String contactId) {
    JSONObject photo = new JSONObject();
    try {
        photo.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo._ID)));
        photo.put("pref", false);
        photo.put("type", "url");
        Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                (Long.valueOf(contactId)));
        Uri photoUri = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        photo.put("value", photoUri.toString());

        // Query photo existance
        Cursor photoCursor = mApp.getActivity().getContentResolver().query(photoUri,
                new String[] { ContactsContract.Contacts.Photo.PHOTO }, null, null, null);
        if (photoCursor == null) {
            return null;
        } else {
            if (!photoCursor.moveToFirst()) {
                photoCursor.close();
                return null;
            }
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return photo;
}

From source file:com.fvd.nimbus.PaintActivity.java

/** Called when the activity is first created. */
@Override//ww w  .j a  va  2s  .co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
    overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    try {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    } catch (Exception e) {
        e.printStackTrace();
    }
    ctx = this;
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    dWidth = prefs.getInt("dWidth", 2);
    fWidth = prefs.getInt("fWidth", 1);
    dColor = prefs.getInt(pColor, Color.RED);
    saveFormat = Integer.parseInt(prefs.getString("saveFormat", "1"));
    serverHelper.getInstance().setCallback(this, this);
    serverHelper.getInstance().setMode(saveFormat);
    setContentView(R.layout.screen_edit);
    drawer = (DrawerLayout) findViewById(R.id.root);
    findViewById(R.id.bDraw1).setOnClickListener(this);
    findViewById(R.id.bDraw2).setOnClickListener(this);
    findViewById(R.id.bDraw3).setOnClickListener(this);
    findViewById(R.id.bDraw4).setOnClickListener(this);
    findViewById(R.id.bDraw5).setOnClickListener(this);
    findViewById(R.id.bDraw6).setOnClickListener(this);
    findViewById(R.id.bDraw8).setOnClickListener(this);
    findViewById(R.id.bColor1).setOnClickListener(this);
    findViewById(R.id.bColor2).setOnClickListener(this);
    findViewById(R.id.bColor3).setOnClickListener(this);
    findViewById(R.id.bColor4).setOnClickListener(this);
    findViewById(R.id.bColor5).setOnClickListener(this);
    paletteButton = (CircleButton) findViewById(R.id.bToolColor);
    paletteButton.setOnClickListener(this);

    paletteButton_land = (CircleButton) findViewById(R.id.bToolColor_land);
    //paletteButton_land.setOnClickListener(this);

    ((SeekBar) findViewById(R.id.seekBarLine)).setProgress(dWidth * 10);
    ((SeekBar) findViewById(R.id.seekBarType)).setProgress(fWidth * 10);

    ((TextView) findViewById(R.id.tvTextType)).setText(String.format("%d", 40 + fWidth * 20));

    findViewById(R.id.bUndo).setOnClickListener(this);
    findViewById(R.id.btnBack).setOnClickListener(this);
    findViewById(R.id.bClearAll).setOnClickListener(this);
    findViewById(R.id.bTurnLeft).setOnClickListener(this);
    findViewById(R.id.bTurnRight).setOnClickListener(this);
    findViewById(R.id.bDone).setOnClickListener(this);
    findViewById(R.id.bApplyText).setOnClickListener(this);

    ((ImageButton) findViewById(R.id.bStroke)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            v.setSelected(!v.isSelected());
        }
    });

    lineWidthListener = new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub
            if (true || fromUser) {
                /*dWidth = (progress/10);
                 drawView.setWidth((dWidth+1)*5);*/
                dWidth = progress;
                drawView.setWidth(dWidth);
                Editor e = prefs.edit();
                e.putInt("dWidth", dWidth);
                e.commit();
            }

        }
    };

    ((SeekBar) findViewById(R.id.seekBarLine)).setOnSeekBarChangeListener(lineWidthListener);
    ((SeekBar) findViewById(R.id.ls_seekBarLine)).setOnSeekBarChangeListener(lineWidthListener);

    fontSizeListener = new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub

            if (fromUser) {
                fWidth = progress / 10;
                int c = 40 + fWidth * 20;
                drawView.setFontSize(c);
                Editor e = prefs.edit();
                e.putInt("fWidth", fWidth);
                e.commit();
                try {
                    ((TextView) findViewById(R.id.tvTextType)).setText(String.format("%d", c));
                    ((TextView) findViewById(R.id.ls_tvTextType)).setText(String.format("%d", c));
                } catch (Exception ex) {

                }

            }
        }
    };

    ((SeekBar) findViewById(R.id.seekBarType)).setOnSeekBarChangeListener(fontSizeListener);
    ((SeekBar) findViewById(R.id.ls_seekBarType)).setOnSeekBarChangeListener(fontSizeListener);

    drawView = (DrawView) findViewById(R.id.painter);
    drawView.setWidth((dWidth + 1) * 5);
    drawView.setFontSize(40 + fWidth * 20);

    setBarConfig(getResources().getConfiguration().orientation);

    findViewById(R.id.bEditPage).setOnClickListener(this);
    findViewById(R.id.bToolColor).setOnClickListener(this);
    findViewById(R.id.bErase).setOnClickListener(this);
    findViewById(R.id.bToolShape).setOnClickListener(this);
    findViewById(R.id.bToolText).setOnClickListener(this);
    findViewById(R.id.bToolCrop).setOnClickListener(this);
    findViewById(R.id.btnBack).setOnClickListener(this);
    findViewById(R.id.bDone).setOnClickListener(this);
    findViewById(R.id.btnShare).setOnClickListener(this);
    findViewById(R.id.bSave2SD).setOnClickListener(this);
    findViewById(R.id.bSave2Nimbus).setOnClickListener(this);

    userMail = prefs.getString("userMail", "");
    userPass = prefs.getString("userPass", "");
    sessionId = prefs.getString("sessionId", "");

    appSettings.sessionId = sessionId;
    appSettings.userMail = userMail;
    appSettings.userPass = userPass;

    storePath = "";
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    //storePath= intent.getPackage().getClass().toString();
    if ((Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SEND.equals(action)
            || "com.onebit.nimbusnote.EDIT_PHOTO".equals(action)) && type != null) {
        if (type.startsWith("image/")) {
            Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
            if (imageUri == null)
                imageUri = intent.getData();
            if (imageUri != null) {
                String url = Uri.decode(imageUri.toString());
                if (url.startsWith(CONTENT_PHOTOS_URI_PREFIX)) {
                    url = getPhotosPhotoLink(url);
                } //else url=Uri.decode(url);

                ContentResolver cr = getContentResolver();
                InputStream is;

                try {
                    is = cr.openInputStream(Uri.parse(url));
                    if ("com.onebit.nimbusnote.EDIT_PHOTO".equals(action))
                        storePath = " ";//getGalleryPath(Uri.parse(url));
                    Bitmap bmp = BitmapFactory.decodeStream(is);
                    if (bmp.getWidth() != -1 && bmp.getHeight() != -1)
                        drawView.setBitmap(bmp, 0);
                } catch (Exception e) {
                    appSettings.appendLog("paint:onCreate  " + e.getMessage());
                }
            }
        }
    } else {
        String act = getIntent().getExtras().getString("act");
        if ("photo".equals(act)) {
            getPhoto();
        } else if ("picture".equals(act)) {
            getPicture();
        } else {
            String filePath = getIntent().getExtras().getString("path");
            boolean isTemp = getIntent().getExtras().getBoolean("temp");
            domain = getIntent().getExtras().getString("domain");
            if (domain == null)
                domain = serverHelper.getDate();
            if (filePath.contains("://")) {
                Bitmap bmp = helper.LoadImageFromWeb(filePath);
                if (bmp != null) {
                    drawView.setBitmap(bmp, 0);
                }
            } else {
                File file = new File(filePath);
                if (file.exists()) {
                    try {
                        int orient = helper.getOrientationFromExif(filePath);
                        Bitmap bmp = helper.decodeSampledBitmap(filePath, 1000, 1000);
                        if (bmp != null) {
                            drawView.setBitmap(bmp, orient);
                        }
                    } catch (Exception e) {
                        appSettings.appendLog("paint.onCreate()  " + e.getMessage());
                    }
                    if (isTemp)
                        file.delete();
                }
            }
        }
    }

    drawView.setBackgroundColor(Color.WHITE);
    drawView.requestFocus();
    drawView.setColour(dColor);
    setPaletteColor(dColor);

    drawView.setSelChangeListener(new shapeSelectionListener() {

        @Override
        public void onSelectionChanged(int shSize, int fSize, int shColor) {
            setSelectedFoot(0);
            setLandToolSelected(R.id.bEditPage_land);
            //updateColorDialog(shSize!=-1?(shSize/5)-1:dWidth, fSize!=-1?(fSize-40)/20:fWidth, shColor!=0?colorToId(shColor):dColor);
            dColor = shColor;
            ccolor = shColor;
            int sw = shSize != -1 ? shSize : dWidth;
            canChange = false;
            ((SeekBar) findViewById(R.id.seekBarLine)).setProgress(sw);
            ((SeekBar) findViewById(R.id.ls_seekBarLine)).setProgress(sw);
            setPaletteColor(dColor);
            drawView.setColour(dColor);
            canChange = true;
        }

        @Override
        public void onTextChanged(String text, boolean stroke) {

            if (findViewById(R.id.text_field).getVisibility() != View.VISIBLE) {
                hideTools();

                findViewById(R.id.bStroke).setSelected(stroke);
                ((EditText) findViewById(R.id.etEditorText)).setText(text);
                findViewById(R.id.text_field).setVisibility(View.VISIBLE);
                findViewById(R.id.etEditorText).requestFocus();
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                        .showSoftInput(findViewById(R.id.etEditorText), 0);
                findViewById(R.id.bToolText).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        setSelectedFoot(2);

                    }
                }, 100);

            }
        }

    });

    setColorButtons(dColor);

    //mPlanetTitles = getResources().getStringArray(R.array.lmenu_paint);

    /*ListView listView = (ListView) findViewById(R.id.left_drawer);
    listView.setAdapter(new DrawerMenuAdapter(this,getResources().getStringArray(R.array.lmenu_paint)));
    listView.setOnItemClickListener(this);*/
}

From source file:com.ringdroid.RingdroidEditActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    if (id == DIALOG_USE_ALL) {
        return new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle(R.string.ring_picker_title)
                .setSingleChoiceItems(R.array.set_ring_option, 0, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ring_button_type = whichButton;
                    }/*from ww  w . ja v  a  2  s.c o m*/
                }).setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        int ring_type = 0;
                        if (ring_button_type == 3) {
                            Intent intent = new Intent();
                            Uri currentFileUri = Uri.parse(mFilename);
                            intent.setData(currentFileUri);
                            intent.setClass(RingdroidEditActivity.this,
                                    com.ringdroid.ChooseContactActivity.class);
                            RingdroidEditActivity.this.startActivity(intent);
                            return;
                        } else if (ring_button_type == 0) {
                            ring_type = RingtoneManager.TYPE_RINGTONE;
                        } else if (ring_button_type == 1) {
                            ring_type = RingtoneManager.TYPE_NOTIFICATION;
                        } else if (ring_button_type == 2) {
                            ring_type = RingtoneManager.TYPE_ALARM;
                        }
                        // u = Const.mp3dir + ring.getString(Const.mp3);
                        Uri currentFileUri = null;
                        if (!mFilename.startsWith("content:")) {
                            String selection;
                            selection = MediaStore.Audio.Media.DATA + "=?";//+"='"+DatabaseUtils.sqlEscapeString(mFilename)+"'";
                            String[] selectionArgs = new String[1];
                            selectionArgs[0] = mFilename;

                            Uri head = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                            Cursor c = getExternalAudioCursor(selection, selectionArgs);
                            if (c == null || c.getCount() == 0) {
                                head = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
                                c = getInternalAudioCursor(selection, selectionArgs);
                            }
                            startManagingCursor(c);
                            if (c == null || c.getCount() == 0)
                                return;
                            c.moveToFirst();
                            String itemUri = head.toString() + "/"
                                    + c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                            currentFileUri = Uri.parse(itemUri);
                        } else {
                            currentFileUri = Uri.parse(mFilename);
                        }
                        RingtoneManager.setActualDefaultRingtoneUri(RingdroidEditActivity.this, ring_type,
                                currentFileUri);
                        Toast.makeText(RingdroidEditActivity.this,
                                "" + getResources().getStringArray(R.array.set_ring_option)[ring_button_type],
                                Toast.LENGTH_SHORT).show();
                    }
                }).setNegativeButton(R.string.alertdialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).create();
    }
    return super.onCreateDialog(id);
}

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

/**
 * Brings up the UI to perform crop on passed image URI
 *
 * @param picUri/*from   w ww  .  j  ava  2 s  .co  m*/
 */
private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties
        cropIntent.putExtra("crop", "true");
        // indicate output X and Y
        if (targetWidth > 0) {
            cropIntent.putExtra("outputX", targetWidth);
        }
        if (targetHeight > 0) {
            cropIntent.putExtra("outputY", targetHeight);
        }
        if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
        }
        // create new file handle to get full resolution crop
        croppedUri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        cropIntent.putExtra("output", croppedUri);

        // start the activity - we handle returning in onActivityResult

        if (this.cordova != null) {
            this.cordova.startActivityForResult((CordovaPlugin) this, cropIntent, CROP_CAMERA);
        }
    } catch (ActivityNotFoundException anfe) {
        Log.e(LOG_TAG, "Crop operation not supported on this device");
        // Send Uri back to JavaScript for viewing image
        this.callbackContext.success(picUri.toString());
    }
}

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

/**
 * Brings up the UI to perform crop on passed image URI
 * /*from w  w  w .  java2  s  . c o  m*/
 * @param picUri
 */
private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties
        cropIntent.putExtra("crop", "true");
        // indicate output X and Y
        if (targetWidth > 0) {
            cropIntent.putExtra("outputX", targetWidth);
        }
        if (targetHeight > 0) {
            cropIntent.putExtra("outputY", targetHeight);
        }
        if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
        }
        // create new file handle to get full resolution crop
        croppedUri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        cropIntent.putExtra("output", croppedUri);

        // start the activity - we handle returning in onActivityResult

        if (this.activity != null) {
            this.activity.startActivityForResult(cropIntent, CROP_CAMERA);
        }
    } catch (ActivityNotFoundException anfe) {
        Log.e(LOG_TAG, "Crop operation not supported on this device");
        // Send Uri back to JavaScript for viewing image
        this.callbackContext.success(picUri.toString());
    }
}

From source file:net.mutina.uclimb.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits. /*from  ww w  .j a  va  2s  . co m*/
 * 
 * @param requestCode       The request code originally supplied to startActivityForResult(), 
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(getTempDirectoryPath(ctx.getContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(),
                        imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.ctx.getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // Create entry in media store for image
            // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
            ContentValues values = new ContentValues();
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = null;
            try {
                uri = this.ctx.getContentResolver()
                        .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } catch (UnsupportedOperationException e) {
                LOG.d(LOG_TAG, "Can't write to external media storage.");
                try {
                    uri = this.ctx.getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException ex) {
                    LOG.d(LOG_TAG, "Can't write to internal media storage.");
                    this.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }

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

            // Restore exif data to file
            exif.createOutFile(getRealPathFromURI(uri, this.ctx));
            exif.writeExifData();

            // Send Uri back to JavaScript for viewing image
            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);

            bitmap.recycle();
            bitmap = null;
            System.gc();

            checkForDuplicateImage();
        } catch (IOException e) {
            e.printStackTrace();
            this.failPicture("Error capturing image.");
        }
    }

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}