Example usage for android.net Uri encode

List of usage examples for android.net Uri encode

Introduction

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

Prototype

public static String encode(String s) 

Source Link

Document

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme.

Usage

From source file:Main.java

/**
 * Finding contact name by telephone number.
 *
 * @param context Context/*from www .  ja  va2  s. c  o  m*/
 * @param number  Telephone number
 * @return Contact display name
 */
public static String getContactName(Context context, String number) {
    Log.d(TAG, "Searching contact with number: " + number);

    /* define the columns I want the query to return */
    String[] projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };

    /* encode the phone number and build the filter URI */
    Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

    /* query time */
    Log.d(TAG, "Sending query");
    Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);

    String name = null;
    if (cursor.moveToFirst()) {
        /* Get values from contacts database: */
        name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
        Log.d(TAG, "Contact found for number: " + number + ". The name is: " + name);
    } else {
        Log.d(TAG, "Contact not found for number: " + number);
    }

    return name;
}

From source file:com.eugene.fithealthmaingit.FatSecretSearchAndGet.FatSecretGetMethod.java

private static String sign(String method, String uri, String[] params) {
    String[] p = { method, Uri.encode(uri), Uri.encode(paramify(params)) };
    String s = join(p, "&");
    SecretKey sk = new SecretKeySpec(Globals.APP_SECRET.getBytes(), Globals.HMAC_SHA1_ALGORITHM);
    try {/*from ww w .j  a v  a2 s. c  om*/
        Mac m = Mac.getInstance(Globals.HMAC_SHA1_ALGORITHM);
        m.init(sk);
        return Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
    } catch (java.security.NoSuchAlgorithmException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    } catch (java.security.InvalidKeyException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    }
}

From source file:com.vk.sdk.util.VKStringJoiner.java

/**
 * Join parameters map into string, usually query string
 *
 * @param queryParams Map to join/*ww  w .j  a va  2  s  .c  om*/
 * @param isUri       Indicates that value parameters must be uri-encoded
 * @return Result query string, like k=v&k1=v1
 */
public static String joinParams(Map<String, Object> queryParams, boolean isUri) {
    ArrayList<String> params = new ArrayList<String>(queryParams.size());
    for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
        Object value = entry.getValue();
        if (value instanceof VKAttachments) {
            value = ((VKAttachments) value).toAttachmentsString();
        }
        params.add(String.format("%s=%s", entry.getKey(),
                isUri ? Uri.encode(String.valueOf(value)) : String.valueOf(value)));
    }
    return join(params, "&");
}

From source file:br.com.anteros.android.ui.controls.autocomplete.AnterosGoogleAutoCompleteSearch.java

private String createUrl(String search) {
    String url = "http://suggestqueries.google.com/complete/search?client=firefox&hl=" + language;
    try {/*from   w w w.j a  v  a  2s.  com*/
        url += "&q=" + Uri.encode(search);
    } catch (Exception e) {
    }
    return url;
}

From source file:com.clevertrail.mobile.viewtrail.Object_TrailArticle.java

private static int loadTrailArticle_helper(Activity activity, String sTrailName) {

    String sResponseLine = "";
    //sanity check
    if (sTrailName == null || sTrailName == "")
        return R.string.error_notrailname;

    //connect to clevertrail.com to get trail article
    HttpURLConnection urlConnection = null;
    try {/*  ww  w  . ja v  a 2  s  .  co m*/
        String requestURL = String.format("http://clevertrail.com/ajax/handleGetArticleJSONByName.php?name=%s",
                Uri.encode(sTrailName));

        URL url = new URL(requestURL);
        urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        BufferedReader r = new BufferedReader(new InputStreamReader(in));

        //trail article in json format
        sResponseLine = r.readLine();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        // could not connect to clevertrail.com
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    JSONObject json = null;
    try {
        if (sResponseLine != "")
            json = new JSONObject(sResponseLine);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_corrupttrailinfo;
    }

    //now that we have the latest trail information, mark it as unsaved
    Object_TrailArticle.bSaved = false;

    // if json is null, we might not have internet activity so check saved
    // files
    if (json == null) {
        Database_SavedTrails db = new Database_SavedTrails(activity);
        db.openToRead();
        String jsonString = db.getJSONString(sTrailName);
        try {
            json = new JSONObject(jsonString);

            // if we found the json object in the db, mark it as saved
            if (json != null) {
                Object_TrailArticle.bSaved = true;
            }

        } catch (JSONException e) {
            return R.string.error_corrupttrailinfo;
        }
        db.close();
    }

    if (json != null) {
        Object_TrailArticle.createFromJSON(sTrailName, json);
        Object_TrailArticle.jsonText = sResponseLine;

        //after loading the data, launch the activity to actually view the trail
        Intent i = new Intent(mActivity, Activity_ViewTrail.class);
        mActivity.startActivity(i);

        return 0;
    }
    return R.string.error_corrupttrailinfo;
}

From source file:com.mindprotectionkit.freephone.contacts.ContactAccessor.java

public CursorLoader getPeopleCursor(Context context, String filter) {
    Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(filter));
    return getPeopleCursor(context, uri);
}

