Example usage for android.os Bundle getParcelable

List of usage examples for android.os Bundle getParcelable

Introduction

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

Prototype

@Nullable
public <T extends Parcelable> T getParcelable(@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:android.support.car.app.CarFragmentActivity.java

/**
 * Perform initialization of all fragments and loaders.
 *///from w w w.  j a v a  2 s  .  c  o m
@SuppressWarnings("deprecation")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    mFragments.attachHost(null /*parent*/);

    super.onCreate(savedInstanceState);

    NonConfigurationInstances nc = (NonConfigurationInstances) getLastNonConfigurationInstance();
    if (nc != null) {
        mFragments.restoreLoaderNonConfig(nc.loaders);
    }
    if (savedInstanceState != null) {
        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, nc != null ? nc.fragments : null);
    }
    mFragments.dispatchCreate();
}

From source file:co.ceryle.radiorealbutton.library.RadioRealButtonGroup.java

@Override
protected void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        state = bundle.getParcelable("state");
        int position = bundle.getInt("position");

        if (lastPosition != position) {
            if (animationType == ANIM_TRANSLATE_X) {
                if (initialPosition != -1)
                    v_selectors.get(initialPosition).setVisibility(INVISIBLE);
                v_selectors.get(position).setVisibility(VISIBLE);
                lastPosition = initialPosition = position;
            }/*www . j av a2s . c o  m*/
            setPosition(position, false);
        }
    }
    super.onRestoreInstanceState(state);
}

From source file:android.com.example.contactslist.ui.ContactDetailFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // If not being created from a previous state
    if (savedInstanceState == null) {
        // Sets the argument extra as the currently displayed contact
        setContact(getArguments() != null ? (Uri) getArguments().getParcelable(EXTRA_CONTACT_URI) : null);
    } else {/*  w  w w  . ja  v  a 2  s.com*/
        // If being recreated from a saved state, sets the contact from the incoming
        // savedInstanceState Bundle
        setContact((Uri) savedInstanceState.getParcelable(EXTRA_CONTACT_URI));
    }
}

From source file:com.kreggysoft.Billing.util.IabHelper.java

/**
 * Initiate the UI flow for an in-app purchase. Call this method to initiate
 * an in-app purchase, which will involve bringing up the Google Play
 * screen. The calling activity will be paused while the user interacts with
 * Google Play, and the result will be delivered via the activity's
 * {@link android.app.Activity#onActivityResult} method, at which point you
 * must call this object's {@link #handleActivityResult} method to continue
 * the purchase flow. This method MUST be called from the UI thread of the
 * Activity.//  w w w .j ava  2s  .  c o m
 * 
 * @param act
 *            The calling activity.
 * @param sku
 *            The sku of the item to purchase.
 * @param requestCode
 *            A request code (to differentiate from other responses -- as in
 *            {@link android.app.Activity#startActivityForResult}).
 * @param listener
 *            The listener to notify when the purchase process finishes
 * @param extraData
 *            Extra data (developer payload), which will be returned with
 *            the purchase data when the purchase completes. This extra data
 *            will be permanently bound to that purchase and will always be
 *            returned when the purchase is queried.
 */
public void launchPurchaseFlow(Activity act, String sku, int requestCode,
        OnIabPurchaseFinishedListener listener, String extraData) {
    checkSetupDone("launchPurchaseFlow");
    flagStartAsync("launchPurchaseFlow");
    IabResult result;

    try {
        logDebug("Constructing buy intent for " + sku);
        Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, ITEM_TYPE_INAPP,
                extraData);
        int response = getResponseCodeFromBundle(buyIntentBundle);
        PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
        if (response != BILLING_RESPONSE_RESULT_OK) {
            logError("Unable to buy item, Error response: " + getResponseDesc(response));

            result = new IabResult(response, "Unable to buy item");
            if (listener != null)
                listener.onIabPurchaseFinished(result, null);

        }
        if (pendingIntent == null) {
            flagEndAsync();
            return;
        }

        logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
        mRequestCode = requestCode;
        mPurchaseListener = listener;
        // if (pendingIntent!=null)
        act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(),
                Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
    } catch (SendIntentException e) {
        logError("SendIntentException while launching purchase flow for sku " + sku);
        e.printStackTrace();

        result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
        if (listener != null)
            listener.onIabPurchaseFinished(result, null);
    } catch (RemoteException e) {
        logError("RemoteException while launching purchase flow for sku " + sku);
        e.printStackTrace();

        result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
        if (listener != null)
            listener.onIabPurchaseFinished(result, null);
    }
}

