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:Main.java

@TargetApi(19)
public static File getFromMediaUri(Context context, ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;

    if (SCHEME_FILE.equals(uri.getScheme())) {
        return new File(uri.getPath());
    } else if (SCHEME_CONTENT.equals(uri.getScheme())) {
        String filePath = "";
        if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;//  w  ww  .j a  v a 2  s.  c  o  m
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            Cursor cursor = null;
            final String column = "_data";
            final String[] projection = { column };

            try {
                cursor = context.getContentResolver().query(contentUri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int column_index = cursor.getColumnIndexOrThrow(column);
                    filePath = cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        } else {
            final String[] filePathColumn = { MediaStore.MediaColumns.DATA,
                    MediaStore.MediaColumns.DISPLAY_NAME };
            Cursor cursor = null;
            try {
                cursor = resolver.query(uri, filePathColumn, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    final int columnIndex = (uri.toString()
                            .startsWith("content://com.google.android.gallery3d"))
                                    ? cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                                    : cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
                    // Picasa images on API 13+
                    if (columnIndex != -1) {
                        filePath = cursor.getString(columnIndex);
                    }
                }
            } catch (IllegalArgumentException e) {
                // Google Drive images
                return getFromMediaUriPfd(context, resolver, uri);
            } catch (SecurityException ignored) {
                // Nothing we can do
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        }

        if (!TextUtils.isEmpty(filePath)) {
            return new File(filePath);
        }
    }
    return null;
}

From source file:com.phonegap.Capture.java

/**
 * Creates a JSONObject that represents a File from the Uri
 *  //from  www. ja  v a 2s.c  om
 * @param data the Uri of the audio/image/video
 * @return a JSONObject that represents a File
 * @throws IOException 
 */
private JSONObject createMediaFile(Uri data) {
    File fp = new File(FileUtils.getRealPathFromURI(data, this.ctx));
    JSONObject obj = new JSONObject();

    try {
        // File properties
        obj.put("name", fp.getName());
        obj.put("fullPath", fp.getAbsolutePath());

        // Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files 
        // are reported as video/3gpp. I'm doing this hacky check of the URI to see if it 
        // is stored in the audio or video content store.
        if (fp.getAbsoluteFile().toString().endsWith(".3gp")
                || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
            if (data.toString().contains("/audio/")) {
                obj.put("type", AUDIO_3GPP);
            } else {
                obj.put("type", VIDEO_3GPP);
            }
        } else {
            obj.put("type", FileUtils.getMimeType(fp.getAbsolutePath()));
        }

        obj.put("lastModifiedDate", fp.lastModified());
        obj.put("size", fp.length());
    } catch (JSONException e) {
        // this will never happen
        e.printStackTrace();
    }

    return obj;
}

From source file:nf.frex.android.FrexActivity.java

private InputStream openHttpContentStream(Uri frexDocUri) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(frexDocUri.toString());
    HttpResponse response = client.execute(request);
    response.getStatusLine().getStatusCode();
    return response.getEntity().getContent();
}

From source file:com.polyvi.xface.extension.zip.XZipExt.java

/**
 * ?assets//  w w w  .j a  va  2  s. c o m
 *
 * @param srcFileUri
 * @param zos
 * @param entry
 * @throws IOException
 * @throws FileNotFoundException
 */
private void compressNormalFile(Uri srcFileUri, ZipOutputStream zos, String entry)
        throws IOException, FileNotFoundException {
    File srcFile = new File(srcFileUri.getPath());
    if (null == srcFile || !srcFile.exists()) {
        XLog.e(CLASS_NAME, "Method compressNormalFile:Source file path does not exist!");
        throw new FileNotFoundException();
    }
    String[] dirList = srcFile.list();
    if ((null == dirList || 1 > dirList.length) && srcFile.isFile()) {
        // ??
        zipFile(srcFileUri, zos, srcFile.getName());
    } else {
        // ?
        String srcRootPath = srcFileUri.toString();
        String srcFilePath = null;
        for (String pathName : dirList) {
            srcFilePath = srcRootPath + File.separator + pathName;
            srcFileUri = Uri.parse(srcFilePath);
            File f = new File(srcFileUri.getPath());
            if (f.isDirectory()) {
                compressNormalFile(srcFileUri, zos, entry + f.getName() + File.separator);
                continue;
            }
            zipFile(srcFileUri, zos, entry + f.getName());
        }
    }
}

From source file:com.example.rafa.sunshine.app.experiments.FetchWeatherTask.java

@Override
protected Void doInBackground(String... params) {

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }/*w w  w . ja v a  2s  .com*/
    String locationQuery = params[0];

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    try {
        // Construct the URL for the OpenWeatherMap query
        // Possible parameters are avaiable at OWM's forecast API page, at
        // http://openweathermap.org/API#forecast
        final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
        final String QUERY_PARAM = "q";
        final String FORMAT_PARAM = "mode";
        final String UNITS_PARAM = "units";
        final String DAYS_PARAM = "cnt";

        Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

        URL url = new URL(builtUri.toString());

        // Create the request to OpenWeatherMap, and open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            return null;
        }
        forecastJsonStr = buffer.toString();
        //getWeatherDataFromJson introdueix en la base de dades els registres correponents
        // a les dades del temps que agafem amb JSON
        getWeatherDataFromJson(forecastJsonStr, locationQuery);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attempting
        // to parse it.
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }
    return null;
}

From source file:com.xorcode.andtweet.PreferencesActivity.java

