Example usage for android.os Bundle getBundle

List of usage examples for android.os Bundle getBundle

Introduction

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

Prototype

@Nullable
public Bundle getBundle(@Nullable String key) 

Source Link

Document

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Usage

From source file:at.wada811.android.dialogfragments.AbstractDialogFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    Dialog dialog = getDialog();/*from   w  ww.  j  av a 2s . c om*/
    if (dialog == null) {
        throw new NullPointerException("Dialog is null! #onCreateDialog must not return null.");
    }
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        isCanceledOnTouchOutside = savedInstanceState.getInt(CANCELED_TOUCH_OUTSIDE, VALUE_NULL);
        useOnShowListener = savedInstanceState.getBoolean(SHOW_LISTENER);
        useOnCancelListener = savedInstanceState.getBoolean(CANCEL_LISTENER);
        useOnDismissListener = savedInstanceState.getBoolean(DISMISS_LISTENER);
        useOnKeyListener = savedInstanceState.getBoolean(KEY_LISTENER);
        extra = savedInstanceState.getBundle(EXTRA);
    }
    if (isCanceledOnTouchOutside != VALUE_NULL) {
        dialog.setCanceledOnTouchOutside(isCanceledOnTouchOutside == VALUE_TRUE);
    }
    if (useOnShowListener) {
        setOnShowListener(dialog);
    }
    if (useOnCancelListener) {
        setOnCancelListener(dialog);
    }
    if (useOnDismissListener) {
        setOnDismissListener(dialog);
    }
    if (useOnKeyListener) {
        setOnKeyListener(dialog);
    }
}

