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.beesham.popularmovies.sync.MoviesSyncAdapter.java

/**
 * Gets and stores the movie trailer and reviews JSON data
 * @param movieId// ww w  . j  ava2 s . c  o m
 * @param flag
 * @return
 */
private String getTrailersOrReviews(String movieId, int flag) {
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    String movieJsonStr = null;
    String MOVIE_QUERY_URL = null;

    try {
        switch (flag) {
        case 0:
            MOVIE_QUERY_URL = getContext().getString(R.string.movies_base_trailers_url, movieId);
            break;
        case 1:
            MOVIE_QUERY_URL = getContext().getString(R.string.movies_base_reviews_url, movieId);
            break;
        }
        final String API_KEY_PARAM = "api_key";

        Uri builtUri = Uri.parse(MOVIE_QUERY_URL).buildUpon().appendQueryParameter(API_KEY_PARAM, API_KEY)
                .build();

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

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(15000);
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null)
            return null;

        reader = new BufferedReader((new InputStreamReader(inputStream)));
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0)
            return null;

        movieJsonStr = buffer.toString();

    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
        }
    }

    return movieJsonStr;
}

From source file:br.com.anteros.social.instagram.AnterosInstagramSession.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    int sanitizedRequestCode = requestCode & 0xFFFF;
    if (sanitizedRequestCode != REQUEST_AUTH)
        return;/*from w  ww  .  j a  v  a  2 s  .c o m*/

    Uri uri = data != null ? data.getData() : null;

    if (uri != null && uri.toString().startsWith(redirectURL)) {
        String parts[] = uri.toString().split("=");
        String verifier = parts[1];
        RequestLoginAsyncTask requestLogin2AsyncTask = new RequestLoginAsyncTask();
        mRequests.put(REQUEST_LOGIN, requestLogin2AsyncTask);
        Bundle args = new Bundle();
        args.putString(RequestLoginAsyncTask.PARAM_VERIFIER, verifier);
        requestLogin2AsyncTask.execute(args);
    } else {
        onLoginListener.get().onFail(new AnterosInstagramException("Incorrect URI returned " + uri));
    }
}

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

/**
 * ?uri'/'?'/'//from ww w  .  j  a  va 2 s  . c  om
 *
 * @param srcFileUri
 * @return
 */
private Uri handleUri(Uri srcFileUri) {
    String srcFile = srcFileUri.toString();
    if (srcFile.endsWith(File.separator)) {
        srcFileUri = Uri.parse(srcFile.substring(0, srcFile.length() - 1));
    }
    return srcFileUri;
}

From source file:mobisocial.musubi.webapp.WebAppActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.appcorral);//w w w. j ava2  s .  co  m

    mMusubi = App.getMusubi(this);
    getSupportActionBar().hide();

    mAppId = getIntent().getStringExtra(EXTRA_APP_ID);
    if (mAppId == null) {
        toast("Must set app id for socialKitJS binding.");
        finish();
        return;
    }

    mArgumentName = getIntent().getStringExtra(EXTRA_APP_NAME);
    if (mArgumentName == null) {
        mArgumentName = "Application";
    }

    mObjUri = getIntent().getData();
    if (mObjUri != null) {
        mArgumentData = mMusubi.objForUri(mObjUri);
    }

    mFeedUri = (Uri) getIntent().getParcelableExtra(Musubi.EXTRA_FEED_URI);
    if (mFeedUri != null) {
        mArgumentFeed = mMusubi.getFeed(mFeedUri);
    }

    if (savedInstanceState != null) {
        mCurrentPage = savedInstanceState.getString(EXTRA_CURRENT_PAGE);
    } else {
        Uri appUrl = getIntent().getParcelableExtra(EXTRA_APP_URI);
        if (appUrl != null) {
            mCurrentPage = appUrl.toString();
        }
    }

    if (mCurrentPage == null) {
        Log.w(TAG, "No WebApp specified, bailing.");
        finish();
        return;
    }

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    WebAppWebViewClient webapp = new WebAppWebViewClient(this, mWebView, mAppId);
    mWebView.setWebViewClient(webapp);
    mWebView.addJavascriptInterface(webapp.mSocialKitJavascript, SocialKitJavascript.MUSUBI_JS_VAR);
    mWebView.setWebChromeClient(new WebAppWebChromeClient(webapp));

    new DataFromLocalhostTask(webapp).execute();
}

