Example usage for android.os Bundle putString

List of usage examples for android.os Bundle putString

Introduction

In this page you can find the example usage for android.os Bundle putString.

Prototype

public void putString(@Nullable String key, @Nullable String value) 

Source Link

Document

Inserts a String value into the mapping of this Bundle, replacing any existing value for the given key.

Usage

From source file:br.random.util.facebookintegration.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String/* w ww .  j  a v a 2s  .  c  o m*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.qburst.android.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String//  w w w.  j av a 2 s .  c  om
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }

    return response;
}

From source file:com.shome.rubyshop.LoginActivity.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
    outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}

From source file:com.facebook.AsyncRequestTests.java

@MediumTest
@LargeTest/*ww w  .  jav a  2s  . co m*/
public void testExecuteSingleGet() {
    final AccessToken accessToken = getAccessTokenForSharedUser();
    Bundle parameters = new Bundle();
    parameters.putString("fields", "location");
    GraphRequest request = new GraphRequest(accessToken, "TourEiffel", parameters, null,
            new ExpectSuccessCallback() {
                @Override
                protected void performAsserts(GraphResponse response) {
                    assertNotNull(response);
                    JSONObject graphPlace = response.getJSONObject();
                    assertEquals("Paris", graphPlace.optJSONObject("location").optString("city"));
                }
            });

    TestGraphRequestAsyncTask task = new TestGraphRequestAsyncTask(request);

    task.executeOnBlockerThread();

    // Wait on 2 signals: request and task will both signal.
    waitAndAssertSuccess(2);
}