From source file:com.antew.redditinpictures.library.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    Uri action = intent.getData();/*from   w w w. j a  v  a2 s  .  co m*/
    Bundle extras = intent.getExtras();

    if (extras == null || action == null) {
        Ln.e("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);
    RequestCode requestCode = (RequestCode) extras.getSerializable(EXTRA_REQUEST_CODE);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    String cookie = extras.getString(EXTRA_COOKIE);
    String userAgent = extras.getString(EXTRA_USER_AGENT);

    // Items in this bundle are simply passed on in onRequestComplete
    Bundle passThrough = extras.getBundle(EXTRA_PASS_THROUGH);

    HttpEntity responseEntity = null;
    Intent result = new Intent(Constants.Broadcast.BROADCAST_HTTP_FINISHED);
    result.putExtra(EXTRA_PASS_THROUGH, passThrough);
    Bundle resultData = new Bundle();

    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) {
            DefaultHttpClient client = new DefaultHttpClient();

            // GZip requests
            // antew on 3/12/2014 - Disabling GZIP for now, need to figure this CloseGuard error:
            // 03-12 21:02:09.248    9674-9683/com.antew.redditinpictures.pro E/StrictMode A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
            //         java.lang.Throwable: Explicit termination method 'end' not called
            // at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            // at java.util.zip.Inflater.<init>(Inflater.java:82)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:96)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81)
            // at com.antew.redditinpictures.library.service.RESTService$GzipDecompressingEntity.getContent(RESTService.java:346)
            client.addRequestInterceptor(getGzipRequestInterceptor());
            client.addResponseInterceptor(getGzipResponseInterceptor());

            if (cookie != null) {
                request.addHeader("Cookie", cookie);
            }

            if (userAgent != null) {
                request.addHeader("User-Agent", Constants.Reddit.USER_AGENT);
            }

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Ln.d("Executing request: %s %s ", 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);

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

            if (responseEntity != null) {
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                resultData.putSerializable(EXTRA_REQUEST_CODE, requestCode);
                resultData.putInt(EXTRA_STATUS_CODE, statusCode);
                result.putExtra(EXTRA_BUNDLE, resultData);

                onRequestComplete(result);
            } else {
                onRequestFailed(result, statusCode);
            }
        }
    } catch (URISyntaxException e) {
        Ln.e(e, "URI syntax was incorrect. %s %s ", verbToString(verb), action.toString());
        onRequestFailed(result, 0);
    } catch (UnsupportedEncodingException e) {
        Ln.e(e, "A UrlEncodedFormEntity was created with an unsupported encoding.");
        onRequestFailed(result, 0);
    } catch (ClientProtocolException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } catch (IOException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } finally {
        if (responseEntity != null) {
            try {
                responseEntity.consumeContent();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.facebook.internal.BundleJSONConverterTests.java

@SmallTest
public void testSimpleValues() throws JSONException {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1st");
    arrayList.add("2nd");
    arrayList.add("third");

    Bundle innerBundle1 = new Bundle();
    innerBundle1.putInt("inner", 1);

    Bundle innerBundle2 = new Bundle();
    innerBundle2.putString("inner", "2");
    innerBundle2.putStringArray("deep list", new String[] { "7", "8" });

    innerBundle1.putBundle("nested bundle", innerBundle2);

    Bundle b = new Bundle();
    b.putBoolean("boolValue", true);
    b.putInt("intValue", 7);
    b.putLong("longValue", 5000000000l);
    b.putDouble("doubleValue", 3.14);
    b.putString("stringValue", "hello world");
    b.putStringArray("stringArrayValue", new String[] { "first", "second" });
    b.putStringArrayList("stringArrayListValue", arrayList);
    b.putBundle("nested", innerBundle1);

    JSONObject json = BundleJSONConverter.convertToJSON(b);
    assertNotNull(json);/*from   w w  w. j a  v  a2 s .  co m*/

    assertEquals(true, json.getBoolean("boolValue"));
    assertEquals(7, json.getInt("intValue"));
    assertEquals(5000000000l, json.getLong("longValue"));
    assertEquals(3.14, json.getDouble("doubleValue"));
    assertEquals("hello world", json.getString("stringValue"));

    JSONArray jsonArray = json.getJSONArray("stringArrayValue");
    assertEquals(2, jsonArray.length());
    assertEquals("first", jsonArray.getString(0));
    assertEquals("second", jsonArray.getString(1));

    jsonArray = json.getJSONArray("stringArrayListValue");
    assertEquals(3, jsonArray.length());
    assertEquals("1st", jsonArray.getString(0));
    assertEquals("2nd", jsonArray.getString(1));
    assertEquals("third", jsonArray.getString(2));

    JSONObject innerJson = json.getJSONObject("nested");
    assertEquals(1, innerJson.getInt("inner"));
    innerJson = innerJson.getJSONObject("nested bundle");
    assertEquals("2", innerJson.getString("inner"));

    jsonArray = innerJson.getJSONArray("deep list");
    assertEquals(2, jsonArray.length());
    assertEquals("7", jsonArray.getString(0));
    assertEquals("8", jsonArray.getString(1));

    Bundle finalBundle = BundleJSONConverter.convertToBundle(json);
    assertNotNull(finalBundle);

    assertEquals(true, finalBundle.getBoolean("boolValue"));
    assertEquals(7, finalBundle.getInt("intValue"));
    assertEquals(5000000000l, finalBundle.getLong("longValue"));
    assertEquals(3.14, finalBundle.getDouble("doubleValue"));
    assertEquals("hello world", finalBundle.getString("stringValue"));

    List<String> stringList = finalBundle.getStringArrayList("stringArrayValue");
    assertEquals(2, stringList.size());
    assertEquals("first", stringList.get(0));
    assertEquals("second", stringList.get(1));

    stringList = finalBundle.getStringArrayList("stringArrayListValue");
    assertEquals(3, stringList.size());
    assertEquals("1st", stringList.get(0));
    assertEquals("2nd", stringList.get(1));
    assertEquals("third", stringList.get(2));

    Bundle finalInnerBundle = finalBundle.getBundle("nested");
    assertEquals(1, finalInnerBundle.getInt("inner"));
    finalBundle = finalInnerBundle.getBundle("nested bundle");
    assertEquals("2", finalBundle.getString("inner"));

    stringList = finalBundle.getStringArrayList("deep list");
    assertEquals(2, stringList.size());
    assertEquals("7", stringList.get(0));
    assertEquals("8", stringList.get(1));
}

From source file:org.mariotaku.twidere.fragment.DMConversationFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    mService = getApplication().getServiceInterface();

    final LazyImageLoader imageloader = ((TwidereApplication) getActivity().getApplication())
            .getProfileImageLoader();//from w w w.  java 2s  . co m
    mAdapter = new DirectMessagesConversationAdapter(getActivity(), imageloader);
    mListView.setAdapter(mAdapter);
    mListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
    mListView.setStackFromBottom(true);
    mListView.setOnItemClickListener(this);
    mListView.setOnItemLongClickListener(this);
    final Bundle args = savedInstanceState == null ? getArguments()
            : savedInstanceState.getBundle(INTENT_KEY_DATA);
    if (args != null) {
        mArguments.putAll(args);
    }
    getLoaderManager().initLoader(0, mArguments, this);

    mEditText.addTextChangedListener(this);
    final String text = savedInstanceState != null ? savedInstanceState.getString(INTENT_KEY_TEXT) : null;
    if (text != null) {
        mEditText.setText(text);
    }

    mUserAutoCompleteAdapter = new UserAutoCompleteAdapter(getActivity());

    mEditScreenName.addTextChangedListener(mScreenNameTextWatcher);
    mEditScreenName.setAdapter(mUserAutoCompleteAdapter);

    mSendButton.setOnClickListener(this);
    mSendButton.setEnabled(false);
    mScreenNameConfirmButton.setOnClickListener(this);
    mScreenNameConfirmButton.setEnabled(false);
}

From source file:com.tct.fw.ex.photo.fragments.PhotoViewFragment.java

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

    final Bundle bundle = getArguments();
    if (bundle == null) {
        return;//ww w .j av a2  s  .  c o  m
    }
    mIntent = bundle.getParcelable(ARG_INTENT);
    mDisplayThumbsFullScreen = mIntent.getBooleanExtra(Intents.EXTRA_DISPLAY_THUMBS_FULLSCREEN, false);

    mPosition = bundle.getInt(ARG_POSITION);
    mOnlyShowSpinner = bundle.getBoolean(ARG_SHOW_SPINNER);
    mProgressBarNeeded = true;

    if (savedInstanceState != null) {
        final Bundle state = savedInstanceState.getBundle(STATE_INTENT_KEY);
        if (state != null) {
            mIntent = new Intent().putExtras(state);
        }
    }

    if (mIntent != null) {
        mResolvedPhotoUri = mIntent.getStringExtra(Intents.EXTRA_RESOLVED_PHOTO_URI);
        mThumbnailUri = mIntent.getStringExtra(Intents.EXTRA_THUMBNAIL_URI);
        mWatchNetworkState = mIntent.getBooleanExtra(Intents.EXTRA_WATCH_NETWORK, false);
    }
}

From source file:app.presentation.foundation.views.BaseActivity.java

private void configureFragment() {
    Bundle bundle = getIntent().getExtras();
    if (bundle == null || bundle.getSerializable(Behaviour.FRAGMENT_CLASS_KEY) == null) {
        Log.w(BaseActivity.class.getSimpleName(),
                "When using " + BaseActivity.class.getSimpleName() + " you could supply"
                        + " a fragment which extends from " + BaseFragment.class.getSimpleName()
                        + " by extra argument in the intent" + " as value and " + Behaviour.FRAGMENT_CLASS_KEY
                        + " as key, but a <FrameLayout android:id=\"@id/fl_fragment\" .../>"
                        + " will be mandatory in your activity layout.");
        return;//from   w  w w  . j  av a  2 s .co m
    }

    Serializable serializable = bundle.getSerializable(Behaviour.FRAGMENT_CLASS_KEY);
    Class<BaseFragment> clazz = (Class<BaseFragment>) serializable;

    BaseFragment baseFragment = replaceFragment(clazz);
    Bundle bundleFragment = bundle.getBundle(Behaviour.BUNDLE_FOR_FRAGMENT);
    baseFragment.setArguments(bundleFragment);
}

From source file:com.apptentive.android.sdk.ApptentiveInternal.java

/**
 * <p>Internal use only.</p>
 * This bundle could be any bundle sent to us by a push Intent from any supported platform. For that reason, it needs to be checked in multiple ways.
 *
 * @param pushBundle a Bundle, or null./* www  .  ja  va  2s  . co  m*/
 * @return a String, or null.
 */
static String getApptentivePushNotificationData(Bundle pushBundle) {
    if (pushBundle != null) {
        if (pushBundle.containsKey(PUSH_EXTRA_KEY_PARSE)) { // Parse
            ApptentiveLog.v("Got a Parse Push.");
            String parseDataString = pushBundle.getString(PUSH_EXTRA_KEY_PARSE);
            if (parseDataString == null) {
                ApptentiveLog.e("com.parse.Data is null.");
                return null;
            }
            try {
                JSONObject parseJson = new JSONObject(parseDataString);
                return parseJson.optString(APPTENTIVE_PUSH_EXTRA_KEY, null);
            } catch (JSONException e) {
                ApptentiveLog.e("com.parse.Data is corrupt: %s", parseDataString);
                return null;
            }
        } else if (pushBundle.containsKey(PUSH_EXTRA_KEY_UA)) { // Urban Airship
            ApptentiveLog.v("Got an Urban Airship push.");
            Bundle uaPushBundle = pushBundle.getBundle(PUSH_EXTRA_KEY_UA);
            if (uaPushBundle == null) {
                ApptentiveLog.e("Urban Airship push extras bundle is null");
                return null;
            }
            return uaPushBundle.getString(APPTENTIVE_PUSH_EXTRA_KEY);
        } else if (pushBundle.containsKey(APPTENTIVE_PUSH_EXTRA_KEY)) { // All others
            // Straight FCM / GCM / SNS, or nested
            ApptentiveLog.v("Found apptentive push data.");
            return pushBundle.getString(APPTENTIVE_PUSH_EXTRA_KEY);
        } else {
            ApptentiveLog.e("Got an unrecognizable push.");
        }
    }
    ApptentiveLog.e("Push bundle was null.");
    return null;
}

From source file:com.dwdesign.tweetings.fragment.DMConversationFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mApplication = getApplication();/*from w  w  w . j  a v a 2s  .co m*/
    mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    mService = getServiceInterface();

    mAdapter = new DirectMessagesConversationAdapter(getActivity());
    mListView.setAdapter(mAdapter);
    mListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
    mListView.setStackFromBottom(true);
    mListView.setOnItemClickListener(this);
    mListView.setOnItemLongClickListener(this);
    final Bundle args = savedInstanceState == null ? getArguments()
            : savedInstanceState.getBundle(INTENT_KEY_DATA);
    if (args != null) {
        mArguments.putAll(args);
    }
    getLoaderManager().initLoader(0, mArguments, this);

    if (mPreferences.getBoolean(PREFERENCE_KEY_QUICK_SEND, false)) {
        mEditText.setOnEditorActionListener(this);
    }

    mEditText.addTextChangedListener(this);
    final String text = savedInstanceState != null ? savedInstanceState.getString(INTENT_KEY_TEXT) : null;
    if (text != null) {
        mEditText.setText(text);
    }

    mAccountsAdapter = new AccountsAdapter(getActivity());
    mAccountSelector.setAdapter(mAccountsAdapter);
    mAccountSelector.setOnItemSelectedListener(this);

    mUserAutoCompleteAdapter = new UserAutoCompleteAdapter(getActivity());

    mEditScreenName.addTextChangedListener(mScreenNameTextWatcher);
    mEditScreenName.setAdapter(mUserAutoCompleteAdapter);

    mSendButton.setOnClickListener(this);
    mSendButton.setEnabled(false);
    mScreenNameConfirmButton.setOnClickListener(this);
    mScreenNameConfirmButton.setEnabled(false);
    mTextCount = (TextView) getActivity().findViewById(R.id.text_count);
}