From source file:net.kourlas.voipms_sms.Utils.java

/**
 * Gets a URI pointing to a contact's photo, given a phone number.
 *
 * @param applicationContext The application context.
 * @param phoneNumber        The phone number of the contact.
 * @return a URI pointing to the contact's photo.
 *///from  w w w. j a  va2s  . co m
public static String getContactPhotoUri(Context applicationContext, String phoneNumber) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    return getContactPhotoUri(applicationContext, uri);
}

From source file:com.innoc.secureline.contacts.ContactAccessor.java

public CursorLoader getRegisteredContactsCursor(Context context, String filter) {
    Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(filter));
    return getRegisteredContactsCursor(context, uri);
}

From source file:com.phonemetra.turbo.lockclock.weather.OpenWeatherMapProvider.java

@Override
public List<LocationResult> getLocations(String input) {
    String url = String.format(URL_LOCATION, Uri.encode(input), getLanguageCode());
    String response = HttpRetriever.retrieve(url);
    if (response == null) {
        return null;
    }/*from w  w  w.  ja  v a2s .  c om*/

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "URL = " + url + " returning a response of " + response);
    }

    try {
        JSONArray jsonResults = new JSONObject(response).getJSONArray("list");
        ArrayList<LocationResult> results = new ArrayList<LocationResult>();
        int count = jsonResults.length();

        for (int i = 0; i < count; i++) {
            JSONObject result = jsonResults.getJSONObject(i);
            LocationResult location = new LocationResult();

            location.id = result.getString("id");
            location.city = result.getString("name");
            location.countryId = result.getJSONObject("sys").getString("country");
            results.add(location);
        }

        return results;
    } catch (JSONException e) {
        Log.w(TAG, "Received malformed location data (input=" + input + ")", e);
    }

    return null;
}

From source file:com.example.m.niceproject.service.YahooWeatherService.java

public void refreshWeather(String location) {

    new AsyncTask<String, Void, Channel>() {
        @Override//  w w w. j a va  2  s.  co m
        protected Channel doInBackground(String[] locations) {

            String location = locations[0];

            Channel channel = new Channel();

            String YQL = String.format(
                    "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"%s\")",
                    location);

            String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json",
                    Uri.encode(YQL));

            try {
                URL url = new URL(endpoint);

                URLConnection connection = url.openConnection();
                connection.setUseCaches(false);

                InputStream inputStream = connection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

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

                JSONObject queryResults = data.optJSONObject("query");

                int count = queryResults.optInt("count");

                if (count == 0) {
                    error = new LocationWeatherException("No weather information found for " + location);
                    return null;
                }

                JSONObject channelJSON = queryResults.optJSONObject("results").optJSONObject("channel");
                channel.populate(channelJSON);

                return channel;

            } catch (Exception e) {
                error = e;
            }

            return null;
        }

        @Override
        protected void onPostExecute(Channel channel) {

            if (channel == null && error != null) {
                listener.serviceFailure(error);
            } else {
                listener.serviceSuccess(channel);
            }

        }

    }.execute(location);
}