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.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

@SuppressLint("NewApi")
protected String getAbsoluteImagePathFromUri(Uri imageUri) {
    String[] proj = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };

    if (BuildConfig.DEBUG) {
        Log.i(TAG, "Image Uri: " + imageUri.toString());
    }//from   ww  w.  j  a  v  a2 s .c o m

    if (imageUri.toString().startsWith("content://com.android.gallery3d.provider")) {
        imageUri = Uri
                .parse(imageUri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
    }

    String filePath = "";
    String imageUriString = imageUri.toString();
    if (imageUriString.startsWith("content://com.google.android.gallery3d")
            || imageUriString.startsWith("content://com.google.android.apps.photos.content")
            || imageUriString.startsWith("content://com.android.providers.media.documents")
            || imageUriString.startsWith("content://com.google.android.apps.docs.storage")
            || imageUriString.startsWith("content://com.microsoft.skydrive.content.external")) {
        filePath = imageUri.toString();
    } else {
        Cursor cursor = context.getContentResolver().query(imageUri, proj, null, null, null);
        cursor.moveToFirst();
        filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.DATA));
        cursor.close();
    }

    if (filePath == null && isDownloadsDocument(imageUri)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            filePath = getPath(context, imageUri);
    }
    return filePath;
}

From source file:com.code.android.vibevault.ShowDetailsScreen.java

/** Create the activity, taking into account ongoing dialogs or already downloaded data.
*
* If there is a retained ParseShowDetailsPageTask, set its parent
* activity to the newly created ShowDetailsScreen (the old one was
* destroyed because of an orientation change or something.  This
* way, the ParseShowDetailsPageTask does not leak any of the Views
* from the old ShowDetailsScreen.  Also, grab the songs from the
* ParseShowDetailsPageTask to refresh the list of songs with.
*//*from   w  w w . ja  va2s. c  om*/
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.show_details_screen);
    Intent intent = getIntent();
    Bundle b = intent.getExtras();
    if (b != null) {
        show = (ArchiveShowObj) b.get("Show");
    }
    if (show == null) {
        if (intent.getScheme().equals("http")) {
            Uri link = intent.getData();
            String linkString = link.toString();
            if (linkString.contains("/download/")) {
                String[] paths = linkString.split("/");
                for (int i = 0; i < paths.length; i++) {
                    if (paths[i].equals("download")) {
                        show = new ArchiveShowObj(Uri.parse("http://www.archive.org/details/" + paths[i + 1]),
                                true);
                        show.setSelectedSong(linkString);
                    }
                }
            } else {
                show = new ArchiveShowObj(link, false);
            }
        }
    }

    //      
    //      

    showTitle = show.getArtistAndTitle();
    showLabel = (TextView) findViewById(R.id.ShowLabel);
    showLabel.setText(showTitle);

    trackList = (ListView) findViewById(R.id.SongsListView);
    trackList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {

            playShow(position);
            Intent i = new Intent(ShowDetailsScreen.this, NowPlayingScreen.class);
            startActivity(i);
        }
    });
    trackList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.add(Menu.NONE, VibeVault.ADD_SONG_TO_QUEUE, Menu.NONE, "Add to playlist");
            menu.add(Menu.NONE, VibeVault.DOWNLOAD_SONG, Menu.NONE, "Download Song");
            menu.add(Menu.NONE, VibeVault.EMAIL_LINK, Menu.NONE, "Email Link to Song");
        }
    });

    downloadLinks = new ArrayList<ArchiveSongObj>();
    Object retained = getLastNonConfigurationInstance();
    if (retained instanceof ParseShowDetailsPageTask) {
        workerTask = (ParseShowDetailsPageTask) retained;
        workerTask.setActivity(this);
        downloadLinks = workerTask.songs;
    } else if (show.getShowURL() != null) {

        workerTask = new ParseShowDetailsPageTask(this);
        workerTask.execute(show);
    }
}

