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:edu.stanford.mobisocial.dungbeetle.feed.objects.VideoObj.java

public static DbObject from(Context context, Uri videoUri) throws IOException {
    // Query gallery for camera picture via
    // Android ContentResolver interface
    ContentResolver cr = context.getContentResolver();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;/*from   w  ww  .  j ava  2s .c  o m*/
    long videoId = Long.parseLong(videoUri.getLastPathSegment());
    Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId,
            MediaStore.Video.Thumbnails.MINI_KIND, options);
    int targetSize = 200;
    int width = curThumb.getWidth();
    int height = curThumb.getHeight();
    int cropSize = Math.min(width, height);
    float scaleSize = ((float) targetSize) / cropSize;
    Matrix matrix = new Matrix();
    matrix.postScale(scaleSize, scaleSize);
    curThumb = Bitmap.createBitmap(curThumb, 0, 0, width, height, matrix, true);
    JSONObject base = new JSONObject();
    String localIp = ContentCorral.getLocalIpAddress();
    if (localIp != null) {
        try {
            // TODO: Security breach hack?
            base.put(Contact.ATTR_LAN_IP, localIp);
            base.put(LOCAL_URI, videoUri.toString());
            base.put(MIME_TYPE, cr.getType(videoUri));
        } catch (JSONException e) {
            Log.e(TAG, "impossible json error possible!");
        }
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    curThumb.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte[] data = baos.toByteArray();
    return from(base, data);
}

From source file:com.krayzk9s.imgurholo.services.UploadService.java

@Override
protected void onHandleIntent(Intent intent) {
    ids = new ArrayList<String>();
    if (intent.hasExtra("images")) {
        Log.d("recieving", "handling multiple");
        ArrayList<Parcelable> list = intent.getParcelableArrayListExtra("images");
        totalUpload = list.size();//from  w  w  w  . ja  v a 2  s . com
        for (Parcelable parcel : list) {
            Uri uri = (Uri) parcel;
            Log.d("recieving", uri.toString());
            SendImage sendImage = new SendImage(apiCall, FileUtils.getPath(this, uri), getApplicationContext(),
                    getResources(), this);
            Log.d("recieving", "executing");
            sendImage.execute();
        }
    } else {
        totalUpload = -1;
        SendImage sendImage = new SendImage(apiCall,
                FileUtils.getPath(getApplicationContext(), intent.getData()), getApplicationContext(),
                getResources(), this);
        sendImage.execute();
    }
}

From source file:org.blanco.techmun.android.cproviders.TechMunContentProvider.java

/**
 * Returns a Cursor with the Eventos object based on the passed
 * content Uri/* w w w  .j  av  a  2s .co  m*/
 * @param uri The content Uri uri where to extract the info to match the Eventos
 * 
 * @return Cursor with the information 
 */
private Cursor getEventosCursorForUri(Uri uri) {
    if (uri == null) {
        return null;
    }

    Cursor result = null;
    //get The mesa id
    try {
        String mesaId = extractGroupFromPattern(MESA_CONTENT_EVENTOS_PETITION_REG_EXP, uri.toString(), 1);
        Eventos eventos = eventosFeher.fetchEventos(Long.parseLong(mesaId));
        //Build the cursor
        ObjectsCursor cursor = new ObjectsCursor(eventos.getEventos());
        result = cursor;
    } catch (IllegalStateException ex) {
        Log.i("Techmun CP", "Unable to fectch eventos from URI" + uri, ex);
    }
    return result;
}

From source file:org.quizpoll.net.AppEngineHelper.java

/**
 * Makes login request to AppEngine server
 *///from   w  ww  . ja v  a2s . co  m
protected HttpUriRequest createLoginRequest(String baseUrl) {
    Uri url = Uri.parse(baseUrl).buildUpon().appendEncodedPath("_ah/login")
            .appendQueryParameter("auth", (String) requestData).build();
    return new HttpGet(url.toString());
}

From source file:com.robertszkutak.androidexamples.imgurexample.ImgurExampleActivity.java

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

    if (auth == false) {
        if (browser == true)
            browser2 = true;// w w  w.j  a v a2s .c o  m

        if (browser == false) {
            browser = true;
            newIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(authURL));
            startActivity(newIntent);
        }

        if (browser2 == true) {
            Uri uri = getIntent().getData();
            uripath = uri.toString();

            if (uri != null && uripath.startsWith(OAUTH_CALLBACK_URL)) {
                String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
                try {

                    provider.retrieveAccessToken(consumer, verifier);

                    token = consumer.getToken();
                    secret = consumer.getTokenSecret();

                    final Editor editor = pref.edit();
                    editor.putString("IMGUR_OAUTH_TOKEN", token);
                    editor.putString("IMGUR_OAUTH_TOKEN_SECRET", secret);
                    editor.commit();

                    auth = true;
                    loggedin = true;

                } catch (OAuthMessageSignerException e) {
                    e.printStackTrace();
                } catch (OAuthNotAuthorizedException e) {
                    e.printStackTrace();
                } catch (OAuthExpectationFailedException e) {
                    e.printStackTrace();
                } catch (OAuthCommunicationException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    if (auth == true) {
        setContentView(R.layout.main);

        path = (EditText) findViewById(R.id.imagepath);
        debugStatus = (TextView) findViewById(R.id.debug_status);
        upload = (Button) findViewById(R.id.upload);
        loginorout = (Button) findViewById(R.id.loginout);

        debug = "Access Token: " + token + "\n\nAccess Token Secret: " + secret;
        debugStatus.setText(debug);

        upload.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (isAuthenticated()) {
                    uploadImage();
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), "You are not logged into Imgur",
                            Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });

        loginorout.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                LogInOrOut();
            }
        });

        updateLoginStatus();
    }

    if (auth == false && browser2 == true)
        finish();
}