From source file:cs408team3.wikidroid.search.WikiDroidHttpClient.java

public String searchGoogle(String content) {
    String result = null;//from  w w w. j  av  a  2 s  . com
    String query = "";
    Uri q = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/customsearch/v1")
            .appendQueryParameter("key", API_KEY).appendQueryParameter("cx", SEARCH_ENGINE_ID)
            .appendQueryParameter("q", content).appendQueryParameter("cref", "*.wikipedia.org/*")
            .appendQueryParameter("fields", QUERY_FIELDS).build();
    query = q.toString();
    for (int i = 0; i < 2; i++) {
        try {
            result = sendGet(query);
            return result;
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(WikiDroidHttpClient.class.getName()).log(Level.SEVERE, null, ex);
            result = "wrong url";
            return result;
        } catch (ClientProtocolException ex) {
            Logger.getLogger(WikiDroidHttpClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(WikiDroidHttpClient.class.getName()).log(Level.SEVERE, null, ex);
            result = "IOException";
            return result;
        }

    }
    return null;
}

From source file:com.luhuiguo.cordova.voice.VoiceHandler.java

/**
 * Executes the request and returns PluginResult.
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackContext       The callback context used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 *//*from w  w w. j  ava2 s.  c om*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    CordovaResourceApi resourceApi = webView.getResourceApi();
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    if (action.equals("startRecording")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startRecording(args.getString(0), VoiceHandler.stripFileProtocol(fileUriStr));
    } else if (action.equals("stopRecording")) {
        this.stopRecording(args.getString(0));
    } else if (action.equals("startPlaying")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startPlaying(args.getString(0), VoiceHandler.stripFileProtocol(fileUriStr));
    } else if (action.equals("seekTo")) {
        this.seekTo(args.getString(0), args.getInt(1));
    } else if (action.equals("pausePlaying")) {
        this.pausePlaying(args.getString(0));
    } else if (action.equals("stopPlaying")) {
        this.stopPlaying(args.getString(0));
    } else if (action.equals("setVolume")) {
        try {
            this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
        } catch (NumberFormatException nfe) {
            //no-op
        }
    } else if (action.equals("getCurrentPosition")) {
        float f = this.getCurrentPosition(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("getPower")) {
        float f = this.getPower(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("getDuration")) {
        float f = this.getDuration(args.getString(0), args.getString(1));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("create")) {
        String id = args.getString(0);
        String src = VoiceHandler.stripFileProtocol(args.getString(1));
        VoicePlayer voice = new VoicePlayer(this, id, src);
        this.players.put(id, voice);
    } else if (action.equals("release")) {
        boolean b = this.release(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, b));
        return true;
    } else { // Unrecognized action.
        return false;
    }

    callbackContext.sendPluginResult(new PluginResult(status, result));

    return true;
}

From source file:it.readbeyond.minstrel.mediarb.AudioHandler.java

/**
 * Executes the request and returns PluginResult.
 * @param action       The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackContext      The callback context used when calling back into JavaScript.
 * @return             A PluginResult object with a status and message.
 *///ww  w.  j  a  v a2s .c  om
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    CordovaResourceApi resourceApi = webView.getResourceApi();
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    if (action.equals("startPlayingAudio")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));
    } else if (action.equals("seekToAudio")) {
        this.seekToAudio(args.getString(0), args.getInt(1));
    } else if (action.equals("pausePlayingAudio")) {
        this.pausePlayingAudio(args.getString(0));
    } else if (action.equals("stopPlayingAudio")) {
        this.stopPlayingAudio(args.getString(0));
    } else if (action.equals("setPlaybackSpeed")) {
        try {
            this.setPlaybackSpeed(args.getString(0), Float.parseFloat(args.getString(1)));
        } catch (NumberFormatException nfe) {
            //no-op
        }
    } else if (action.equals("setVolume")) {
        try {
            this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
        } catch (NumberFormatException nfe) {
            //no-op
        }
    } else if (action.equals("getCurrentPositionAudio")) {
        float f = this.getCurrentPositionAudio(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("getDurationAudio")) {
        float f = this.getDurationAudio(args.getString(0), args.getString(1));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("create")) {
        String id = args.getString(0);
        String src = FileHelper.stripFileProtocol(args.getString(1));
        this.mMode = args.getString(2);
        getOrCreatePlayer(id, src);
    } else if (action.equals("release")) {
        boolean b = this.release(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, b));
        return true;
    } else if (action.equals("messageChannel")) {
        messageChannel = callbackContext;
        return true;
    } else { // Unrecognized action.
        return false;
    }

    callbackContext.sendPluginResult(new PluginResult(status, result));

    return true;
}

