Example usage for android.os Bundle putInt

List of usage examples for android.os Bundle putInt

Introduction

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

Prototype

public void putInt(@Nullable String key, int value) 

Source Link

Document

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

Usage

From source file:com.mirasense.scanditsdk.plugin.ScanditSDK.java

private void setOptionsOnBundle(JSONObject options, Bundle bundle) {
    @SuppressWarnings("unchecked")
    Iterator<String> iter = (Iterator<String>) options.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        Object obj = options.opt(key);
        if (obj != null) {
            if (obj instanceof Float) {
                bundle.putFloat(key.toLowerCase(), (Float) obj);
            } else if (obj instanceof Double) {
                bundle.putDouble(key.toLowerCase(), (Double) obj);
            } else if (obj instanceof Integer) {
                bundle.putInt(key.toLowerCase(), (Integer) obj);
            } else if (obj instanceof Boolean) {
                bundle.putBoolean(key.toLowerCase(), (Boolean) obj);
            } else if (obj instanceof String) {
                bundle.putString(key.toLowerCase(), (String) obj);
            }// w  w w  . j  a  va 2  s  .c  o m
        }
    }
}

From source file:org.anhonesteffort.flock.SubscriptionStripeFragment.java

private void handleVerifyCardAndPutToServer() {
    if (asyncTask != null)
        return;//from   www.j  av  a  2s .  c  o m

    asyncTask = new AsyncTask<Void, Void, Bundle>() {

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleVerifyCardAndPutToServer()");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        private String handleGetStripeCardTokenId(String cardNumber, String cardExpiration, String cardCVC)
                throws StripeException {
            String[] expiration = cardExpiration.split("/");
            Integer expirationMonth = Integer.valueOf(expiration[0]);
            Integer expirationYear;

            if (expiration[1].length() == 4)
                expirationYear = Integer.valueOf(expiration[1]);
            else
                expirationYear = Integer.valueOf(expiration[1]) + 2000;

            java.util.Map<String, Object> cardParams = new HashMap<String, Object>();
            java.util.Map<String, Object> tokenParams = new HashMap<String, Object>();

            cardParams.put("number", cardNumber.replace(" ", ""));
            cardParams.put("exp_month", expirationMonth);
            cardParams.put("exp_year", expirationYear);
            cardParams.put("cvc", cardCVC);

            tokenParams.put("card", cardParams);

            return Token.create(tokenParams, OwsRegistration.STRIPE_PUBLIC_KEY).getId();
        }

        private void handlePutStripeTokenToServer(String stripeTokenId)
                throws IOException, RegistrationApiException, CardException {
            RegistrationApi registrationApi = new RegistrationApi(subscriptionActivity);
            registrationApi.setStripeCard(subscriptionActivity.davAccount, stripeTokenId);
        }

        private void handleUpdateSubscriptionStore(String cardNumber, String cardExpiration)
                throws JsonProcessingException {
            String cardNoSpaces = cardNumber.replace(" ", "");
            String lastFour = cardNoSpaces.substring(cardNoSpaces.length() - 4);

            FlockCardInformation cardInformation = new FlockCardInformation(
                    subscriptionActivity.davAccount.getUserId(), lastFour, cardExpiration);

            StripePlan newStripePlan = new StripePlan(subscriptionActivity.davAccount.getUserId(), "nope");

            AccountStore.setLastChargeFailed(subscriptionActivity, false);
            AccountStore.setSubscriptionPlan(subscriptionActivity, newStripePlan);
            AccountStore.setAutoRenew(subscriptionActivity, true);
            AccountStore.setCardInformation(subscriptionActivity, Optional.of(cardInformation));
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();
            String cardNumber = ((TextView) subscriptionActivity.findViewById(R.id.card_number)).getText()
                    .toString();
            String cardExpiration = ((TextView) subscriptionActivity.findViewById(R.id.card_expiration))
                    .getText().toString();
            String cardCVC = ((TextView) subscriptionActivity.findViewById(R.id.card_cvc)).getText().toString();

            if (StringUtils.isEmpty(cardNumber) || cardNumber.contains("*")) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_NUMBER_INVALID);
                return result;
            }

            if (StringUtils.isEmpty(cardExpiration) || cardExpiration.split("/").length != 2) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_EXPIRATION_INVALID);
                return result;
            }

            if (StringUtils.isEmpty(cardCVC) || cardCVC.length() < 1) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_CVC_INVALID);
                return result;
            }

            try {

                String stripeTokenId = handleGetStripeCardTokenId(cardNumber, cardExpiration, cardCVC);
                handlePutStripeTokenToServer(stripeTokenId);
                handleUpdateSubscriptionStore(cardNumber, cardExpiration);

                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

            } catch (CardException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (StripeException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (RegistrationApiException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (JsonProcessingException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (IOException e) {
                ErrorToaster.handleBundleError(e, result);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            asyncTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS) {
                Toast.makeText(subscriptionActivity, R.string.card_verified_and_saved, Toast.LENGTH_LONG)
                        .show();
                handleUpdateUi();
            }

            else {
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
                handleUpdateUi();
            }
        }
    }.execute();
}

From source file:com.ferasinfotech.gwreader.ScreenSlidePageFragment.java

/**
 * Alternate Factory method for this fragment class. Constructs a new fragment for the given page number,
 * and HTML story element.//from  www .  j  a  va 2  s  .com
 */
public static ScreenSlidePageFragment create(int pageNumber, int numPages, org.jsoup.nodes.Element story) {
    int story_id = -1;
    String name = "";
    String summary = "";
    String headline = "";
    String cover_photo_url = "";
    String story_string = "";
    long createdAt;

    ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
    Bundle args = new Bundle();
    if (pageNumber == 0) {
        story_id = 0;
        name = "Grasswire Help";
        headline = "Usage Instructions";
        cover_photo_url = "android.resource://com.ferasinfotech.gwreader/" + R.drawable.gw_logo;
        summary = "Swipe right and left to read each story.\n\n"
                + "Scroll down to read facts and associated news items (tweets and links) for each story.\n\n"
                + "Tap on a news items within a story and you'll be able to follow web links, view tweets via the Twitter app, or watch videos.\n\n"
                + "A long press on a story's cover photo will launch the device browser to view or edit the story on the Grasswire mobile site.\n\n"
                + "A long press on the image above will launch the Grasswire main page.\n\n" + "App Version: "
                + BuildConfig.VERSION_NAME + "\n\n";
    } else {

        // doing a story page, Element 'story' is the story data

        Elements e_list;
        org.jsoup.nodes.Element tag;

        story_id = Integer.valueOf(story.attr("data-story-id"));
        e_list = story.getElementsByClass("feature__tag");
        tag = e_list.get(0);
        name = tag.text() + " (" + pageNumber + "/" + numPages + ")";
        e_list = story.getElementsByClass("story__summary");
        tag = e_list.get(0);
        summary = tag.html().replace("<br />", "\r");
        e_list = story.getElementsByClass("feature__text");
        tag = e_list.get(0);
        headline = tag.text();
        e_list = story.getElementsByClass("feature__image");
        tag = e_list.get(0);
        cover_photo_url = tag.attr("src");
        story_string = story.toString();

    }

    args.putInt(ARG_PAGE, pageNumber);
    args.putInt(ARG_STORY_ID, story_id);
    args.putString(ARG_TITLE, name);
    args.putString(ARG_SUMMARY, summary);
    args.putString(ARG_HEADLINE, headline);
    args.putString(ARG_COVER_PHOTO, cover_photo_url);
    args.putString(ARG_STORY_STRING, "<html><head></head><body>" + story_string + "</body></html>");
    fragment.setArguments(args);
    return fragment;
}

From source file:com.android.gallery3d.app.Gallery.java

private void startViewAction(Intent intent) {
    Boolean slideshow = intent.getBooleanExtra(EXTRA_SLIDESHOW, false);
    getStateManager().setLaunchGalleryOnTop(true);
    if (slideshow) {
        getActionBar().hide();//w  w  w . j  a va2s.c  o  m
        DataManager manager = getDataManager();
        Path path = manager.findPathByUri(intent.getData());
        if (path == null || manager.getMediaObject(path) instanceof MediaItem) {
            path = Path.fromString(manager.getTopSetPath(DataManager.INCLUDE_IMAGE));
        }
        Bundle data = new Bundle();
        data.putString(SlideshowPage.KEY_SET_PATH, path.toString());
        data.putBoolean(SlideshowPage.KEY_RANDOM_ORDER, true);
        data.putBoolean(SlideshowPage.KEY_REPEAT, true);
        getStateManager().startState(SlideshowPage.class, data);
    } else {
        Bundle data = new Bundle();
        DataManager dm = getDataManager();
        Uri uri = intent.getData();
        String contentType = getContentType(intent);
        if (contentType == null) {
            Toast.makeText(this, R.string.no_such_item, Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (uri == null) {
            int typeBits = GalleryUtils.determineTypeBits(this, intent);
            data.putInt(KEY_TYPE_BITS, typeBits);
            data.putString(AlbumSetPage.KEY_MEDIA_PATH, getDataManager().getTopSetPath(typeBits));
            getStateManager().setLaunchGalleryOnTop(true);
            getStateManager().startState(AlbumSetPage.class, data);
        } else if (contentType.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE)) {
            int mediaType = intent.getIntExtra(KEY_MEDIA_TYPES, 0);
            if (mediaType != 0) {
                uri = uri.buildUpon().appendQueryParameter(KEY_MEDIA_TYPES, String.valueOf(mediaType)).build();
            }
            Path setPath = dm.findPathByUri(uri);
            MediaSet mediaSet = null;
            if (setPath != null) {
                mediaSet = (MediaSet) dm.getMediaObject(setPath);
            }
            if (mediaSet != null) {
                if (mediaSet.isLeafAlbum()) {
                    data.putString(AlbumPage.KEY_MEDIA_PATH, setPath.toString());
                    getStateManager().startState(AlbumPage.class, data);
                } else {
                    data.putString(AlbumSetPage.KEY_MEDIA_PATH, setPath.toString());
                    getStateManager().startState(AlbumSetPage.class, data);
                }
            } else {
                startDefaultPage();
            }
        } else {
            Path itemPath = dm.findPathByUri(uri);
            Path albumPath = dm.getDefaultSetOf(itemPath);
            // TODO: Make this parameter public so other activities can reference it.
            boolean singleItemOnly = intent.getBooleanExtra("SingleItemOnly", false);
            if (!singleItemOnly && albumPath != null) {
                data.putString(PhotoPage.KEY_MEDIA_SET_PATH, albumPath.toString());
            }
            data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, itemPath.toString());
            getStateManager().startState(PhotoPage.class, data);
        }
    }
}

From source file:com.heightechllc.breakify.MainActivity.java

/**
 * Resets the CircleTimerView and reverts the Activity's UI to its initial state
 * @param isTimerComplete Whether the timer is complete
 *//*from w  w w . ja va 2s.c om*/
private void resetTimerUI(boolean isTimerComplete) {
    timerState = TIMER_STATE_STOPPED;

    // Reset the UI
    timeLbl.clearAnimation();
    stateLbl.clearAnimation();
    resetBtn.setVisibility(View.GONE);
    skipBtn.setVisibility(View.GONE);
    timeLbl.setText("");

    // Record the state we're about to reset from, in case the user chooses to undo
    Bundle undoStateBundle = new Bundle();
    if (isTimerComplete) {
        undoStateBundle.putLong("totalTime", 0);
        undoStateBundle.putLong("remainingTime", 0);
    } else {
        undoStateBundle.putLong("totalTime", circleTimer.getTotalTime());
        undoStateBundle.putLong("remainingTime", circleTimer.getRemainingTime());
    }
    undoStateBundle.putInt("workState", getWorkState());

    // Back to initial state
    setWorkState(WORK_STATE_WORKING);

    // Update the start / stop label
    startStopLbl.setText(R.string.start);
    startStopLbl.setVisibility(View.VISIBLE);

    circleTimer.stopIntervalAnimation();
    circleTimer.invalidate();

    // Remove record of total timer duration and the time remaining for the paused timer
    sharedPref.edit().remove("schedTotalTime").remove("pausedTimeRemaining").apply();

    // Create and show the undo bar
    showUndoBar(getString(R.string.reset_toast), undoStateBundle, new UndoBarController.UndoListener() {
        @Override
        public void onUndo(Parcelable parcelable) {
            if (parcelable == null)
                return;

            // Extract the saved state from the Parcelable
            Bundle undoStateBundle = (Bundle) parcelable;
            long prevTotalTime = undoStateBundle.getLong("totalTime");
            long prevRemainingTime = undoStateBundle.getLong("remainingTime");
            int prevWorkState = undoStateBundle.getInt("workState");
            if (prevTotalTime > 0 && prevRemainingTime > 0) {
                // Cause startTimer() to treat it like we're resuming (b/c we are)
                timerState = TIMER_STATE_PAUSED;
                setWorkState(prevWorkState);
                // Restore to the previous timer state, similar to how we restore a
                //  running timer from SharedPreferences in onCreate()
                circleTimer.setTotalTime(prevTotalTime);
                circleTimer.updateTimeLbl(prevRemainingTime);
                // Record the total duration, so we can resume if the activity is destroyed
                sharedPref.edit().putLong("schedTotalTime", prevTotalTime).apply();
                startTimer(prevRemainingTime);
            } else {
                // Means the timer was complete when resetTimerUI() was called, so we
                //  need to start the timer from the beginning of the next state
                if (prevWorkState == WORK_STATE_WORKING)
                    setWorkState(WORK_STATE_BREAKING);
                else
                    setWorkState(WORK_STATE_WORKING);
                startTimer();
            }
            // Analytics
            if (mixpanel != null)
                mixpanel.track("Timer reset undone", null);
        }
    });
}

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

@Override
public boolean onLongClick(final View view) {
    if (mUserList == null)
        return false;
    final boolean is_my_activated_account = isMyActivatedAccount(getActivity(), mUserId);
    if (!is_my_activated_account)
        return false;
    switch (view.getId()) {
    case R.id.name_container:
    case R.id.description_container:
        final Bundle args = new Bundle();
        args.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        args.putString(INTENT_KEY_LIST_NAME, mUserList.getName());
        args.putString(INTENT_KEY_DESCRIPTION, mUserList.getDescription());
        args.putString(INTENT_KEY_TITLE, getString(R.string.description));
        args.putBoolean(INTENT_KEY_IS_PUBLIC, mUserList.isPublic());
        args.putInt(INTENT_KEY_LIST_ID, mUserList.getId());
        mEditUserListDialogFragment.setArguments(args);
        mEditUserListDialogFragment.show(getFragmentManager(), "edit_user_list_details");
        return true;
    }/*from   www .  ja v  a  2  s . c  om*/
    return false;
}

From source file:ac.robinson.mediaphone.activity.NarrativeBrowserActivity.java

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putString(getString(R.string.extra_internal_id), mCurrentSelectedNarrativeId);
    if (mNarrativeAdapter != null) {
        // save horizontal scroll positions
        HashMap<String, Integer> scrollPositions = mNarrativeAdapter.getAdapterScrollPositions();
        if (scrollPositions != null) {
            for (String narrativeId : scrollPositions.keySet()) {
                savedInstanceState.putInt(narrativeId, scrollPositions.get(narrativeId));
            }//from   ww w  . j  a v a  2 s  .com
        }
    }
    // savedInstanceState.putInt(getString(R.string.extra_start_scrolled_to_end), mScrollNarrativesToEnd);
    super.onSaveInstanceState(savedInstanceState);
}

