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:org.tigase.mobile.chat.ChatHistoryFragment.java

private void clearMessageHistory() {
    getActivity().getApplicationContext().getContentResolver().delete(
            Uri.parse(ChatHistoryProvider.CHAT_URI + "/" + Uri.encode(chat.getJid().getBareJid().toString())),
            null, null);//from  ww  w  .j a v  a 2s. co  m
}

From source file:org.opendatakit.common.android.views.OdkCommon.java

/**
 * Return the base uri for the Tables app name with a trailing separator.
 *
 * @return/*from w  w w .ja  v  a 2s  .c  o m*/
 */
private String getBaseContentUri() {
    logDebug("getBaseContentUri()");
    Uri contentUri = Uri.parse(mActivity.getWebViewContentUri());
    String appName = mActivity.getAppName();
    contentUri = Uri.withAppendedPath(contentUri, Uri.encode(appName));
    return contentUri.toString() + "/";
}

From source file:org.musicmod.android.app.QueryFragment.java

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

    String filter = "";

    if (args != null) {
        filter = args.getString(INTENT_KEY_FILTER) != null ? args.getString(INTENT_KEY_FILTER) : "";
    }/*  w w  w  . j a v a 2 s . c  o  m*/

    StringBuilder where = new StringBuilder();

    where.append(Audio.Media.IS_MUSIC + "=1");
    where.append(" AND " + Audio.Media.TITLE + " != ''");

    String[] cols = new String[] { BaseColumns._ID, Audio.Media.MIME_TYPE, Audio.Artists.ARTIST,
            Audio.Albums.ALBUM, Audio.Media.TITLE, "data1", "data2" };

    Uri uri = Uri.parse("content://media/external/audio/search/fancy/" + Uri.encode(filter));

    // Now create and return a CursorLoader that will take care of
    // creating a Cursor for the data being displayed.
    return new CursorLoader(getActivity(), uri, cols, where.toString(), null, null);
}

From source file:com.ultramegasoft.flavordex2.util.EntryFormHelper.java

/**
 * Set up the autocomplete for the maker field.
 *//*from  w w  w  . j a v a 2  s  .c  o m*/
private void setupMakersAutoComplete() {
    final SimpleCursorAdapter adapter = new SimpleCursorAdapter(mFragment.getContext(),
            R.layout.simple_dropdown_item_2line, null,
            new String[] { Tables.Makers.NAME, Tables.Makers.LOCATION },
            new int[] { android.R.id.text1, android.R.id.text2 }, 0);

    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {
            final Uri uri;
            if (TextUtils.isEmpty(constraint)) {
                uri = Tables.Makers.CONTENT_URI;
            } else {
                uri = Uri.withAppendedPath(Tables.Makers.CONTENT_FILTER_URI_BASE,
                        Uri.encode(constraint.toString()));
            }

            final Bundle args = new Bundle();
            args.putParcelable("uri", uri);

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mFragment.getLoaderManager().restartLoader(LOADER_MAKERS, args, EntryFormHelper.this);
                }
            });

            return adapter.getCursor();
        }
    });

    mTxtMaker.setAdapter(adapter);

    // fill in maker and origin fields with a suggestion
    mTxtMaker.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final Cursor cursor = (Cursor) parent.getItemAtPosition(position);
            cursor.moveToPosition(position);

            final String name = cursor.getString(cursor.getColumnIndex(Tables.Makers.NAME));
            final String origin = cursor.getString(cursor.getColumnIndex(Tables.Makers.LOCATION));
            mTxtMaker.setText(name);
            mTxtOrigin.setText(origin);

            // skip origin field
            mTxtOrigin.focusSearch(View.FOCUS_DOWN).requestFocus();
        }
    });
}

From source file:com.pbadun.fragment.adapter.ImageDownloader.java

Bitmap downloadBitmap(String url) {
    //final int IO_BUFFER_SIZE = 4 * 1024;

    //  ...  url//from w w w .  ja v a 2  s . com
    String fName = Uri.encode(url);

    //  
    try {
        FileInputStream fi = context.openFileInput(fName);
        Log.d("log", "File is set!");

        //   -      
        Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(fi));
        return bitmap;
    } catch (FileNotFoundException e1) {
        //Log.d("bitmap",e1.toString());
        Log.d("log", "File not isset!");
    }

    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient()
            : AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));

                //    ...
                FileOutputStream fo = null;
                try {
                    fo = context.openFileOutput(fName, Context.MODE_PRIVATE);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fo);
                    fo.flush();
                } catch (Exception e) {
                    //     ... :(
                    Log.d("log", "Error create file.");
                    //    ...
                    context.deleteFile(fName);
                } finally {
                    if (fo != null) {
                        //   
                        fo.close();
                    }
                }

                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
    }
    return null;
}

From source file:com.lottodroid.widgets.wikipicture.WikipictureHelper.java