From source file:org.cobaltians.cobalt.activities.CobaltActivity.java

public void popTo(String controller, String page, JSONObject data) {
    Intent popToIntent = Cobalt.getInstance(this).getIntentForController(controller, page);

    if (popToIntent != null) {
        Bundle popToExtras = popToIntent.getBundleExtra(Cobalt.kExtras);
        String popToActivityClassName = popToExtras.getString(Cobalt.kActivity);

        try {/*www  .  ja  v a 2 s .c o m*/
            Class<?> popToActivityClass = Class.forName(popToActivityClassName);

            boolean popToControllerFound = false;
            int popToControllerIndex = -1;

            for (int i = sActivitiesArrayList.size() - 1; i >= 0; i--) {
                Activity oldActivity = sActivitiesArrayList.get(i);
                Class<?> oldActivityClass = oldActivity.getClass();

                Bundle oldBundle = oldActivity.getIntent().getExtras();
                Bundle oldExtras = (oldBundle != null) ? oldBundle.getBundle(Cobalt.kExtras) : null;
                String oldPage = (oldExtras != null) ? oldExtras.getString(Cobalt.kPage) : null;

                if (oldPage == null && CobaltActivity.class.isAssignableFrom(oldActivityClass)) {
                    Fragment fragment = ((CobaltActivity) oldActivity).getSupportFragmentManager()
                            .findFragmentById(((CobaltActivity) oldActivity).getFragmentContainerId());
                    if (fragment != null) {
                        oldExtras = fragment.getArguments();
                        oldPage = (oldExtras != null) ? oldExtras.getString(Cobalt.kPage) : null;
                    }
                }

                if (popToActivityClass.equals(oldActivityClass) && (!CobaltActivity.class
                        .isAssignableFrom(oldActivityClass)
                        || (CobaltActivity.class.isAssignableFrom(oldActivityClass) && page.equals(oldPage)))) {
                    popToControllerFound = true;
                    popToControllerIndex = i;
                    ((CobaltActivity) oldActivity).setDataNavigation(data);
                    break;
                }
            }

            if (popToControllerFound) {
                while (popToControllerIndex + 1 < sActivitiesArrayList.size()) {
                    sActivitiesArrayList.get(popToControllerIndex + 1).finish();
                }
            } else if (Cobalt.DEBUG)
                Log.w(Cobalt.TAG, TAG + " - popTo: controller " + controller
                        + (page == null ? "" : " with page " + page) + " not found in history. Abort.");
        } catch (ClassNotFoundException exception) {
            exception.printStackTrace();
        }
    } else if (Cobalt.DEBUG)
        Log.e(Cobalt.TAG, TAG + " - popTo: unable to pop to null controller");
}