From source file:ca.rmen.android.scrumchatter.main.MainActivity.java

/**
 * The user tapped on the OK button on a dialog in which s/he entered text.
 *
 * @param actionId the action id which was provided to the {@link DialogFragmentFactory} when creating the dialog.
 * @param input    the text entered by the user.
 * @param extras   any extras which were provided to the {@link DialogFragmentFactory} when creating the dialog.
 * @see ca.rmen.android.scrumchatter.dialog.InputDialogFragment.DialogInputListener#onInputEntered(int, java.lang.String, android.os.Bundle)
 *//*ww w . j  a  va 2 s.c o m*/
@Override
public void onInputEntered(int actionId, String input, Bundle extras) {
    Log.v(TAG, "onInputEntered: actionId = " + actionId + ", input = " + input + ", extras = " + extras);
    if (actionId == R.id.fab_new_member) {
        long teamId = extras.getLong(Teams.EXTRA_TEAM_ID);
        mMembers.createMember(teamId, input);
    } else if (actionId == R.id.action_rename_member) {
        long memberId = extras.getLong(Members.EXTRA_MEMBER_ID);
        mMembers.renameMember(memberId, input);
    } else if (actionId == R.id.action_team) {
        mTeams.createTeam(input);
    } else if (actionId == R.id.action_team_rename) {
        Uri teamUri = extras.getParcelable(Teams.EXTRA_TEAM_URI);
        mTeams.renameTeam(teamUri, input);
    }
}

From source file:br.liveo.searchliveo.SearchCardLiveo.java

@Override
public void onRestoreInstanceState(Parcelable state) {

    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        this.setActive(bundle.getBoolean(STATE_TO_SAVE));

        String text = bundle.getString(SEARCH_TEXT, "");
        if (!text.trim().equals("")) {
            mEdtSearch.setText(text);//from   ww  w  . j  a v  a  2s  . c o m
        }

        if (this.isActive()) {
            show();
        }

        state = bundle.getParcelable(INSTANCE_STATE);
    }

    super.onRestoreInstanceState(state);
}

From source file:com.chess.genesis.engine.GameState.java