From source file:com.example.avs.sunshine.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;
    }//from w w  w .  j  av  a  2  s .co  m
    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(forecastJsonStr, locationQuery);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
    } 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);
            }
        }
    }

    //        // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:com.luxtech_eg.sunshine.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 ww.  j  ava2 s .c  o  m
    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";
        final String APPID_PARAM = "APPID";

        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))
                .appendQueryParameter(APPID_PARAM, appid).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(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:br.com.dgimenes.sunshine.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;
    }//from   ww w  . j  av a2  s  . co m
    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";
        final String APIKEY_PARAM = "APPID";

        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))
                .appendQueryParameter(APIKEY_PARAM, APP_ID).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(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 attemping
        // to parse it.
        return null;
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Error ", 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.acrutiapps.browser.tasks.HistoryBookmarksImportTask.java

private String readAsJSON(File file) {
    List<ContentValues> insertValues = null;

    try {//from w  w  w . ja v a2 s.  c o m
        insertValues = new ArrayList<ContentValues>();

        publishProgress(1, 0, 0);

        FileInputStream fis = new FileInputStream(file);

        StringBuilder sb = new StringBuilder();
        String line;

        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
                return e.getMessage();
            }
        }

        JSONObject data = new JSONObject(sb.toString());

        Map<Long, Folder> folders = new HashMap<Long, Folder>();

        if (data.has("folders")) {
            JSONArray foldersArray = data.getJSONArray("folders");

            int progress = 0;
            int total = foldersArray.length();

            for (int i = 0; i < foldersArray.length(); i++) {

                publishProgress(3, progress, total);

                JSONObject folder = foldersArray.getJSONObject(i);

                long id = folder.getLong("id");
                long parentId = folder.getLong("parentId");
                String title = URLDecoder.decode(folder.getString("title"), "UTF-8");

                ContentValues values = new ContentValues();
                values.put(BookmarksProvider.Columns.TITLE, title);
                values.put(BookmarksProvider.Columns.BOOKMARK, 0);
                values.put(BookmarksProvider.Columns.IS_FOLDER, 1);
                values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, -1);

                Uri insertionUri = mContext.getContentResolver().insert(BookmarksProvider.BOOKMARKS_URI,
                        values);
                String insertionString = insertionUri.toString();

                // Get the new id for the current folder.
                long insertionId = -1;
                try {
                    insertionId = Long
                            .parseLong(insertionString.substring(insertionString.lastIndexOf('/') + 1));
                } catch (NumberFormatException e) {
                    insertionId = -1;
                }

                // Keep a relation between the id of the folder in the export file, its parent id (in the export file), and its new id.
                folders.put(id, new Folder(insertionId, parentId));

                progress++;
            }

            publishProgress(4, 0, 0);

            // Correct folders parent ids.
            if (!folders.isEmpty()) {
                for (Folder folder : folders.values()) {
                    // For each folder previously inserted, check if it had a parent folder in the export file.
                    long oldParentId = folder.getOldParentId();

                    if (oldParentId != -1) {
                        // Get the parent folder by its old Id, key of folders map.
                        Folder parentFolder = folders.get(oldParentId);
                        if (parentFolder != null) {

                            ContentValues values = new ContentValues();
                            values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId());

                            String whereClause = BookmarksProvider.Columns._ID + " = " + folder.getNewId();

                            mContext.getContentResolver().update(BookmarksProvider.BOOKMARKS_URI, values,
                                    whereClause, null);
                        }
                    }
                }
            }
        }

        if (data.has("bookmarks")) {
            JSONArray bookmarksArray = data.getJSONArray("bookmarks");

            int progress = 0;
            int total = bookmarksArray.length();

            for (int i = 0; i < bookmarksArray.length(); i++) {

                publishProgress(5, progress, total);

                JSONObject bookmark = bookmarksArray.getJSONObject(i);

                long folderId = bookmark.getLong("folderId");
                Folder parentFolder = null;
                if (folderId != -1) {
                    parentFolder = folders.get(folderId);
                }

                String title = URLDecoder.decode(bookmark.getString("title"), "UTF-8");
                String url = URLDecoder.decode(bookmark.getString("url"), "UTF-8");

                ContentValues values = createContentValues(title, url, bookmark.getInt("visits"),
                        bookmark.getLong("visitedDate"), bookmark.getLong("creationDate"), 1);

                if (parentFolder != null) {
                    values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId());
                }

                insertValues.add(values);

                progress++;
            }
        }

        if (data.has("history")) {
            JSONArray historyArray = data.getJSONArray("history");

            int progress = 0;
            int total = historyArray.length();

            for (int i = 0; i < historyArray.length(); i++) {

                publishProgress(6, progress, total);

                JSONObject history = historyArray.getJSONObject(i);

                String title = URLDecoder.decode(history.getString("title"), "UTF-8");
                String url = URLDecoder.decode(history.getString("url"), "UTF-8");

                ContentValues values = createContentValues(title, url, history.getInt("visits"),
                        history.getLong("visitedDate"), 0, 0);

                insertValues.add(values);

                progress++;
            }
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (JSONException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return e.getMessage();
    }

    if (insertValues != null) {
        publishProgress(7, 0, 0);
        mContext.getContentResolver().bulkInsert(BookmarksProvider.BOOKMARKS_URI,
                insertValues.toArray(new ContentValues[insertValues.size()]));
    }

    return null;
}