@Override
protected void onResume() {
    super.onResume();

    // Stop service to force preferences reload on the next start
    // Plus disable repeating alarms for awhile (till next start service...)
    AndTweetServiceManager.stopAndTweetService(this, true);

    showAllPreferences();/* w  ww  .  j ava  2  s  .  c  om*/
    MyPreferences.getDefaultSharedPreferences().registerOnSharedPreferenceChangeListener(this);

    Uri uri = getIntent().getData();
    if (uri != null) {
        if (MyLog.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "uri=" + uri.toString());
        }
        if (CALLBACK_URI.getScheme().equals(uri.getScheme())) {
            // To prevent repeating of this task
            getIntent().setData(null);
            // This activity was started by Twitter ("Service Provider")
            // so start second step of OAuth Authentication process
            new OAuthAcquireAccessTokenTask().execute(uri);
            // and return back to default screen
            overrideBackButton = true;
        }
    }
}

From source file:org.devtcg.five.provider.FiveSyncAdapter.java

private static void downloadFileAndUpdateProviderCancelable(final SyncContext context,
        final AbstractSyncProvider serverDiffs, final HttpGet request, final Uri localUri,
        final Uri localFeedItemUri, final String columnToUpdate) throws ClientProtocolException, IOException {
    sClient.execute(request, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                return null;

            if (context.hasCanceled())
                return null;

            /*//  w  ww .j  av  a 2 s.  c  om
             * Access a temp file path (FiveProvider treats this as a
             * special case when isTemporary is true and uses a temporary
             * path to be moved manually during merging).
             */
            ParcelFileDescriptor pfd = serverDiffs.openFile(localUri, "w");

            InputStream in = response.getEntity().getContent();
            OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(pfd);

            try {
                IOUtilities.copyStream(in, out);

                if (context.hasCanceled() == true)
                    return null;

                /*
                 * Update the record to reflect the newly downloaded uri.
                 * During table merging we'll need to move the file and
                 * update the uri we store here.
                 */
                ContentValues values = new ContentValues();
                values.put(columnToUpdate, localUri.toString());
                serverDiffs.update(localFeedItemUri, values, null, null);
            } finally {
                if (in != null)
                    IOUtilities.close(in);

                if (out != null)
                    IOUtilities.close(out);
            }

            return null;
        }
    });
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final int code = contentHelper.matchUri(uri);
    if (code != UriMatcher.NO_MATCH) {
        if (code == ContentHelper.uriSyncCode) {
            if (DEBUG) {
                Log.d(TAG, "CP-update-sync: " + uri.toString());
            }//from   w  w  w. j  a v a2  s  .com
            return (Sync(uri.getPathSegments().get(1), uri.getPathSegments().get(2), selection) ? 1 : 0);
        }
        final TableInfo tab = contentHelper.getTableFromCode(code & ContentHelper.uriCode);
        if (tab.readonly) {
            throw new IllegalArgumentException("Table " + tab.name + " is readonly.");
        }
        if (isItemCode(code)) {
            if (isItemRowIDCode(code)) {
                selection = "isDeleted=0 AND ROWID=" + uri.getPathSegments().get(2)
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
            } else {
                selection = "isDeleted=0" + tab.getSelection()
                        + (!TextUtils.isEmpty(selection) ? "(" + selection + ") AND " : "");
                int i = 0;
                final String[] old = selectionArgs;
                final int len = (old == null) ? 0 : old.length;
                selectionArgs = new String[len + tab.primaryKey.length];
                for (; i < tab.primaryKey.length; i++) {
                    selectionArgs[i] = uri.getPathSegments().get(i);
                }
                if (len > 0) {
                    for (; i < old.length; i++) {
                        selectionArgs[i] = old[i - tab.primaryKey.length];
                    }
                }
            }
        } else {
            selection = "isDeleted=0" + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
        }
        boolean syncToNetwork = checkSyncToNetwork(uri);
        values.put("isDirty", 1);
        int ret = getWritableDatabase().update(tab.name, values, selection, selectionArgs);
        if (ret > 0) {
            final ContentResolver cr = getContext().getContentResolver();
            cr.notifyChange(uri, null, syncToNetwork);
            for (String n : tab.notifyUris) {
                cr.notifyChange(Uri.parse(n), null, syncToNetwork);
            }
        }
        return ret;
    }
    throw new IllegalArgumentException("Unknown Uri " + uri);
}

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

private void setOutputUri(Intent intent, Uri uri) {
    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);

    JSONObject response;/* w  w w  . j a v  a  2s.c  o m*/
    try {
        response = new JSONObject();
        response.put("uri", uri.toString());
        response.put("pending", true);
    } catch (JSONException e) {
        Log.e(LOG_TAG, "On pending result creation" + e);
        return;
    }

    PluginResult r = new PluginResult(PluginResult.Status.OK, response);
    r.setKeepCallback(true);
    callbackContext.sendPluginResult(r);
}

From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

/**
 * The item names and descriptions are a separate API call from the News Items. This method
 * obtains the information on the items that have been looted, crafted, and purchased.
 *
 * @param itemId//from w ww.  j  a  v  a2s  .  c om
 *         id of item from news feed API to get from item API
 * @return JSON formatted string containing the item data
 *
 * @throws JSONException
 *         if any JSON object parsing fails
 * @see <a href="http://blizzard.github.io/api-wow-docs/">WOW API Documentation</a>
 */
private GuildViewerItem getItemFromAPI(long itemId) throws JSONException {

    final String ITEM_LOOKUP_BASE_URL = "http://us.battle.net/api/wow/item/";
    Uri builtUri = Uri.parse(ITEM_LOOKUP_BASE_URL).buildUpon().appendPath(Long.toString(itemId)).build();
    //Log.v(LOG_TAG, "URI to get Item: " + builtUri.toString());

    return processItemDataFromJson(getHTTPData(builtUri.toString()));
}