@Override
public boolean handleMessage(final Message msg) {
    try {/*  ww  w . j a  v  a2s .  co  m*/
        switch (msg.what) {
        case GenEngine.MSG:
        case RegEngine.MSG:
            final Bundle bundle = (Bundle) msg.obj;

            if (bundle.getLong("time") == 0) {
                cpu.setBoard(board);
                new Thread(cpu).start();
                return true;
            } else if (activity.isFinishing()) {
                // activity is gone, so give up!
                return true;
            }
            currentMove();

            final Move tmove = bundle.getParcelable("move");
            final Move move = board.newMove();
            if (board.validMove(tmove, move))
                applyMove(move, true, true);
            break;
        case CpuTimeDialog.MSG:
            final PrefEdit pref = new PrefEdit(activity);
            pref.putInt(R.array.pf_cputime, (Integer) msg.obj);
            pref.commit();
            cpu.setTime((Integer) msg.obj);
            break;
        case NetworkClient.GAME_DRAW:
        case NetworkClient.SUBMIT_MOVE:
            JSONObject json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                undoMove();
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText("Checking Game Status");

            net.game_status(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case ResignConfirm.MSG:
            progress.setText("Sending Resignation");

            net.resign_game(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case NudgeConfirm.MSG:
            progress.setText("Sending Nudge");

            net.nudge_game(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case IdleResignConfirm.MSG:
            progress.setText("Sending Idle Resign");

            net.idle_resign(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case DrawDialog.MSG:
        case AcceptDrawDialog.MSG:
            final String value = (String) msg.obj;
            progress.setText("Sending Draw");

            net.game_draw(settings.getString("gameid"), value);
            new Thread(net).start();
            break;
        case PawnPromoteDialog.MSG:
            applyMove((RegMove) msg.obj, true, true);
            break;
        case NetworkClient.RESIGN_GAME:
        case NetworkClient.IDLE_RESIGN:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText("Resignation Sent");

            net.game_status(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case NetworkClient.NUDGE_GAME:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error"))
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
            progress.remove();
            break;
        case NetworkClient.GAME_STATUS:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            final int status = Enums.GameStatus(json.getString("status"));

            settings.putString("status", String.valueOf(status));

            final GameDataDB db = new GameDataDB(activity);
            db.updateOnlineGame(json);
            db.close();
            GenesisNotifier.clearNotification(activity, GenesisNotifier.YOURTURN_NOTE);

            applyRemoteMove(json.getString("history"));
            if (status != Enums.ACTIVE) {
                if (Integer.parseInt(settings.getString("eventtype")) == Enums.INVITE) {
                    progress.remove();
                    ShowGameStats(json);
                    return true;
                }
                progress.setText("Retrieving Score");

                net.game_score(settings.getString("gameid"));
                new Thread(net).start();
            } else {
                progress.setText("Status Synced");
                progress.remove();
            }
            break;
        case NetworkClient.GAME_SCORE:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText("Score Loaded");
            progress.remove();

            ShowGameStats(json);
            break;
        case RematchConfirm.MSG:
            final Bundle data = (Bundle) msg.obj;
            progress.setText("Sending Newgame Request");

            final String opponent = data.getString("opp_name");
            final String color = Enums.ColorType(data.getInt("color"));
            final String gametype = Enums.GameType(data.getInt("gametype"));

            net.new_game(opponent, gametype, color);
            new Thread(net).start();
            break;
        case NetworkClient.NEW_GAME:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText(json.getString("reason"));
            progress.remove();
            break;
        }
        return true;
    } catch (final JSONException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.owncloud.android.ui.fragment.FileDetailFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    if (savedInstanceState != null) {
        mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
        mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
    }//  w  ww . j a  v a 2 s .  c o  m

    View view = null;
    view = inflater.inflate(mLayout, container, false);
    mView = view;

    if (mLayout == R.layout.file_details_fragment) {
        mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
        mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
        mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
        mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
        mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
        //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
        mPreview = (ImageView) mView.findViewById(R.id.fdPreview);
    }

    updateFileDetails(false);
    return view;
}

From source file:com.bangz.smartmute.LocationsMapFragment.java

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

    getMapAsync(this);
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addApi(LocationServices.API)
            .addOnConnectionFailedListener(this).addConnectionCallbacks(this).build();

    mGoogleApiClient.connect();//from ww w  . j ava  2 s. c  o  m

    if (savedInstanceState == null) {
        mLastLocation = PrefUtils.getLastLatLng(getActivity());
        mapInitState = 0;
    } else {

        // When subclass from MapFragment, do not use outState to save you state data which is
        // parcelable object, if you do, when in onCreate, onCreateView, onActivityCreated ,
        // saveInstance.getParcelable will get Class not found when unmarshalling from
        // java.lang.ClassNotFoundException. The cause may be google play service clean class
        // info in his saveInstance. to workaround this ,you add your all date to a new Bundle
        // and save this Bundle to outState in onSaveInstanceState method.

        // http://stackoverflow.com/a/15973603/1036923
        // in above site, the best answer is suggest use setArguments() when CTO new Bundle,
        // then onSaveInstanceState use getArguments()

        Bundle mybundle = savedInstanceState.getBundle(KEY_STATE_MYARGUMENT);
        mSavedMarkerExInfos = mybundle.getParcelableArrayList(KEY_STATE_MARKERS);
        mapInitState = mybundle.getInt(KEY_STATE_MAPINIT, 0);
        bLocationUpdated = mybundle.getBoolean(KEY_STATE_LOCATION_UPDATED, false);
        mLocationUpdateType = mybundle.getInt(KEY_STATE_LOCATION_UPDATE_TYPE);

        meiSelected = mybundle.getParcelable(KEY_STATE_SELECT_MARKER);
    }
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager.//w w w.ja v  a  2  s.  c o m
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}