From source file:activities.Activity_Main.java

/** Called when the activity is first created. */
@Override//ww  w  .  j  a v a  2s .  co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myself = this;
    setContentView(R.layout.activity_home);

    SP_params = PreferenceManager.getDefaultSharedPreferences(this);
    SP_prefEditor = SP_params.edit();
    Tracer = tracerengine.getInstance(SP_params);

    //Added by Doume
    File storage = new File(Environment.getExternalStorageDirectory() + "/domodroid/.conf/");
    if (!storage.exists())
        storage.mkdirs();
    //Configure Tracer tool initial state
    File logpath = new File(Environment.getExternalStorageDirectory() + "/domodroid/.log/");
    if (!logpath.exists())
        logpath.mkdirs();

    String currlogpath = SP_params.getString("LOGNAME", "");
    if (currlogpath.equals("")) {
        //Not yet existing prefs : Configure debugging by default, to configure Tracer
        currlogpath = Environment.getExternalStorageDirectory() + "/domodroid/.log/";
        SP_prefEditor.putString("LOGPATH", currlogpath);
        SP_prefEditor.putString("LOGNAME", "Domodroid.txt");
        SP_prefEditor.putBoolean("SYSTEMLOG", false);
        SP_prefEditor.putBoolean("TEXTLOG", false);
        SP_prefEditor.putBoolean("SCREENLOG", false);
        SP_prefEditor.putBoolean("LOGCHANGED", true);
        SP_prefEditor.putBoolean("LOGAPPEND", false);
    } else {
        SP_prefEditor.putBoolean("LOGCHANGED", true); //To force Tracer to consider current settings
    }
    //prefEditor.putBoolean("SYSTEMLOG", false);      // For tests : no system logs....
    SP_prefEditor.putBoolean("SYSTEMLOG", true); // For tests : with system logs....

    SP_prefEditor.commit();

    Tracer.set_profile(SP_params);
    // Create .nomedia file, that will prevent Android image gallery from showing domodroid file
    String nomedia = Environment.getExternalStorageDirectory() + "/domodroid/.nomedia";
    try {
        if (!(new File(nomedia).exists())) {
            new FileOutputStream(nomedia).close();
        }
    } catch (Exception e) {
    }

    appname = (ImageView) findViewById(R.id.app_name);

    LoadSelections();

    // Prepare a listener to know when a sync dialog is closed...
    if (sync_listener == null) {
        sync_listener = new DialogInterface.OnDismissListener() {

            public void onDismiss(DialogInterface dialog) {

                Tracer.d(mytag, "sync dialog has been closed !");

                // Is it success or fail ?
                if (((Dialog_Synchronize) dialog).need_refresh) {
                    // Sync has been successful : Force to refresh current main view
                    Tracer.d(mytag, "sync dialog requires a refresh !");
                    reload = true; // Sync being done, consider shared prefs are OK
                    VG_parent.removeAllViews();
                    if (WU_widgetUpdate != null) {
                        WU_widgetUpdate.resync();
                    } else {
                        Tracer.i(mytag + ".onCreate", "WidgetUpdate is null startCacheengine!");
                        startCacheEngine();
                    }
                    Bundle b = new Bundle();
                    //Notify sync complete to parent Dialog
                    b.putInt("id", 0);
                    b.putString("type", "root");
                    Message msg = new Message();
                    msg.setData(b);
                    if (widgetHandler != null)
                        widgetHandler.sendMessage(msg); // That should force to refresh Views
                    /* */
                    if (WU_widgetUpdate != null) {
                        WU_widgetUpdate.Disconnect(0); //That should disconnect all opened widgets from cache engine
                        //widgetUpdate.dump_cache();   //For debug
                        dont_kill = true; // to avoid engines kill when onDestroy()
                    }
                    onResume();
                } else {
                    Tracer.d(mytag, "sync dialog end with no refresh !");

                }
                ((Dialog_Synchronize) dialog).need_refresh = false;
            }
        };
    }

    //update thread
    sbanim = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name2));
            } else if (msg.what == 1) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name3));
            } else if (msg.what == 2) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name1));
            } else if (msg.what == 3) {
                appname.setImageDrawable(getResources().getDrawable(R.drawable.app_name4));
            } else if (msg.what == 8000) {
                Tracer.e(mytag, "Request to display message : 8000");
                /*
                if(dialog_message == null) {
                   Create_message_box();
                }
                dialog_message.setMessage("Starting cache engine...");
                dialog_message.show();
                        
                */
            } else if (msg.what == 8999) {
                //Cache engine is ready for use....
                if (Tracer != null)
                    Tracer.e(mytag, "Cache engine has notified it's ready !");
                cache_ready = true;
                if (end_of_init_requested)
                    end_of_init();
                PG_dialog_message.dismiss();
            }
        }
    };

    //power management
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    this.PM_WakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "");
    this.PM_WakeLock.acquire();

    //titlebar
    final FrameLayout titlebar = (FrameLayout) findViewById(R.id.TitleBar);
    titlebar.setBackgroundDrawable(Gradients_Manager.LoadDrawable("title", 40));

    //Parent view
    VG_parent = (ViewGroup) findViewById(R.id.home_container);

    LL_house_map = new LinearLayout(this);
    LL_house_map
            .setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    LL_house_map.setOrientation(LinearLayout.HORIZONTAL);
    LL_house_map.setPadding(5, 5, 5, 5);

    house = new Basic_Graphical_zone(getApplicationContext(), 0, Graphics_Manager.Names_Agent(this, "House"),
            "", "house", 0, "", null);
    house.setPadding(0, 0, 5, 0);
    map = new Basic_Graphical_zone(getApplicationContext(), 0, Graphics_Manager.Names_Agent(this, "Map"), "",
            "map", 0, "", null);
    map.setPadding(5, 0, 0, 0);

    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT, 1.0f);

    house.setLayoutParams(param);
    house.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (SP_params.getBoolean("SYNC", false)) {
                loadWigets(0, "root");
                historyPosition++;
                history.add(historyPosition, new String[] { "0", "root" });
            } else {
                if (AD_notSyncAlert == null)
                    createAlert();
                AD_notSyncAlert.show();
            }
        }
    });

    map.setLayoutParams(param);
    map.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (SP_params.getBoolean("SYNC", false)) {
                //dont_freeze=true;      //To avoid WidgetUpdate engine freeze
                Tracer.w(mytag, "Before call to Map, Disconnect widgets from engine !");
                if (WU_widgetUpdate != null) {
                    WU_widgetUpdate.Disconnect(0); //That should disconnect all opened widgets from cache engine
                    //widgetUpdate.dump_cache();   //For debug
                    dont_kill = true; // to avoid engines kill when onDestroy()
                }
                INTENT_map = new Intent(Activity_Main.this, Activity_Map.class);
                Tracer.d(mytag, "Call to Map, run it now !");
                Tracer.Map_as_main = false;
                startActivity(INTENT_map);
            } else {
                if (AD_notSyncAlert == null)
                    createAlert();
                AD_notSyncAlert.show();
            }
        }
    });

    LL_house_map.addView(house);
    LL_house_map.addView(map);

    init_done = false;
    // Detect if it's the 1st use after installation...
    if (!SP_params.getBoolean("SPLASH", false)) {
        // Yes, 1st use !
        init_done = false;
        reload = false;
        if (backupprefs.exists()) {
            // A backup exists : Ask if reload it
            Tracer.v(mytag, "settings backup found after a fresh install...");

            DialogInterface.OnClickListener reload_listener = new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    Tracer.e(mytag, "Reload dialog returns : " + which);
                    if (which == dialog.BUTTON_POSITIVE) {
                        reload = true;
                    } else if (which == dialog.BUTTON_NEGATIVE) {
                        reload = false;
                    }
                    check_answer();
                    dialog.dismiss();
                }
            };
            dialog_reload = new AlertDialog.Builder(this);
            dialog_reload.setMessage(getText(R.string.home_reload));
            dialog_reload.setTitle(getText(R.string.reload_title));
            dialog_reload.setPositiveButton(getText(R.string.reloadOK), reload_listener);
            dialog_reload.setNegativeButton(getText(R.string.reloadNO), reload_listener);
            dialog_reload.show();
            init_done = false; //A choice is pending : Rest of init has to be completed...
        } else {
            //No settings backup found
            Tracer.v(mytag, "no settings backup found after fresh install...");
            end_of_init_requested = true;
            // open server config view
            Intent helpI = new Intent(Activity_Main.this, Preference.class);
            startActivity(helpI);
        }
    } else {
        // It's not the 1st use after fresh install
        // This method will be followed by 'onResume()'
        end_of_init_requested = true;
    }
    if (SP_params.getBoolean("SYNC", false)) {
        //A config exists and a sync as been done by past.
        if (WU_widgetUpdate == null) {
            Tracer.i(mytag + ".onCreate", "Params splach is false and WidgetUpdate is null startCacheengine!");
            startCacheEngine();
        }

    }

    Tracer.e(mytag, "OnCreate() complete !");
    // End of onCreate (UIThread)
}

