Example usage for android.net Uri decode

List of usage examples for android.net Uri decode

Introduction

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

Prototype

public static String decode(String s) 

Source Link

Document

Decodes '%'-escaped octets in the given string using the UTF-8 scheme.

Usage

From source file:com.stfalcon.contentmanager.ContentManager.java

private void processFile(final String queryUri) {
    pickContentListener.onStartContentLoading();

    new Thread(new Runnable() {
        @Override/*from www. j  a v  a2s .c o  m*/
        public void run() {
            String originalPath = null;
            String uri = queryUri;
            if (uri.startsWith("file://") || uri.startsWith("/")) {
                originalPath = sanitizeUri(uri);
            } else if (uri.startsWith("content:")) {
                originalPath = getAbsolutePathIfAvailable(uri);
            }
            uri = originalPath;
            // Still content:: Try ContentProvider stream import
            if (uri.startsWith("content:")) {
                originalPath = getFileFromContentProvider(originalPath);
            }

            // Check for URL Encoded file paths
            try {
                String decodedURL = Uri.parse(Uri.decode(originalPath)).toString();
                if (!decodedURL.equals(originalPath)) {
                    originalPath = decodedURL;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            final String finalOriginalPath = originalPath;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    pickContentListener.onContentLoaded(Uri.parse(finalOriginalPath), savedContent.toString());
                }
            });
        }
    }).start();

}

From source file:com.cerema.cloud2.ui.activity.Uploader.java

public void uploadFiles() {
    try {//from ww w. j  a  va2s.  co m

        // ArrayList for files with path in external storage
        ArrayList<String> local = new ArrayList<String>();
        ArrayList<String> remote = new ArrayList<String>();

        // this checks the mimeType 
        for (Parcelable mStream : mStreamsToUpload) {

            Uri uri = (Uri) mStream;
            String data = null;
            String filePath = "";

            if (uri != null) {
                if (uri.getScheme().equals("content")) {
                    String mimeType = getContentResolver().getType(uri);

                    if (mimeType.contains("image")) {
                        String[] CONTENT_PROJECTION = { Images.Media.DATA, Images.Media.DISPLAY_NAME,
                                Images.Media.MIME_TYPE, Images.Media.SIZE };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Images.Media.DATA);
                        data = c.getString(index);
                        local.add(data);
                        remote.add(mUploadPath + c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME)));

                    } else if (mimeType.contains("video")) {
                        String[] CONTENT_PROJECTION = { Video.Media.DATA, Video.Media.DISPLAY_NAME,
                                Video.Media.MIME_TYPE, Video.Media.SIZE, Video.Media.DATE_MODIFIED };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Video.Media.DATA);
                        data = c.getString(index);
                        local.add(data);
                        remote.add(mUploadPath + c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME)));

                    } else if (mimeType.contains("audio")) {
                        String[] CONTENT_PROJECTION = { Audio.Media.DATA, Audio.Media.DISPLAY_NAME,
                                Audio.Media.MIME_TYPE, Audio.Media.SIZE };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Audio.Media.DATA);
                        data = c.getString(index);
                        local.add(data);
                        remote.add(mUploadPath + c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME)));

                    } else {
                        filePath = Uri.decode(uri.toString()).replace(uri.getScheme() + "://", "");
                        // cut everything whats before mnt. It occured to me that sometimes apps send
                        // their name into the URI
                        if (filePath.contains("mnt")) {
                            String splitedFilePath[] = filePath.split("/mnt");
                            filePath = splitedFilePath[1];
                        }
                        final File file = new File(filePath);
                        local.add(file.getAbsolutePath());
                        remote.add(mUploadPath + file.getName());
                    }
                } else if (uri.getScheme().equals("file")) {
                    filePath = Uri.decode(uri.toString()).replace(uri.getScheme() + "://", "");
                    if (filePath.contains("mnt")) {
                        String splitedFilePath[] = filePath.split("/mnt");
                        filePath = splitedFilePath[1];
                    }
                    final File file = new File(filePath);
                    data = file.getAbsolutePath();
                    filePath = mUploadPath + file.getName();
                } else {
                    throw new SecurityException();
                }
                if (data == null) {
                    mRemoteCacheData.add(filePath);
                    CopyTmpFileAsyncTask copyTask = new CopyTmpFileAsyncTask(this);
                    Object[] params = { uri, filePath, mRemoteCacheData.size() - 1, getAccount().name,
                            getContentResolver() };
                    mNumCacheFile++;
                    showWaitingCopyDialog();
                    copyTask.execute(params);
                }
            } else {
                throw new SecurityException();
            }

            Intent intent = new Intent(getApplicationContext(), FileUploader.class);
            intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
            intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()]));
            intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote.toArray(new String[remote.size()]));
            intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
            startService(intent);

            //Save the path to shared preferences
            SharedPreferences.Editor appPrefs = PreferenceManager
                    .getDefaultSharedPreferences(getApplicationContext()).edit();
            appPrefs.putString("last_upload_path", mUploadPath);
            appPrefs.apply();

            finish();
        }

    } catch (SecurityException e) {
        String message = String.format(getString(R.string.uploader_error_forbidden_content),
                getString(R.string.app_name));
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}