From source file:com.vinnypalumbo.vinnysmovies.FetchTrailersTask.java

@Override
protected List<Trailer> doInBackground(String... params) {
    Log.d("vinny-debug", "FetchTrailersTask - doInBackground");

    // If there's no movieId, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }/*w w w  .  ja  v  a2 s  . c o m*/
    String movieId = 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 trailerJsonStr = null;

    try {
        // Construct the URL for the TheMovieDB query
        // Possible parameters are available at TMDB's movie API page

        //URL url = new URL("http://api.themoviedb.org/3/movie/281957/videos?api_key=XXXX");

        final String TRAILER_BASE_URL = "http://api.themoviedb.org/3/movie";
        final String VIDEO_SEGMENT = "videos";
        final String APIKEY_PARAM = "api_key";

        Uri builtUri = Uri.parse(TRAILER_BASE_URL).buildUpon().appendPath(movieId).appendPath(VIDEO_SEGMENT)
                .appendQueryParameter(APIKEY_PARAM, BuildConfig.THE_MOVIE_DB_API_KEY).build();

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

        // Create the request to TheMovieDB, 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;
        }
        trailerJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the trailer data, there's no point in attempting
        // 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 getTrailerDataFromJson(trailerJsonStr);
    } 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:com.beesham.popularmovies.sync.MoviesSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient,
        SyncResult syncResult) {/*from w w w.  j av  a2  s  . c  o m*/
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    String moviesJsonStr = null;

    try {
        final String MOVIES_BASE_URL = getContext().getString(R.string.movies_base_url);
        final String API_KEY_PARAM = "api_key";

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        String sort_by = prefs.getString(getContext().getString(R.string.pref_sort_key),
                getContext().getString(R.string.pref_sort_default));

        Uri builtUri = Uri.parse(MOVIES_BASE_URL).buildUpon().appendPath(sort_by)
                .appendQueryParameter(API_KEY_PARAM, API_KEY).build();

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

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(15000);
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null)
            return;

        reader = new BufferedReader((new InputStreamReader(inputStream)));
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0)
            return;

        moviesJsonStr = buffer.toString();
        getMovieDataFromJson(moviesJsonStr);

    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } catch (IOException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } 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 (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
        }
    }
}

From source file:com.sudhirkhanger.app.popularmovies.FetchTasks.FetchMoviesTask.java

@Override
protected ArrayList<Movie> 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  ava  2s.co  m

    // 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 movieJsonStr = null;

    try {

        // http://api.themoviedb.org/3/movie/popular?page=1&api_key={API Key}
        // Build an URL like above

        final String MOVIEDB_BASE_URL = "http://api.themoviedb.org/3/movie";
        final String QUERY_PAGE = "page";
        final String QUERY_API_KEY = "api_key";

        Uri builtUri = Uri.parse(MOVIEDB_BASE_URL).buildUpon().appendPath(params[0])
                .appendQueryParameter(QUERY_PAGE, params[1])
                .appendQueryParameter(QUERY_API_KEY, BuildConfig.THE_MOVIE_DB_API_KEY).build();

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

        Log.d(LOG_TAG, url.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;
        }
        movieJsonStr = 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 getMovieDataFromJson(movieJsonStr);
    } 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;
}