From source file:org.ohmage.auth.Authenticator.java

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) throws NetworkErrorException {

    // Extract the email and refresh_token from the Account Manager, and ask
    // the server for a new refresh_token.
    String authToken = am.peekAuthToken(account, authTokenType);

    // Lets give another try to authenticate the user
    AccessToken token = null;// w w w . j  av a 2  s . com
    UserRecoverableAuthException userRecoverableAuthException = null;

    if (TextUtils.isEmpty(authToken)) {
        final String refreshToken = am.getPassword(account);
        Log.i(TAG, "Auth token is null");
        if (refreshToken != null) {
            Log.i(TAG, "Refresh Token");
            try {
                // If the account credentials have not gone to the server yet we saved the
                // password for the user
                if (Boolean.parseBoolean(am.getUserData(account, USE_PASSWORD))) {
                    token = ohmageService.getAccessToken(account.name, refreshToken);
                    if (token != null) {
                        am.setUserData(account, Authenticator.USE_PASSWORD, String.valueOf(false));
                        am.setUserData(account, Authenticator.USER_ID, token.getUserId());
                    }
                } else {
                    // refresh token
                    if (Ohmage.USE_DSU_DATAPOINTS_API) {

                        Log.i(TAG, "Refresh Token with DSU");
                        token = ohmageService.refreshAccessToken(refreshToken, "refresh_token");
                    } else {
                        token = ohmageService.getAccessToken(refreshToken);
                    }
                }
            } catch (AuthenticationException e) {
                // This will happen if the refresh token was already used, or it was
                // invalidated or something

                // We can try getting the token from google
                String googleAccount = am.getUserData(account, USER_DATA_GOOGLE_ACCOUNT);
                if (googleAccount != null) {
                    try {
                        token = getTokenFromGoogle(googleAccount);
                        Log.i(TAG, token.toString());
                    } catch (UserRecoverableAuthException e1) {
                        userRecoverableAuthException = e1;
                    }
                }
            } catch (RetrofitError e) {
                if (e.getResponse() != null && e.getResponse().getStatus() == 409) {
                    // The user hasn't activated their account by clicking the link
                    final Bundle bundle = new Bundle();
                    bundle.putString(AccountManager.KEY_AUTH_FAILED_MESSAGE,
                            Ohmage.app().getString(R.string.account_not_activated));
                    bundle.putParcelable(AccountManager.KEY_INTENT,
                            new Intent(mContext, AccountNotActivatedDialog.class));
                    return bundle;
                } else {
                    throw new NetworkErrorException();
                }
            } catch (Exception e) {
                Log.e(TAG, "", e);
            }
        }
    }

    // If we get an authToken - we return it
    if (token != null) {
        am.setPassword(account, token.getRefreshToken());
        authToken = token.getAccessToken();
    }

    if (!TextUtils.isEmpty(authToken)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        return result;
    }

    // If we get here, then we couldn't access the user's password - so we
    // need to re-prompt them for their credentials. We do that by creating
    // an intent to display our AuthenticatorActivity.
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    intent.putExtra(AuthenticatorActivity.EXTRA_FROM_AUTHENTICATOR, true);
    intent.putExtra(AuthenticatorActivity.EXTRA_HANDLE_USER_RECOVERABLE_ERROR, userRecoverableAuthException);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

From source file:com.familygraph.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //from ww  w .  j  ava  2 s.c  om
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("FamilyGraph-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FamilyGraphAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FamilyGraph
        // error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:br.com.anteros.social.facebook.actions.FacebookAction.java

private Bundle updateAppSecretProof(Bundle bundle) {
    if (configuration.useAppsecretProof()) {
        if (bundle == null) {
            bundle = new Bundle();
        }//from  w w  w  .  j  ava2s . co  m
        bundle.putString("appsecret_proof",
                FacebookUtils.encode(configuration.getAppSecret(), sessionManager.getAccessToken().getToken()));
    }
    return bundle;
}

From source file:com.facebook.AsyncRequestTests.java

@MediumTest
@LargeTest//from w  w w . j a v a  2 s .  com
public void testExecuteSingleGetUsingHttpURLConnection() {
    final AccessToken accessToken = getAccessTokenForSharedUser();
    Bundle parameters = new Bundle();
    parameters.putString("fields", "location");
    GraphRequest request = new GraphRequest(accessToken, "TourEiffel", parameters, null,
            new ExpectSuccessCallback() {
                @Override
                protected void performAsserts(GraphResponse response) {
                    assertNotNull(response);
                    JSONObject graphPlace = response.getJSONObject();
                    assertEquals("Paris", graphPlace.optJSONObject("location").optString("city"));
                }
            });
    HttpURLConnection connection = GraphRequest.toHttpConnection(request);

    TestGraphRequestAsyncTask task = new TestGraphRequestAsyncTask(connection,
            Arrays.asList(new GraphRequest[] { request }));

    task.executeOnBlockerThread();

    // Wait on 2 signals: request and task will both signal.
    waitAndAssertSuccess(2);
}

From source file:com.facebook.applinks.FacebookAppLinkResolver.java

/**
 * Asynchronously resolves App Link data for multiple URLs
 *
 * @param uris A list of Uri objects to resolve into App Links
 * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was
 * successfully resolved into an App Link. Uris that could not be resolved into App Links will
 * not be present in the Map. In the case of general server errors, the task will be completed
 * with the corresponding error.//from w  ww . j  a  va 2 s. c  o m
 */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();

    for (Uri uri : uris) {
        AppLink appLink = null;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }

        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }

    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }

    final Task<Map<Uri, AppLink>>.TaskCompletionSource taskCompletionSource = Task.create();

    Bundle appLinkRequestParameters = new Bundle();

    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY,
            APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    GraphRequest appLinkRequest = new GraphRequest(
            // We will use the current access token if we have one else we will use the client
            // token
            AccessToken.getCurrentAccessToken(), /* Access Token */
            "", /* Graph path */
            appLinkRequestParameters, /* Query parameters */
            null, /* HttpMethod */
            new GraphRequest.Callback() { /* Callback */
                @Override
                public void onCompleted(GraphResponse response) {
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        taskCompletionSource.setError(error.getException());
                        return;
                    }

                    JSONObject responseJson = response.getJSONObject();
                    if (responseJson == null) {
                        taskCompletionSource.setResult(appLinkResults);
                        return;
                    }

                    for (Uri uri : urisToRequest) {
                        String uriString = uri.toString();
                        if (!responseJson.has(uriString)) {
                            continue;
                        }

                        JSONObject urlData = null;
                        try {
                            urlData = responseJson.getJSONObject(uri.toString());
                            JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);

                            JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);

                            int targetsCount = rawTargets.length();
                            List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);

                            for (int i = 0; i < targetsCount; i++) {
                                AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                                if (target != null) {
                                    targets.add(target);
                                }
                            }

                            Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                            AppLink appLink = new AppLink(uri, targets, webFallbackUrl);

                            appLinkResults.put(uri, appLink);
                            synchronized (cachedAppLinks) {
                                cachedAppLinks.put(uri, appLink);
                            }
                        } catch (JSONException e) {
                            // The data for this uri was missing or badly formed.
                            continue;
                        }
                    }

                    taskCompletionSource.setResult(appLinkResults);
                }
            });

    appLinkRequest.executeAsync();

    return taskCompletionSource.getTask();
}

