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.digipom.manteresting.android.fragment.NailFragment.java

private boolean handleMenuItemSelected(int listItemPosition, int itemId) {
    listItemPosition -= listView.getHeaderViewsCount();

    if (listItemPosition >= 0 && listItemPosition < nailAdapter.getCount()) {
        switch (itemId) {
        case R.id.share:
            try {
                final Cursor cursor = (Cursor) nailAdapter.getItem(listItemPosition);

                if (cursor != null && !cursor.isClosed()) {
                    final int nailId = cursor.getInt(cursor.getColumnIndex(Nails.NAIL_ID));
                    final JSONObject nailJson = new JSONObject(
                            cursor.getString(cursor.getColumnIndex(Nails.NAIL_JSON)));

                    final Uri uri = MANTERESTING_SERVER.buildUpon().appendPath("nail")
                            .appendPath(String.valueOf(nailId)).build();
                    String description = nailJson.getString("description");

                    if (description.length() > 100) {
                        description = description.substring(0, 97) + '';
                    }//from  w ww. ja  v a2  s.  c o m

                    final String user = nailJson.getJSONObject("user").getString("username");
                    final String category = nailJson.getJSONObject("workbench").getJSONObject("category")
                            .getString("title");

                    final Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("text/plain");
                    shareIntent.putExtra(Intent.EXTRA_TEXT, description + ' ' + uri.toString());
                    shareIntent.putExtra(Intent.EXTRA_SUBJECT,
                            String.format(getResources().getString(R.string.shareSubject), user, category));
                    try {
                        startActivity(Intent.createChooser(shareIntent, getText(R.string.share)));
                    } catch (ActivityNotFoundException e) {
                        new AlertDialog.Builder(getActivity()).setMessage(R.string.noShareApp).show();
                    }
                }
            } catch (Exception e) {
                if (LoggerConfig.canLog(Log.WARN)) {
                    Log.w(TAG, "Could not share nail at position " + listItemPosition + " with id " + itemId);
                }
            }

            return true;
        default:
            return false;
        }
    } else {
        return false;
    }
}

From source file:org.mobisocial.corral.ContentCorral.java

/**
 * If the given path is provisioned by baseUri, returns a localized
 * representation of that path.//  ww  w  . j a  v  a 2  s.  com
 */
private String absoluteToRelative(Uri baseUri, String path) {
    if (path.startsWith(baseUri.toString())) {
        path = path.substring(baseUri.toString().length());
        Log.d(TAG, "TRUNCATED TO " + path);
    }
    return path;
}