From source file:com.synox.android.ui.activity.Uploader.java

public void uploadFiles() {
    try {/*  w w  w  .j av  a2 s  . c  o m*/

        // ArrayList for files with path in external storage
        ArrayList<String> local = new ArrayList<>();
        ArrayList<String> remote = new ArrayList<>();

        // this checks the mimeType
        for (Parcelable mStream : mStreamsToUpload) {

            Uri uri = (Uri) mStream;
            String data = null;
            String filePath = "";

            if (uri != null) {
                if (uri.getScheme().equals("content")) {
                    String mimeType = getContentResolver().getType(uri);

                    if (mimeType.contains("image")) {
                        String[] CONTENT_PROJECTION = { Images.Media.DATA, Images.Media.DISPLAY_NAME,
                                Images.Media.MIME_TYPE, Images.Media.SIZE };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Images.Media.DATA);
                        data = c.getString(index);
                        filePath = mUploadPath + c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME));

                    } else if (mimeType.contains("video")) {
                        String[] CONTENT_PROJECTION = { Video.Media.DATA, Video.Media.DISPLAY_NAME,
                                Video.Media.MIME_TYPE, Video.Media.SIZE, Video.Media.DATE_MODIFIED };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Video.Media.DATA);
                        data = c.getString(index);
                        filePath = mUploadPath + c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME));

                    } else if (mimeType.contains("audio")) {
                        String[] CONTENT_PROJECTION = { Audio.Media.DATA, Audio.Media.DISPLAY_NAME,
                                Audio.Media.MIME_TYPE, Audio.Media.SIZE };
                        Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
                        c.moveToFirst();
                        int index = c.getColumnIndex(Audio.Media.DATA);
                        data = c.getString(index);
                        filePath = mUploadPath + c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME));

                    } else {
                        Cursor cursor = getContentResolver().query(uri,
                                new String[] { MediaStore.MediaColumns.DISPLAY_NAME }, null, null, null);
                        cursor.moveToFirst();
                        int nameIndex = cursor.getColumnIndex(cursor.getColumnNames()[0]);
                        if (nameIndex >= 0) {
                            filePath = mUploadPath + cursor.getString(nameIndex);
                        }
                    }

                } else if (uri.getScheme().equals("file")) {
                    filePath = Uri.decode(uri.toString()).replace(uri.getScheme() + "://", "");
                    if (filePath.contains("mnt")) {
                        String splitedFilePath[] = filePath.split("/mnt");
                        filePath = splitedFilePath[1];
                    }
                    final File file = new File(filePath);
                    data = file.getAbsolutePath();
                    filePath = mUploadPath + file.getName();
                } else {
                    throw new SecurityException();
                }
                if (data == null) {
                    mRemoteCacheData.add(filePath);
                    CopyTmpFileAsyncTask copyTask = new CopyTmpFileAsyncTask(this);
                    Object[] params = { uri, filePath, mRemoteCacheData.size() - 1, getAccount().name,
                            getContentResolver() };
                    mNumCacheFile++;
                    showWaitingCopyDialog();
                    copyTask.execute(params);
                } else {
                    remote.add(filePath);
                    local.add(data);
                }
            } else {
                throw new SecurityException();
            }

            Intent intent = new Intent(getApplicationContext(), FileUploader.class);
            intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
            intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()]));
            intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote.toArray(new String[remote.size()]));
            intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
            startService(intent);

            //Save the path to shared preferences
            SharedPreferences.Editor appPrefs = PreferenceManager
                    .getDefaultSharedPreferences(getApplicationContext()).edit();
            appPrefs.putString("last_upload_path", mUploadPath);
            appPrefs.apply();

            finish();
        }

    } catch (SecurityException e) {
        String message = String.format(getString(R.string.uploader_error_forbidden_content),
                getString(R.string.app_name));
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    } catch (NullPointerException npe) {
        Log_OC.e(this.getClass().getName(), "Unknown error occurred. Message: " + npe.getLocalizedMessage());
    }
}