/**
 * Read and return the content for a specific Wiktionary page. This makes a
 * lightweight API call, and trims out just the page content returned.
 * Because this call blocks until results are available, it should not be
 * run from a UI thread./*  ww w . j  a v  a 2 s.  c  om*/
 * 
 * @param title The exact title of the Wiktionary page requested.
 * @param expandTemplates If true, expand any wiki templates found.
 * @return Exact content of page.
 * @throws ApiException If any connection or server error occurs.
 * @throws ParseException If there are problems parsing the response.
 */
public static String getPageContent(String title, boolean expandTemplates) throws ApiException, ParseException {
    // Encode page title and expand templates if requested
    String encodedTitle = Uri.encode(title);
    String expandClause = expandTemplates ? WIKIPICTURE_EXPAND_TEMPLATES : "";

    // Query the API for content
    String content = getUrlContent(String.format(WIKIPICTURE_PAGE, encodedTitle, expandClause));
    try {
        // Drill into the JSON response to find the content body
        JSONObject response = new JSONObject(content);
        JSONObject query = response.getJSONObject("query");
        JSONObject pages = query.getJSONObject("pages");
        JSONObject page = pages.getJSONObject((String) pages.keys().next());
        JSONArray revisions = page.getJSONArray("revisions");
        JSONObject revision = revisions.getJSONObject(0);
        return revision.getString("*");
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response", e);
    }
}

From source file:com.xorcode.andtweet.TweetListActivity.java

/**
 * Prepare query to the ContentProvider (to the database) and load List of Tweets with data
 * @param queryIntent/*from  w w  w  .  j  a  v a 2s.c o  m*/
 * @param otherThread This method is being accessed from other thread
 * @param loadOneMorePage load one more page of tweets
 */
protected void queryListData(Intent queryIntent, boolean otherThread, boolean loadOneMorePage) {
    // The search query is provided as an "extra" string in the query intent
    // TODO maybe use mQueryString here...
    String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
    Intent intent = getIntent();

    if (MyLog.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "doSearchQuery; queryString=\"" + queryString + "\"; TimelineType=" + mTimelineType);
    }

    Uri contentUri = Tweets.CONTENT_URI;

    SelectionAndArgs sa = new SelectionAndArgs();
    String sortOrder = Tweets.DEFAULT_SORT_ORDER;
    // Id of the last (oldest) tweet to retrieve 
    long lastItemId = -1;

    if (queryString != null && queryString.length() > 0) {
        // Record the query string in the recent queries suggestions
        // provider
        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                TimelineSearchSuggestionProvider.AUTHORITY, TimelineSearchSuggestionProvider.MODE);
        suggestions.saveRecentQuery(queryString, null);

        contentUri = Tweets.SEARCH_URI;
        contentUri = Uri.withAppendedPath(contentUri, Uri.encode(queryString));
    }
    intent.putExtra(SearchManager.QUERY, queryString);

    if (!contentUri.equals(intent.getData())) {
        intent.setData(contentUri);
    }

    if (sa.nArgs == 0) {
        // In fact this is needed every time you want to load next page of
        // tweets.
        // So we have to duplicate here everything we set in
        // com.xorcode.andtweet.TimelineActivity.onOptionsItemSelected()
        sa.clear();
        sa.addSelection(Tweets.TWEET_TYPE + " IN (?, ?)", new String[] {
                String.valueOf(Tweets.TIMELINE_TYPE_FRIENDS), String.valueOf(Tweets.TIMELINE_TYPE_MENTIONS) });
        if (mTimelineType == Tweets.TIMELINE_TYPE_FAVORITES) {
            sa.addSelection(AndTweetDatabase.Tweets.FAVORITED + " = ?", new String[] { "1" });
        }
        if (mTimelineType == Tweets.TIMELINE_TYPE_MENTIONS) {
            sa.addSelection(Tweets.MESSAGE + " LIKE ?",
                    new String[] { "%@" + TwitterUser.getTwitterUser().getUsername() + "%" });
        }
    }

    if (!positionRestored) {
        // We have to ensure that saved position will be
        // loaded from database into the list
        lastItemId = getSavedPosition(true);
    }

    int nTweets = 0;
    if (mCursor != null && !mCursor.isClosed()) {
        if (positionRestored) {
            // If position is NOT loaded - this cursor is from other
            // timeline/search
            // and we shouldn't care how much rows are there.
            nTweets = mCursor.getCount();
        }
        if (!otherThread) {
            mCursor.close();
        }
    }

    if (lastItemId > 0) {
        if (sa.nArgs == 0) {
            sa.addSelection("AndTweetDatabase.Tweets.TWEET_TYPE" + " IN (?, ?)" + ")",
                    new String[] { String.valueOf(Tweets.TIMELINE_TYPE_FRIENDS),
                            String.valueOf(Tweets.TIMELINE_TYPE_MENTIONS) });
        }
        sa.addSelection(Tweets._ID + " >= ?", new String[] { String.valueOf(lastItemId) });
    } else {
        if (loadOneMorePage) {
            nTweets += PAGE_SIZE;
        } else if (nTweets < PAGE_SIZE) {
            nTweets = PAGE_SIZE;
        }
        sortOrder += " LIMIT 0," + nTweets;
    }

    // This is for testing pruneOldRecords
    //        try {
    //            FriendTimeline fl = new FriendTimeline(TweetListActivity.this,
    //                    AndTweetDatabase.Tweets.TIMELINE_TYPE_FRIENDS);
    //            fl.pruneOldRecords();
    //
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }

    mCursor = getContentResolver().query(contentUri, PROJECTION, sa.selection, sa.selectionArgs, sortOrder);
    if (!otherThread) {
        createAdapters();
    }

}