From source file:com.wiret.arbrowser.AbstractArchitectCamActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == KmlFileBrowserActivity.FILE_SELECT_CODE) {
        if (resultCode == RESULT_OK) {
            try {
                String filename = "";
                Uri uri = data.getData();

                if (false) {
                    Toast.makeText(this,
                            "The selected file is too large. Selet a new file with size less than 2mb",
                            Toast.LENGTH_LONG).show();
                } else {
                    String mimeType = getContentResolver().getType(uri);
                    if (mimeType == null) {
                        String path = getPath(this, uri);
                        if (path == null) {
                            filename = FilenameUtils.getName(uri.toString());
                        } else {
                            File file = new File(path);
                            filename = file.getName();
                        }/*from w w w.j  av a  2  s . c om*/
                    } else {
                        Uri returnUri = data.getData();
                        Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
                        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                        returnCursor.moveToFirst();
                        filename = returnCursor.getString(nameIndex);
                        String size = Long.toString(returnCursor.getLong(sizeIndex));
                    }
                    String sourcePath = getExternalFilesDir(null).toString();
                    try {
                        File outputPath = new File(sourcePath + "/" + filename);
                        copyFileStream(outputPath, uri, this);
                        importData(outputPath.getAbsolutePath());

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

From source file:com.hichinaschool.flashcards.async.Connection.java

/**
 * Downloads any missing media files according to the mediaURL deckvar.
 * /*from   ww w . ja  va 2 s  .  co m*/
 * @param data
 * @return The return type contains data.resultType and an array of Integer in data.data. data.data[0] is the number
 *         of total missing media, data.data[1] is the number of downloaded ones.
 */
private Payload doInBackgroundDownloadMissingMedia(Payload data) {
    // Log.i(AnkiDroidApp.TAG, "DownloadMissingMedia");
    HashMap<String, String> missingPaths = new HashMap<String, String>();
    HashMap<String, String> missingSums = new HashMap<String, String>();

    Decks deck = (Decks) data.data[0];
    data.result = deck; // pass it to the return object so we close the deck in the deck picker
    String syncName = "";// deck.getDeckName();

    data.success = false;
    data.data = new Object[] { 0, 0, 0 };
    // if (!deck.hasKey("mediaURL")) {
    // data.success = true;
    // return data;
    // }
    String urlbase = "";// deck.getVar("mediaURL");
    if (urlbase.equals("")) {
        data.success = true;
        return data;
    }

    String mdir = "";// deck.mediaDir(true);
    int totalMissing = 0;
    int missing = 0;
    int grabbed = 0;

    Cursor cursor = null;
    try {
        cursor = null;// deck.getDB().getDatabase().rawQuery("SELECT filename, originalPath FROM media", null);
        String path = null;
        String f = null;
        while (cursor.moveToNext()) {
            f = cursor.getString(0);
            path = mdir + "/" + f;
            File file = new File(path);
            if (!file.exists()) {
                missingPaths.put(f, path);
                missingSums.put(f, cursor.getString(1));
                // Log.i(AnkiDroidApp.TAG, "Missing file: " + f);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    totalMissing = missingPaths.size();
    data.data[0] = new Integer(totalMissing);
    if (totalMissing == 0) {
        data.success = true;
        return data;
    }
    publishProgress(Boolean.FALSE, new Integer(totalMissing), new Integer(0), syncName);

    URL url = null;
    HttpURLConnection connection = null;
    String path = null;
    String sum = null;
    int readbytes = 0;
    byte[] buf = new byte[4096];
    for (String file : missingPaths.keySet()) {

        try {
            android.net.Uri uri = android.net.Uri.parse(Uri.encode(urlbase, ":/@%") + Uri.encode(file));
            url = new URI(uri.toString()).toURL();
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 200) {
                path = missingPaths.get(file);
                InputStream is = connection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is, 4096);
                FileOutputStream fos = new FileOutputStream(path);
                while ((readbytes = bis.read(buf, 0, 4096)) != -1) {
                    fos.write(buf, 0, readbytes);
                    // Log.i(AnkiDroidApp.TAG, "Downloaded " + readbytes + " file: " + path);
                }
                fos.close();

                // Verify with checksum
                sum = missingSums.get(file);
                if (true) {// sum.equals("") || sum.equals(Utils.fileChecksum(path))) {
                    grabbed++;
                } else {
                    // Download corrupted, delete file
                    // Log.i(AnkiDroidApp.TAG, "Downloaded media file " + path + " failed checksum.");
                    File f = new File(path);
                    f.delete();
                    missing++;
                }
            } else {
                Log.e(AnkiDroidApp.TAG, "Connection error (" + connection.getResponseCode()
                        + ") while retrieving media file " + urlbase + file);
                Log.e(AnkiDroidApp.TAG, "Connection message: " + connection.getResponseMessage());
                if (missingSums.get(file).equals("")) {
                    // Ignore and keep going
                    missing++;
                } else {
                    data.success = false;
                    data.data = new Object[] { file };
                    return data;
                }
            }
            connection.disconnect();
        } catch (URISyntaxException e) {
            Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e));
        } catch (MalformedURLException e) {
            Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e));
            Log.e(AnkiDroidApp.TAG, "MalformedURLException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e));
            Log.e(AnkiDroidApp.TAG, "IOException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        publishProgress(Boolean.TRUE, new Integer(totalMissing), new Integer(grabbed + missing), syncName);
    }

    data.data[1] = new Integer(grabbed);
    data.data[2] = new Integer(missing);
    data.success = true;
    return data;
}

From source file:dk.dr.radio.afspilning.Afspiller.java

void ringDenAlarm() {
      Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
      if (alert == null) {
          // alert is null, using backup
          alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          if (alert == null) { // I can't see this ever being null (as always have a default notification) but just incase
              // alert backup is null, using 2nd backup
              alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
          }/* w w  w  .  j  av  a2 s. c  om*/
      }
      lydkilde = new AlarmLydkilde(alert.toString(), lydkilde);
      handler.postDelayed(startAfspilningIntern, 100);
      vibru(4000);
  }

From source file:com.aniruddhc.acemusic.player.LauncherActivity.LauncherActivity.java

/** Given a URI, returns a map of campaign data that can be sent with
 * any GA hit./*from w  w w.j a  va  2 s.c  om*/
 *
 * @param uri A hierarchical URI that may or may not have campaign data
 *     stored in query parameters.
 *
 * @return A map that may contain campaign or referrer
 *     that may be sent with any Google Analytics hit.
    */
private Map<String, String> getReferrerMapFromUri(Uri uri) {
    MapBuilder paramMap = new MapBuilder();

    //If no URI, return an empty Map.
    if (uri == null) {
        return paramMap.build();
    }

    /* Source is the only required campaign field. No need to continue if not
     * present. */
    if (uri.getQueryParameter(CAMPAIGN_SOURCE_PARAM) != null) {

        /* MapBuilder.setCampaignParamsFromUrl parses Google Analytics campaign
         * ("UTM") parameters from a string URL into a Map that can be set on
         * the Tracker. */
        paramMap.setCampaignParamsFromUrl(uri.toString());

        /* If no source parameter, set authority to source and medium to
         * "referral". */
    } else if (uri.getAuthority() != null) {
        paramMap.set(Fields.CAMPAIGN_MEDIUM, "referral");
        paramMap.set(Fields.CAMPAIGN_SOURCE, uri.getAuthority());
    }

    return paramMap.build();
}

From source file:com.example.scrumptious.SelectionFragment.java

private Pair<File, Integer> getImageFileAndMinDimension() {
    File photoFile = null;/*from   w ww .  j  a v  a 2s.c o  m*/
    String photoUriString = photoUri.toString();
    if (photoUriString.startsWith("file://")) {
        photoFile = new File(photoUri.getPath());
    } else if (photoUriString.startsWith("content://")) {
        FileOutputStream photoOutputStream = null;
        InputStream contentInputStream = null;
        try {
            Uri photoUri = Uri.parse(photoUriString);
            photoFile = new File(getTempPhotoStagingDirectory(),
                    URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8"));

            photoOutputStream = new FileOutputStream(photoFile);
            contentInputStream = getActivity().getContentResolver().openInputStream(photoUri);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = contentInputStream.read(buffer)) > 0) {
                photoOutputStream.write(buffer, 0, len);
            }
        } catch (FileNotFoundException fnfe) {
            Log.e(TAG, "photo not found", fnfe);
        } catch (UnsupportedEncodingException uee) {
            Log.e(TAG, "bad photo name", uee);
        } catch (IOException ioe) {
            Log.e(TAG, "can't copy photo", ioe);
        } finally {
            try {
                if (photoOutputStream != null) {
                    photoOutputStream.close();
                }
                if (contentInputStream != null) {
                    contentInputStream.close();
                }
            } catch (IOException ioe) {
                Log.e(TAG, "can't close streams");
            }
        }
    }

    if (photoFile != null) {
        InputStream is = null;
        try {
            is = new FileInputStream(photoFile);

            // We only want to get the bounds of the image, rather than load the whole thing.
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, options);

            return new Pair<>(photoFile, Math.min(options.outWidth, options.outHeight));
        } catch (Exception e) {
            return null;
        } finally {
            Utility.closeQuietly(is);
        }
    }
    return null;
}

From source file:com.appdynamics.demo.gasp.service.RESTIntentService.java

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

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        Log.e(TAG, "You did not pass extras or data with the Intent.");
        return;
    }

    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    Bundle headers = extras.getParcelable(EXTRA_HEADERS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        HttpRequestBase request = null;

        // Get query params from Bundle and build URL
        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()));

            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()));

            HttpPut putRequest = (HttpPut) request;

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

        // Get Headers from Bundle
        for (BasicNameValuePair header : paramsToList(headers)) {
            request.setHeader(header.getName(), header.getValue());
        }

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

            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            HttpResponse response = client.execute(request);

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

            if ((responseEntity != null) && (responseStatus.getStatusCode() == 200)) {
                Bundle resultData = new Bundle();
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                receiver.send(statusCode, resultData);
            } else {
                receiver.send(statusCode, null);
            }
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e);
        receiver.send(0, null);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        receiver.send(0, null);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:sjizl.com.ChatActivity.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        if (data != null) {
            // Get the URI of the selected file
            final Uri uri = data.getData();
            Log.i("ffff:", "Uri = " + uri.toString());
            try {
                // Get the file path from the URI
                final String path = FileUtils.getPath(this, uri);
                //      Toast.makeText(ChatActivity.this,
                //    "File Selected: " + path, Toast.LENGTH_LONG).show();

                //     CommonUtilities.custom_toast(getApplicationContext(), ChatActivity.this,"File Selected: " + path,  null,R.drawable.iconbd);                   

                Thread thread = new Thread(new Runnable() {
                    public void run() {
                        doFileUpload(path);
                        runOnUiThread(new Runnable() {
                            public void run() {

                            }/*  ww  w. ja  va  2 s .  c  om*/
                        });
                    }
                });
                thread.start();

            } catch (Exception e) {
                Log.e("FileSelectorTestActivity", "File select error", e);
            }
        }
    }

}