From source file:gc.david.dfm.ui.MainActivity.java

/**
 * Handles a send intent with position data.
 *
 * @param intent Input intent with position data.
 */// w  w w.  j a  va2s .  com
private void handleViewPositionIntent(final Intent intent) throws Exception {
    Mint.leaveBreadcrumb("MainActivity::handleViewPositionIntent");
    final Uri uri = intent.getData();
    Mint.addExtraData("queryParameter", uri.toString());

    final String uriScheme = uri.getScheme();
    if (uriScheme.equals("geo")) {
        final String schemeSpecificPart = uri.getSchemeSpecificPart();
        final Matcher matcher = getMatcherForUri(schemeSpecificPart);
        if (matcher.find()) {
            if (matcher.group(1).equals("0") && matcher.group(2).equals("0")) {
                if (matcher.find()) { // Manage geo:0,0?q=lat,lng(label)
                    setDestinationPosition(matcher);
                } else { // Manage geo:0,0?q=my+street+address
                    String destination = Uri.decode(uri.getQuery()).replace('+', ' ');
                    destination = destination.replace("q=", "");

                    // TODO check this ugly workaround
                    new SearchPositionByName().execute(destination);
                    mustShowPositionWhenComingFromOutside = true;
                }
            } else { // Manage geo:latitude,longitude or geo:latitude,longitude?z=zoom
                setDestinationPosition(matcher);
            }
        } else {
            final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                    "Error al obtener las coordenadas. Matcher = " + matcher.toString());
            Mint.logException(noSuchFieldException);
            throw noSuchFieldException;
        }
    } else if ((uriScheme.equals("http") || uriScheme.equals("https"))
            && (uri.getHost().equals("maps.google.com"))) { // Manage maps.google.com?q=latitude,longitude

        final String queryParameter = uri.getQueryParameter("q");
        if (queryParameter != null) {
            final Matcher matcher = getMatcherForUri(queryParameter);
            if (matcher.find()) {
                setDestinationPosition(matcher);
            } else {
                final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                        "Error al obtener las coordenadas. Matcher = " + matcher.toString());
                Mint.logException(noSuchFieldException);
                throw noSuchFieldException;
            }
        } else {
            final NoSuchFieldException noSuchFieldException = new NoSuchFieldException(
                    "Query sin parmetro q.");
            Mint.logException(noSuchFieldException);
            throw noSuchFieldException;
        }
    } else {
        final Exception exception = new Exception("Imposible tratar la query " + uri.toString());
        Mint.logException(exception);
        throw exception;
    }
}

From source file:com.jtechme.apphub.views.ManageReposActivity.java

private void checkIfNewRepoOnSameWifi(NewRepoConfig newRepo) {
    // if this is a local repo, check we're on the same wifi
    if (!TextUtils.isEmpty(newRepo.getBssid())) {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String bssid = wifiInfo.getBSSID();
        if (TextUtils.isEmpty(bssid)) /* not all devices have wifi */
            return;
        bssid = bssid.toLowerCase(Locale.ENGLISH);
        String newRepoBssid = Uri.decode(newRepo.getBssid()).toLowerCase(Locale.ENGLISH);
        if (!bssid.equals(newRepoBssid)) {
            String msg = String.format(getString(R.string.not_on_same_wifi), newRepo.getSsid());
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }/*from  w  w  w . j  a v a  2  s . co  m*/
        // TODO we should help the user to the right thing here,
        // instead of just showing a message!
    }
}