From source file:nz.ac.auckland.lablet.script.ScriptRunnerActivity.java

/**
 * Extracts the user answers from a bundle and saves them to a file.
 *
 * @param bundle the top-level (script-level) bundle of data
 * @param fileWriter the FileWriter object in which to write user answers
 * @return true if everything is written successfully; false otherwise
 *///  www  . j av  a  2 s .  co  m
private boolean saveUserAnswersToFile(@Nullable Bundle bundle, @Nullable FileWriter fileWriter) {
    if (bundle == null || fileWriter == null) {
        return false;
    }

    try {
        // write timestamp and script name to file
        fileWriter.write((new Date()).toString() + "\n");
        fileWriter.write(bundle.getString("script_name", "unknown_script") + "\n\n");

        int i = 0;
        Bundle sheet;
        Bundle child;

        // for all sheets in bundle ("0", "1", "2", ...)
        while ((sheet = bundle.getBundle(Integer.toString(i++))) != null) {
            int j = 0;
            int k = 0;
            boolean sheet_label_printed = false;

            // for all child objects ("child0", "child1", "child2", ...)
            while ((child = sheet.getBundle("child" + Integer.toString(j++))) != null) {
                String question;
                String answer;

                // if child has a "question" and "answer" field
                if ((question = child.getString("question")) != null
                        && (answer = child.getString("answer")) != null) {

                    // print sheet title if not printed yet
                    if (!sheet_label_printed) {
                        fileWriter.write("Sheet" + Integer.toString(i - 1) + "\n--------\n");
                        sheet_label_printed = true;
                    }

                    // print question
                    fileWriter.write(String.format(Locale.US, "Q%d: %s\n", ++k, question));

                    // print answer
                    fileWriter.write(String.format(Locale.US, "%s\n\n", answer));
                }
            }
        }
    } catch (IOException e) {
        // ERROR
        Log.e(TAG, "Error: ", e);
        Log.e(TAG, "Could not write user answers to file: " + fileWriter.toString());
        try {
            fileWriter.close();
        } catch (IOException e1) {
            Log.w(TAG, "Error: ", e1);
            Log.w(TAG, "Could not close user answer file: " + fileWriter.toString());
        }
        return false;
    }
    try {
        // flush and close file with user answers
        fileWriter.close();
    } catch (IOException e) {
        Log.w(TAG, "Error: ", e);
        Log.w(TAG, "Could not close user answer file: " + fileWriter.toString());
    }

    // SUCCESS
    Log.i(TAG, "User answer saved successfully to: " + fileWriter.toString());
    return true;
}