From source file:gr.scify.newsum.ui.ViewActivity.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    final Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    outState.putInt(SELECTED_ITEM_BUNDLE_KEY, spinner.getSelectedItemPosition());
    super.onSaveInstanceState(outState);
}

From source file:ca.spencerelliott.mercury.Changesets.java

private synchronized void startThread() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //Create the thread that will process the incoming feed
    load_thread = new Thread() {
        @Override/*ww  w .ja v  a 2  s .  c  o m*/
        public void run() {
            changesets_list.clear();

            DatabaseHelper db_helper = DatabaseHelper.getInstance(getApplicationContext());
            EncryptionHelper encrypt_helper = EncryptionHelper.getInstance("DEADBEEF".toCharArray(),
                    new byte[] { 'L', 'O', 'L' });

            //Get the repository information from the local database
            Beans.RepositoryBean repo_type = db_helper.getRepository(repo_id, encrypt_helper);
            AtomHandler feed_handler = null;

            //Detect the type of repository and create a parser based on that
            switch (repo_type.getType()) {
            case Mercury.RepositoryTypes.HGSERVE:
                feed_handler = new HGWebAtomHandler();
                break;
            case Mercury.RepositoryTypes.GOOGLECODE:
                feed_handler = new GoogleCodeAtomHandler();
                break;
            case Mercury.RepositoryTypes.BITBUCKET:
                feed_handler = new BitbucketAtomHandler();
                break;
            case Mercury.RepositoryTypes.CODEPLEX:
                feed_handler = new CodePlexAtomHandler();
                break;
            }

            HttpURLConnection conn = null;
            boolean connected = false;

            try {
                // XXX We need to use our own factory to make all ssl certs work
                HttpsURLConnection.setDefaultSSLSocketFactory(NaiveSSLSocketFactory.getSocketFactory());

                String repo_url_string = (repo_type.getUrl().endsWith("/") || repo_type.getUrl().endsWith("\\")
                        ? feed_handler
                                .formatURL(repo_type.getUrl().substring(0, repo_type.getUrl().length() - 1))
                        : feed_handler.formatURL(repo_type.getUrl()));

                switch (repo_type.getType()) {
                case Mercury.RepositoryTypes.BITBUCKET:
                    //Only add the token if the user requested it
                    if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.TOKEN)
                        repo_url_string = repo_url_string + "?token=" + repo_type.getSSHKey();
                    break;
                }

                URL repo_url = new URL(repo_url_string);
                conn = (HttpURLConnection) repo_url.openConnection();

                //Check to see if the user enabled HTTP authentication
                if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.HTTP) {
                    //Get their username and password
                    byte[] decrypted_info = (repo_type.getUsername() + ":" + repo_type.getPassword())
                            .getBytes();

                    //Add the header to the http request
                    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBytes(decrypted_info));
                }
                conn.connect();
                connected = true;
            } catch (ClientProtocolException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("There was a problem with the HTTP protocol");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (IOException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("Server did not respond with a valid HTTP response");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (NullPointerException e3) {

            } catch (Exception e) {

            }

            BufferedReader reader = null;

            //Create a new reader based on the information retrieved
            if (connected) {
                try {
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Make sure both the feed handler and info loaded from the web are not null
            if (reader != null && feed_handler != null) {
                try {
                    Xml.parse(reader, feed_handler);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Stored beans in the devices database
            ArrayList<Beans.ChangesetBean> stored_beans = null;

            if (prefs.getBoolean("caching", false)) {
                long last_insert = db_helper.getHighestID(DatabaseHelper.DB_TABLE_CHANGESETS, repo_id);

                if (last_insert >= 0) {
                    //Get all of the stored changesets
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                    String rev_id = "";

                    //Try to find the revision id of the bean that has the id of the last inserted value
                    for (Beans.ChangesetBean b : stored_beans) {
                        if (b.getID() == last_insert) {
                            rev_id = b.getRevisionID();
                            break;
                        }
                    }

                    //Trim the list starting from this revision
                    feed_handler.trimStartingFromRevision(rev_id);
                }
            }

            //Create a new bundle for the progress
            Bundle progress_bundle = new Bundle();

            //Retreive all the beans from the handler
            ArrayList<Beans.ChangesetBean> beans = feed_handler.getAllChangesets();
            int bean_count = beans.size();

            //Store the amount of changesets
            progress_bundle.putInt("max", bean_count);

            //Create a new message and store the bundle and what type of message it is
            Message msg = new Message();
            msg.setData(progress_bundle);
            msg.what = SETUP_COUNT;
            list_handler.sendMessage(msg);

            //Add each of the beans to the list
            for (int i = 0; i < bean_count; i++) {
                String commit_text = beans.get(i).getTitle();
                Date commit_date = new Date(beans.get(i).getUpdated());
                changesets_list.add(createChangeset(
                        (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                        beans.get(i).getRevisionID() + " - " + commit_date.toLocaleString()));

                //Store the current progress of the changeset loading
                progress_bundle.putInt("progress", i);

                //Reuse the old message and send an update progress message
                msg = new Message();
                msg.setData(progress_bundle);
                msg.what = UPDATE_PROGRESS;
                list_handler.sendMessage(msg);
            }

            //Get the current count of changesets and the shared preferences
            long changeset_count = db_helper.getChangesetCount(repo_id);

            if (prefs.getBoolean("caching", false)) {
                //Get all of the stored beans from the device if not already done
                if (stored_beans == null)
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                //Add all the changesets from the device
                for (Beans.ChangesetBean b : stored_beans) {
                    changesets_list.add(createChangeset(
                            (b.getTitle().length() > 30 ? (b.getTitle().substring(0, 30)) + "..."
                                    : b.getTitle()),
                            b.getRevisionID() + " - " + new Date(b.getUpdated()).toLocaleString()));
                }

                //Reverse the list so the oldest changesets are stored first
                Collections.reverse(beans);

                //Iterate through each bean and add it to the device's database
                for (Beans.ChangesetBean b : beans) {
                    db_helper.insert(b, repo_id);
                }

                //Get the amount of changesets allowed to be stored on the device
                int max_changes = Integer.parseInt(prefs.getString("max_changesets", "-1"));

                //Delete the oldest changesets if too many have been stored
                if (changeset_count > max_changes) {
                    db_helper.deleteNumChangesets(repo_id, (changeset_count - max_changes));
                }
            } else if (changeset_count > 0) {
                //Since the user does not have caching enabled, delete the changesets
                db_helper.deleteAllChangesets(repo_id);
            }

            //Update the tables to the newest revision
            if (!beans.isEmpty())
                db_helper.updateLastRev(repo_id, beans.get(0).getRevisionID());

            //Add all of the data to the changeset list
            changesets_data.addAll(beans);

            if (prefs.getBoolean("caching", false))
                changesets_data.addAll(stored_beans);

            //Clean up the sql connection
            db_helper.cleanup();
            db_helper = null;

            //Notify the handler that the loading of the list was successful
            list_handler.sendEmptyMessage(SUCCESSFUL);
        }
    };

    //Start the thread
    load_thread.start();
}