From source file:org.fdroid.fdroid.views.ManageReposActivity.java

private void checkIfNewRepoOnSameWifi(NewRepoConfig newRepo) {
    // if this is a local repo, check we're on the same wifi
    if (!TextUtils.isEmpty(newRepo.getBssid())) {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String bssid = wifiInfo.getBSSID();
        if (TextUtils.isEmpty(bssid)) { /* not all devices have wifi */
            return;
        }/*from w w  w .  ja va2 s .c o m*/
        bssid = bssid.toLowerCase(Locale.ENGLISH);
        String newRepoBssid = Uri.decode(newRepo.getBssid()).toLowerCase(Locale.ENGLISH);
        if (!bssid.equals(newRepoBssid)) {
            String msg = String.format(getString(R.string.not_on_same_wifi), newRepo.getSsid());
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
        // TODO we should help the user to the right thing here,
        // instead of just showing a message!
    }
}

From source file:com.if3games.chessonline.DroidFish.java

/**
 * Return PGN/FEN data or filename from the Intent. Both can not be non-null.
 * @return Pair of PGN/FEN data and filename.
 *///  www. ja va2  s  .c  om
private final Pair<String, String> getPgnOrFenIntent() {
    String pgnOrFen = null;
    String filename = null;
    try {
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data == null) {
            Bundle b = intent.getExtras();
            if (b != null) {
                Object strm = b.get(Intent.EXTRA_STREAM);
                if (strm instanceof Uri) {
                    data = (Uri) strm;
                    if ("file".equals(data.getScheme())) {
                        filename = data.getEncodedPath();
                        if (filename != null)
                            filename = Uri.decode(filename);
                    }
                }
            }
        }
        if (data == null) {
            if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction()))
                    && ("application/x-chess-pgn".equals(intent.getType())
                            || "application/x-chess-fen".equals(intent.getType())))
                pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT);
        } else {
            String scheme = intent.getScheme();
            if ("file".equals(scheme)) {
                filename = data.getEncodedPath();
                if (filename != null)
                    filename = Uri.decode(filename);
            }
            if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) {
                ContentResolver resolver = getContentResolver();
                InputStream in = resolver.openInputStream(intent.getData());
                StringBuilder sb = new StringBuilder();
                while (true) {
                    byte[] buffer = new byte[16384];
                    int len = in.read(buffer);
                    if (len <= 0)
                        break;
                    sb.append(new String(buffer, 0, len));
                }
                pgnOrFen = sb.toString();
            }
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show();
    }
    return new Pair<String, String>(pgnOrFen, filename);
}

From source file:org.mozilla.gecko.GeckoAppShell.java