From source file:net.peterkuterna.android.apps.devoxxsched.service.SyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
    if (receiver != null)
        receiver.send(STATUS_RUNNING, Bundle.EMPTY);

    final Context context = this;
    final SharedPreferences syncServicePrefs = getSharedPreferences(SyncPrefs.DEVOXXSCHED_SYNC,
            Context.MODE_PRIVATE);
    final int localVersion = syncServicePrefs.getInt(SyncPrefs.LOCAL_VERSION, VERSION_NONE);
    final long lastRemoteSync = syncServicePrefs.getLong(SyncPrefs.LAST_REMOTE_SYNC, 0);

    try {/*from w w  w  .  ja v  a2  s  .  co  m*/
        // Bulk of sync work, performed by executing several fetches from
        // local and online sources.

        final long startLocal = System.currentTimeMillis();
        final boolean localParse = localVersion < VERSION_LOCAL;
        Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_LOCAL=" + VERSION_LOCAL);
        if (localParse) {
            // Parse values from local cache first
            mLocalExecutor.execute(R.xml.search_suggest, new LocalSearchSuggestHandler());
            mLocalExecutor.execute(context, "cache-rooms.json", new RemoteRoomsHandler());
            mLocalExecutor.execute(context, "cache-presentationtypes.json", new RemoteSessionTypesHandler());
            mLocalExecutor.execute(context, "cache-speakers.json", new RemoteSpeakersHandler());
            mLocalExecutor.execute(context, "cache-presentations.json", new RemoteSessionsHandler());
            mLocalExecutor.execute(context, "cache-schedule.json", new RemoteScheduleHandler());

            // Save local parsed version
            syncServicePrefs.edit().putInt(SyncPrefs.LOCAL_VERSION, VERSION_LOCAL).commit();
        }
        Log.d(TAG, "local sync took " + (System.currentTimeMillis() - startLocal) + "ms");

        final long startRemote = System.currentTimeMillis();
        boolean performRemoteSync = performRemoteSync(mResolver, mHttpClient, intent, context);
        if (performRemoteSync) {
            // Parse values from REST interface
            ArrayList<RequestHash> result = mRemoteExecutor.executeGet(new String[] { Constants.ROOMS_URL, },
                    new RemoteRoomsHandler());
            for (RequestHash requestHash : result) {
                SyncUtils.updateLocalMd5(mResolver, requestHash.getUrl(), requestHash.getMd5());
            }
            result = mRemoteExecutor.executeGet(new String[] { Constants.LABS_PRESENTATION_TYPES_URL, },
                    new RemoteSessionTypesHandler());
            for (RequestHash requestHash : result) {
                SyncUtils.updateLocalMd5(mResolver, requestHash.getUrl(), requestHash.getMd5());
            }
            result = mRemoteExecutor.executeGet(
                    new String[] { Constants.SPEAKERS_URL, Constants.LABS_SPEAKERS_URL, },
                    new RemoteSpeakersHandler());
            for (RequestHash requestHash : result) {
                SyncUtils.updateLocalMd5(mResolver, requestHash.getUrl(), requestHash.getMd5());
            }
            result = mRemoteExecutor.executeGet(
                    new String[] { Constants.PRESENTATIONS_URL, Constants.LABS_PRESENTATIONS_URL, },
                    new RemoteSessionsHandler());
            for (RequestHash requestHash : result) {
                SyncUtils.updateLocalMd5(mResolver, requestHash.getUrl(), requestHash.getMd5());
            }
            result = mRemoteExecutor.executeGet(
                    new String[] { Constants.SCHEDULE_URL, Constants.LABS_SCHEDULE_URL, },
                    new RemoteScheduleHandler());
            for (RequestHash requestHash : result) {
                SyncUtils.updateLocalMd5(mResolver, requestHash.getUrl(), requestHash.getMd5());
            }

            // Save last remote sync time
            syncServicePrefs.edit().putLong(SyncPrefs.LAST_REMOTE_SYNC, startRemote).commit();
            // Save remote parsed version
            syncServicePrefs.edit().putInt(SyncPrefs.LOCAL_VERSION, VERSION_REMOTE).commit();
        }
        Log.d(TAG, "remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");

        if (!localParse && performRemoteSync) {
            NotificationUtils.cancelNotifications(context);
            NotificationUtils.notifyNewSessions(context, getContentResolver());
            NotificationUtils.notifyChangedStarredSessions(context, getContentResolver());
        }
    } catch (Exception e) {
        Log.e(TAG, "Problem while syncing", e);

        if (receiver != null) {
            // Pass back error to surface listener
            final Bundle bundle = new Bundle();
            bundle.putString(Intent.EXTRA_TEXT, e.toString());
            receiver.send(STATUS_ERROR, bundle);
        }
    }

    // Announce success to any surface listener
    Log.d(TAG, "sync finished");
    if (receiver != null)
        receiver.send(STATUS_FINISHED, Bundle.EMPTY);
}