Example usage for android.os Bundle containsKey

List of usage examples for android.os Bundle containsKey

Introduction

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

Prototype

public boolean containsKey(String key) 

Source Link

Document

Returns true if the given key is contained in the mapping of this Bundle.

Usage

From source file:net.idlesoft.android.apps.github.activities.NewsFeed.java

@Override
public void onRestoreInstanceState(final Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    boolean keepGoing = true;
    try {//w  ww.j a  v a  2 s.c om
        if (savedInstanceState.containsKey("json")) {
            mJson = new JSONArray(savedInstanceState.getString("json"));
        } else {
            keepGoing = false;
        }
    } catch (final JSONException e) {
        keepGoing = false;
    }

    if (keepGoing == true) {
        mActivityAdapter.loadData(mJson);
        mActivityAdapter.pushData();
    }
}

From source file:karroo.app.test.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//from   w  w w . ja  v a  2 s  .com
 * @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) {
            if (params.get(key) instanceof byte[]) {
                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.mobli.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*  w ww . j a v a 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);
    }
    Util.logd("Mobli-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " MobliAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            Object parameter = params.get(key);
            if (parameter instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) parameter);
            }
        }

        // 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 Mobli error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.permpings.utils.facebook.sdk.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//from  ww  w . j a va2  s .  co 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);
    }
    Util.logd("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()) {
            Object parameter = params.get(key);
            if (parameter instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) parameter);
            }
        }

        // 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:org.mifos.androidclient.main.CentersListActivity.java

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.centers_list);
    CollectionSheetHolder.setCOLLECTION_SHEET(1);
    if (bundle != null && bundle.containsKey(CustomersData.BUNDLE_KEY)) {
        mCustomersData = (CustomersData) bundle.getSerializable(CustomersData.BUNDLE_KEY);
    }/*w  w w  .j  a v  a 2 s . c o m*/

    mFilterBox = (EditText) findViewById(R.id.centers_list_filter_box);
    mCentersList = (ListView) findViewById(R.id.centers_list);
    mContent = (LinearLayout) findViewById(R.id.centersList_content);
    mMessage = (TextView) findViewById(R.id.centersList_noDataMessage);
    mCustomerService = new CustomerService(this);
}

From source file:com.android.volley.toolbox.AndroidAuthenticator.java

@SuppressWarnings("deprecation")
@Override//from   w  w w . j  a va 2s. c  o  m
public String getAuthToken() throws AuthFailureError {
    AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(mAccount, mAuthTokenType,
            mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}

From source file:com.pindroid.syncadapter.BookmarkSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {//from www  . j a  va2s.com

    boolean upload = extras.containsKey(ContentResolver.SYNC_EXTRAS_UPLOAD);
    boolean manual = extras.containsKey(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF)
            && extras.containsKey(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS);

    try {
        if (upload) {
            Log.d(TAG, "Beginning Upload Sync");
            DeleteBookmarks(account, syncResult);
            UploadBookmarks(account, syncResult);
        } else {
            if (manual)
                Log.d(TAG, "Beginning Manual Download Sync");
            else
                Log.d(TAG, "Beginning Download Sync");

            DeleteBookmarks(account, syncResult);
            UploadBookmarks(account, syncResult);
            InsertBookmarks(account, syncResult);
        }

        checkSecretToken(account);
    } catch (final ParseException e) {
        syncResult.stats.numParseExceptions++;
        Log.e(TAG, "ParseException", e);
    } catch (final AuthenticationException e) {
        syncResult.stats.numAuthExceptions++;
        Log.e(TAG, "AuthException", e);
    } catch (final IOException e) {
        syncResult.stats.numIoExceptions++;
        Log.e(TAG, "IOException", e);
    } catch (final TooManyRequestsException e) {
        syncResult.delayUntil = e.getBackoff();
        Log.d(TAG, "Too Many Requests.  Backing off for " + e.getBackoff() + " seconds.");
    } catch (PinboardException e) {
        syncResult.stats.numSkippedEntries++;
        Log.e(TAG, "PinboardException", e);
    } finally {
        Log.d(TAG, "Finished Sync");
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(SYNC_FINISHED_ACTION));
    }
}

From source file:com.ble.facebook.Util.java

public static String posttowall(String url, String method, Bundle params, String Accesstoken)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;//from ww  w. j  ava  2 s  .  co m

    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.putByteArray("method", method.getBytes());
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(Accesstoken);
            params.putByteArray("access_token", decoded_token.getBytes());
        }

        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());
        Log.d("OutputStreamedData", ("--" + strBoundary + endLine) + (encodePostBody(params, strBoundary))
                + (endLine + "--" + strBoundary + endLine));
        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.cloudbees.gasp.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    // When an intent is received by this Service, this method
    // is called on a new thread.

    Uri action = intent.getData();//w w  w .  j a v  a2 s . c  om
    Bundle extras = intent.getExtras();

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        // Extras contain our ResultReceiver and data is our REST action.  
        // So, without these components we can't do anything useful.
        Log.e(TAG, "You did not pass extras or data with the Intent.");

        return;
    }

    // We default to GET if no verb was specified.
    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case 
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this thread.
            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            // Our ResultReceiver allows us to communicate back the results to the caller. This
            // class has a method named send() that can send back a code and a Bundle
            // of data. ResultReceiver and IntentService abstract away all the IPC code
            // we would need to write to normally make this work.
            if (responseEntity != null) {
                Bundle resultData = new Bundle();
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                receiver.send(statusCode, resultData);
            } else {
                receiver.send(statusCode, null);
            }
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e);
        receiver.send(0, null);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        receiver.send(0, null);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    }
}

From source file:io.teak.sdk.GooglePlay.java

private JSONObject querySkuDetails(String itemType, String sku) {
    try {//  ww  w . j a v  a  2  s. c  o  m
        ArrayList<String> skuList = new ArrayList<>();
        skuList.add(sku);
        Class<?> cls = Class.forName("com.android.vending.billing.IInAppBillingService");
        Method m = cls.getMethod("getSkuDetails", int.class, String.class, String.class, Bundle.class);

        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList);

        Bundle skuDetails = (Bundle) m.invoke(mService, 3, mContext.getPackageName(), itemType, querySkus);

        if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
            int response = getResponseCodeFromBundle(skuDetails);
            if (response != BILLING_RESPONSE_RESULT_OK) {
                Log.e(LOG_TAG, "getSkuDetails() failed: " + response);
                return null;
            } else {
                Log.e(LOG_TAG, "getSkuDetails() returned a bundle with neither an error nor a detail list.");
                return null;
            }
        }

        ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST);

        if (responseList != null && responseList.size() == 1) {
            JSONObject ret = new JSONObject(responseList.get(0));
            if (Teak.isDebug) {
                Log.d(LOG_TAG, "SKU Details: " + ret.toString(2));
            }
            return ret;
        } else {
            Log.e(LOG_TAG, "Mismatched input/output length for getSkuDetails().");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Reflection error: " + Log.getStackTraceString(e));
        Teak.sdkRaven.reportException(e);
    }

    return null;
}