From source file:de.appplant.cordova.plugin.notification.Asset.java

/**
 * Parse given PathStrings to Uris//from   w w  w  .j a v  a 2  s . c om
 * @param notification Notifications JSONObject
 * @return   new Notification JSONObject with additional iconUri and soundUri
 */
public JSONObject parseURIs(JSONObject notification) {
    //sound
    String sound = notification.optString("sound", null);
    Uri soundUri = null;
    if (sound != null) {
        try {
            int soundId = (Integer) RingtoneManager.class.getDeclaredField(sound).get(Integer.class);

            soundUri = RingtoneManager.getDefaultUri(soundId);
        } catch (Exception e) {
            soundUri = getURIfromPath(sound);
        }
    }
    if (soundUri != null && soundUri != Uri.EMPTY) {
        try {
            notification.put("soundUri", soundUri.toString());
        } catch (JSONException jse) {
            jse.printStackTrace();
        }
    }
    //image
    String icon = notification.optString("icon", "icon");
    Uri iconUri = null;
    iconUri = getURIfromPath(icon);
    if (iconUri != Uri.EMPTY && iconUri != null) {
        try {
            notification.put("iconUri", iconUri.toString());
        } catch (JSONException jse) {
            jse.printStackTrace();
        }
    }
    return notification;
}

From source file:app.com.example.wungmathing.sunshine.FetchWeatherTask.java

@Override
protected String[] 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;
    }//from   w  ww  .jav  a 2 s  .c o  m
    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();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.
        return null;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try {
        return getWeatherDataFromJson(forecastJsonStr, locationQuery);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

From source file:it.feio.android.omninotes.SettingsFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case SPRINGPAD_IMPORT:
            Uri filesUri = intent.getData();
            String path = FileHelper.getPath(getActivity(), filesUri);
            // An IntentService will be launched to accomplish the import task
            Intent service = new Intent(getActivity(), DataBackupIntentService.class);
            service.setAction(DataBackupIntentService.ACTION_DATA_IMPORT_SPRINGPAD);
            service.putExtra(DataBackupIntentService.EXTRA_SPRINGPAD_BACKUP, path);
            getActivity().startService(service);
            break;

        case RINGTONE_REQUEST_CODE:
            Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            String notificationSound = uri == null ? null : uri.toString();
            prefs.edit().putString("settings_notification_ringtone", notificationSound).apply();
            break;
        }/*from  ww  w. j a  v a  2 s. com*/
    }
}

From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java

/**
 * Get a {@link InputStream} from {@link Uri}.
 * /*from  w  w  w  . j a va2  s.  co m*/
 * @param cr
 *            {@link ContentResolver}
 * @param uri
 *            {@link Uri}
 * @return {@link InputStream}
 */
private InputStream getStream(final ContentResolver cr, final Uri uri) {
    if (uri.toString().startsWith("import")) {
        String url;
        if (uri.getScheme().equals("imports")) {
            url = "https:/";
        } else {
            url = "http:/";
        }
        url += uri.getPath();
        final HttpGet request = new HttpGet(url);
        Log.d(TAG, "url: " + url);
        try {
            final HttpResponse response = new DefaultHttpClient().execute(request);
            int resp = response.getStatusLine().getStatusCode();
            if (resp != HttpStatus.SC_OK) {
                return null;
            }
            return response.getEntity().getContent();
        } catch (IOException e) {
            Log.e(TAG, "error in reading export: " + url, e);
            return null;
        }
    } else if (uri.toString().startsWith("content://") || uri.toString().startsWith("file://")) {
        try {
            return cr.openInputStream(uri);
        } catch (IOException e) {
            Log.e(TAG, "error in reading export: " + uri.toString(), e);
            return null;
        }
    }
    Log.d(TAG, "getStream() returns null, " + uri.toString());
    return null;
}