From source file:vn.mbm.phimp.me.gallery3d.picasa.PicasaApi.java

public int getAlbums(AccountManager accountManager, SyncResult syncResult, UserEntry user,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append(BASE_QUERY_STRING);/* ww  w  .  ja v  a2s.c  om*/
    builder.append("&kind=album");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = user.albumsEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    if (!retry) {
                        accountManager.invalidateAuthToken(PicasaService.ACCOUNT_TYPE, mAuth.authToken);
                        retry = true;
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                default:
                    Log.i(TAG, "getAlbums uri " + builder.toString());
                    Log.e(TAG, "getAlbums: unexpected status code " + operation.outStatus + " data: "
                            + operation.outBody.toString());
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the user/albums feed.
            user.albumsEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mAlbumInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(TAG, "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(TAG, "getAlbums: " + e);
        ++syncResult.stats.numIoExceptions;
    } catch (SAXException e) {
        Log.e(TAG, "getAlbums: " + e);
        ++syncResult.stats.numParseExceptions;
    }
    return RESULT_ERROR;
}

From source file:com.ocp.picasa.PicasaApi.java

public int getAlbums(AccountManager accountManager, SyncResult syncResult, UserEntry user,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append(BASE_QUERY_STRING);//from   w  w w  .  ja va 2 s . c  o  m
    builder.append("&kind=album");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = user.albumsEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    if (!retry) {
                        accountManager.invalidateAuthToken(PicasaService.ACCOUNT_TYPE, mAuth.authToken);
                        retry = true;
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                default:
                    Log.i(Gallery.TAG, TAG + ": " + "getAlbums uri " + builder.toString());
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbums: unexpected status code " + operation.outStatus
                            + " data: " + operation.outBody.toString());
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the user/albums feed.
            user.albumsEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mAlbumInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbums: " + e);
        ++syncResult.stats.numIoExceptions;
    } catch (SAXException e) {
        Log.e(Gallery.TAG, TAG + ": " + "getAlbums: " + e);
        ++syncResult.stats.numParseExceptions;
    }
    return RESULT_ERROR;
}

From source file:com.silentcircle.accounts.AccountStep3.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mFragment = this;

    String deviceId = null;/*  w w w  . j av a2  s .c  o m*/
    String username = null;

    Bundle args = getArguments();
    if (args != null) {
        mRoninCode = args.getString(AuthenticatorActivity.ARG_RONIN_CODE);
        deviceId = args.getString(ProvisioningActivity.DEVICE_ID);
        mUseExistingAccount = args.getBoolean(ProvisioningActivity.USE_EXISTING, false);
        username = args.getString(ProvisioningActivity.USERNAME);
    }

    if (ConfigurationUtilities.mTrace)
        Log.d(TAG, "Feature code: '" + mRoninCode + "', instance device id: '" + deviceId + "', existing: "
                + mUseExistingAccount + ", username: " + username);
    if (deviceId == null || username == null) {
        // Report this problem
        mParent.showErrorInfo("Feature code: '" + mRoninCode + "', device id: '" + deviceId + "'"
                + "username: '" + username + "'");
        return;
    }
    // Add the feature code / license code to JSON data
    // only do this if an account is being created (SPA-930)
    JSONObject data = mParent.getJsonHolder();
    if (mRoninCode != null && !mUseExistingAccount) {
        try {
            data.put("license_code", mRoninCode);
        } catch (JSONException e) {
            mParent.showErrorInfo(e.getLocalizedMessage());
            Log.e(TAG, "JSON problem: ", e);
        }
    }
    try {
        // https://sccps.silentcircle.com/v1/user/  (PUT)
        mRequestUrlCreateAccount = new URL(
                ConfigurationUtilities.getProvisioningBaseUrl(mParent.getBaseContext())
                        + ConfigurationUtilities.getUserManagementBaseV1User(mParent.getBaseContext())
                        + Uri.encode(username) + "/");

        // https://sccps.silentcircle.com/v1/me/device/{device_id}/  (PUT)
        // TODO remove enable_tfa from querystring for production
        mRequestUrlProvisionDevice = new URL(
                ConfigurationUtilities.getProvisioningBaseUrl(mParent.getBaseContext())
                        + ConfigurationUtilities.getDeviceManagementBase(mParent.getBaseContext())
                        + Uri.encode(deviceId) + "/?enable_tfa=1");
    } catch (MalformedURLException e) {
        mParent.provisioningCancel();
    }
}