From source file:com.ofalvai.bpinfo.api.bkkfutar.FutarApiClient.java

@Override
public void fetchAlertList(@NonNull AlertRequestParams params) {
    // If a request is in progress, we don't proceed. The response callback will notify every subscriber
    if (mRequestInProgress)
        return;//w  w  w .j  a  v  a  2s  .c om

    mLanguageCode = params.mLanguageCode;

    Uri uri = buildUri();

    LOGI(TAG, "API request: " + uri.toString());

    JsonObjectRequest request = new JsonObjectRequest(uri.toString(), null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        mRoutes = parseRoutes(response);
                        mAlertsToday = parseAlerts(response, AlertListType.ALERTS_TODAY);
                        mAlertsFuture = parseAlerts(response, AlertListType.ALERTS_FUTURE);
                        EventBus.getDefault().post(new AlertListMessage(mAlertsToday, mAlertsFuture));
                    } catch (Exception ex) {
                        EventBus.getDefault().post(new AlertListErrorMessage(ex));
                    } finally {
                        mRequestInProgress = false;
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    EventBus.getDefault().post(new AlertListErrorMessage(error));
                }
            });

    mRequestInProgress = true;
    mRequestQueue.add(request);
}

From source file:com.android.dialer.lookup.yellowpages.YellowPagesReverseLookup.java

/**
 * Lookup image/*w  ww .  j av  a2s  . co m*/
 *
 * @param context The application context
 * @param uri The image URI
 */
public Bitmap lookupImage(Context context, Uri uri) {
    if (uri == null) {
        throw new NullPointerException("URI is null");
    }

    Log.e(TAG, "Fetching " + uri);

    String scheme = uri.getScheme();

    if (scheme.startsWith("http")) {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri.toString());

        try {
            HttpResponse response = client.execute(request);

            int responseCode = response.getStatusLine().getStatusCode();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            byte[] responseBytes = out.toByteArray();

            if (responseCode == HttpStatus.SC_OK) {
                Bitmap bmp = BitmapFactory.decodeByteArray(responseBytes, 0, responseBytes.length);
                return bmp;
            }
        } catch (IOException e) {
            Log.e(TAG, "Failed to retrieve image", e);
        }
    } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
        try {
            ContentResolver cr = context.getContentResolver();
            Bitmap bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
            return bmp;
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Failed to retrieve image", e);
        }
    }

    return null;
}

From source file:it.readbeyond.minstrel.media.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.
 *///from www .  j a  v a2  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("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("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));
        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.eyekabob.ArtistInfo.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.artist_info);
    artist = (Artist) getIntent().getExtras().get("artist");
    Log.d(getClass().getName(), "Artist name is: " + artist.getName());
    findViewById(R.id.findLiveMusicButton).setOnClickListener(onClickListener);
    findViewById(R.id.aboutButton).setOnClickListener(onClickListener);
    findViewById(R.id.contactButton).setOnClickListener(onClickListener);
    findViewById(R.id.infoBioToggleButton).setOnClickListener(onClickListener);

    Map<String, String> params = new HashMap<String, String>();
    if (artist.getMbid() == null) {
        params.put("artist", artist.getName());
    } else {//from   w w  w . j  a va 2s. co  m
        params.put("mbid", artist.getMbid());
    }
    Uri artistInfoUri = EyekabobHelper.LastFM.getUri("artist.getInfo", params);

    // Send the request for artist info.
    new ArtistRequestTask().execute(artistInfoUri.toString());

    // Send last.fm request.
    Map<String, String> lastFMParams = new HashMap<String, String>();
    lastFMParams.put("artist", artist.getName());
    lastFMParams.put("limit", "10");
    Uri lastFMUri = EyekabobHelper.LastFM.getUri("artist.getEvents", lastFMParams);
    new FutureEventsRequestTask().execute(lastFMUri.toString());
}

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

@Override
protected List<Review> doInBackground(String... params) {
    Log.d("vinny-debug", "FetchReviewsTask - 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.j  av  a2s.co  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 reviewJsonStr = 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/reviews?api_key=XXXX");

        final String REVIEW_BASE_URL = "http://api.themoviedb.org/3/movie";
        final String REVIEW_SEGMENT = "reviews";
        final String APIKEY_PARAM = "api_key";

        Uri builtUri = Uri.parse(REVIEW_BASE_URL).buildUpon().appendPath(movieId).appendPath(REVIEW_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;
        }
        reviewJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error ", e);
        // If the code didn't successfully get the review 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 getReviewDataFromJson(reviewJsonStr);
    } 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;
}