static boolean openUriExternal(String aUriSpec, String aMimeType, String aPackageName, String aClassName,
        String aAction, String aTitle) {
    Intent intent = getIntentForActionString(aAction);
    if (aAction.equalsIgnoreCase(Intent.ACTION_SEND)) {
        Intent shareIntent = getIntentForActionString(aAction);
        shareIntent.putExtra(Intent.EXTRA_TEXT, aUriSpec);
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, aTitle);
        if (aMimeType != null && aMimeType.length() > 0)
            shareIntent.setType(aMimeType);
        intent = Intent.createChooser(shareIntent,
                GeckoApp.mAppContext.getResources().getString(R.string.share_title));
    } else if (aMimeType.length() > 0) {
        intent.setDataAndType(Uri.parse(aUriSpec), aMimeType);
    } else {//w w  w . ja v a2  s .c om
        Uri uri = Uri.parse(aUriSpec);
        if ("sms".equals(uri.getScheme())) {
            // Have a apecial handling for the SMS, as the message body
            // is not extracted from the URI automatically
            final String query = uri.getEncodedQuery();
            if (query != null && query.length() > 0) {
                final String[] fields = query.split("&");
                boolean foundBody = false;
                String resultQuery = "";
                for (int i = 0; i < fields.length; i++) {
                    final String field = fields[i];
                    if (field.length() > 5 && "body=".equals(field.substring(0, 5))) {
                        final String body = Uri.decode(field.substring(5));
                        intent.putExtra("sms_body", body);
                        foundBody = true;
                    } else {
                        resultQuery = resultQuery.concat(resultQuery.length() > 0 ? "&" + field : field);
                    }
                }
                if (foundBody) {
                    // Put the query without the body field back into the URI
                    final String prefix = aUriSpec.substring(0, aUriSpec.indexOf('?'));
                    uri = Uri.parse(resultQuery.length() > 0 ? prefix + "?" + resultQuery : prefix);
                }
            }
        }
        intent.setData(uri);
    }
    if (aPackageName.length() > 0 && aClassName.length() > 0)
        intent.setClassName(aPackageName, aClassName);

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    try {
        GeckoApp.mAppContext.startActivity(intent);
        return true;
    } catch (ActivityNotFoundException e) {
        return false;
    }
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

private boolean webServiceImageUrl() {

    try {/* ww w . j  a va2s. co m*/
        Log.d("webServiceUserInfo", "called");
        HttpParams p = new BasicHttpParams();
        p.setParameter("user", "1");
        HttpClient httpclient = new DefaultHttpClient(p);
        String url = "http://ip.roaming4world.com/esstel/profile-data/profile_pic_download.php?self_contact="
                + prefs.getString(stored_user_country_code, "NoValue")
                + prefs.getString(stored_user_mobile_no, "NoValue")
                //           +"918860357393"
                + "&type=thumb";

        Log.d("url", url + " #");
        ResponseHandler<String> responseHandler;
        String responseBody;
        responseHandler = new BasicResponseHandler();

        HttpPost httppost = new HttpPost(url);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("user", "1"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        responseBody = httpclient.execute(httppost, responseHandler);

        JSONObject json = new JSONObject(responseBody);
        JSONArray response = json.getJSONArray("contacts");
        String path = json.getString("path");
        Log.d("pathtst", path + " #");
        Log.d("response", response + " #");
        phone_no = new String[response.length()];
        url_image = new String[response.length()];
        name = new String[response.length()];
        status = new String[response.length()];
        for (int i = 0; i < response.length(); i++) {
            JSONObject position = response.getJSONObject(i);
            Log.d("position", position + " #");
            phone_no[i] = position.getString("p");

            String url_update = position.getString("t");

            if (!url_update.equals("No image")) {
                url_image[i] = path + url_update;
            } else {
                url_image[i] = position.getString("t");
            }

            name[i] = position.getString("un");
            name[i] = Uri.decode(name[i]);
            status[i] = Uri.decode(position.getString("s"));

            username = position.getString("un");
            number = position.getString("p");
            user_status = position.getString("s");
            user_urlpath = url_image[i];

            Log.d(i + " phone_no  ", phone_no[i] + "   !");
            Log.d(i + " name ", name[i] + "   !");
            Log.d(i + " status ", status[i] + "   !");
            Log.d(i + " url", url_image[i] + "   !");

            dbContacts = new DBContacts(mcontext);

            dbContacts.openToWrite();

            String check = dbContacts.insert_or_update_R4Wcontact_detail_in_db(number, username, user_status,
                    user_urlpath);

            if (check.equals("update")) {
                updated_number.add(number);
                updated_url.add(user_urlpath);
            }

            //dbContacts.insert_R4Wcontact_detail_in_db(phone_no[i], name[i], status[i], url_image[i]);
        }

        dbContacts.close();
        return true;
    } catch (Exception t) {

        t.printStackTrace();

        return false;
    }

}

From source file:com.android.mail.browse.ConversationCursor.java

private static String uriStringFromCachingUri(Uri uri) {
    Uri underlyingUri = uriFromCachingUri(uri);
    // Remember to decode the underlying Uri as it might be encoded (as w/ Gmail)
    return Uri.decode(underlyingUri.toString());
}