Example usage for android.preference PreferenceManager setDefaultValues

List of usage examples for android.preference PreferenceManager setDefaultValues

Introduction

In this page you can find the example usage for android.preference PreferenceManager setDefaultValues.

Prototype

public static void setDefaultValues(Context context, @XmlRes int resId, boolean readAgain) 

Source Link

Document

Sets the default values from an XML preference file by reading the values defined by each Preference item's android:defaultValue attribute.

Usage

From source file:net.ddns.mlsoftlaberge.trycorder.TryviscamFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tryviscam_fragment, container, false);

    // utility class to fetch infos from the system
    mFetcher = new Fetcher(getContext());

    PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, false);

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    autoListen = sharedPref.getBoolean("pref_key_auto_listen", false);
    isChatty = sharedPref.getBoolean("pref_key_ischatty", false);
    speakLanguage = sharedPref.getString("pref_key_speak_language", "");
    listenLanguage = sharedPref.getString("pref_key_listen_language", "");
    displayLanguage = sharedPref.getString("pref_key_display_language", "");
    deviceName = sharedPref.getString("pref_key_device_name", "");
    replaySent = sharedPref.getBoolean("pref_key_replay_sent", true);

    // ===================== top horizontal button grid ==========================
    // the start button
    mBacktopButton = (ImageButton) view.findViewById(R.id.backtop_button);
    mBacktopButton.setOnClickListener(new View.OnClickListener() {
        @Override//from  w w  w  . ja  v  a  2s .c  o m
        public void onClick(View view) {
            buttonsound();
            switchtryviscammode(1);
        }
    });

    // the sound-effect button
    mBackButton = (Button) view.findViewById(R.id.back_button);
    mBackButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            buttonsound();
            switchtryviscammode(1);
        }
    });

    // the settings button
    mSettingsButton = (Button) view.findViewById(R.id.settings_button);
    mSettingsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            buttonsound();
            settingsactivity();
        }
    });

    mTextstatus_top = (TextView) view.findViewById(R.id.textstatus_top);

    // ===================== bottom horizontal button grid ==========================
    // the ask button
    mBackbottomButton = (ImageButton) view.findViewById(R.id.backbottom_button);
    mBackbottomButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            buttonsound();
            switchtryviscammode(1);
        }
    });

    // the stop button
    mEffectButton = (Button) view.findViewById(R.id.effect_button);
    mEffectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            buttonsound();
            rotateeffect();
        }
    });

    // the settings button
    mSceneButton = (Button) view.findViewById(R.id.scene_button);
    mSceneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            buttonsound();
            rotatescene();
        }
    });

    mTextstatus_bottom = (TextView) view.findViewById(R.id.textstatus_bottom);
    mTextstatus_bottom.setText("Ready");

    // =========================== center content area ============================

    // the center layout to show contents
    mCenterLayout = (LinearLayout) view.findViewById(R.id.center_layout);

    mSensor1Layout = (LinearLayout) view.findViewById(R.id.sensor1_layout);

    // ==============================================================================
    // create layout params for the created views
    final LinearLayout.LayoutParams tlayoutParams = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

    // create and activate a textureview to contain vision display
    mTextureView = new AutoFitTextureView(getContext());

    // add my sensorview to the layout 1
    mSensor1Layout.addView(mTextureView, tlayoutParams);
    mSensor1Layout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            buttonsound();
            takePicture();
        }
    });

    return (view);
}

From source file:org.petero.droidfish.DroidFish.java

/** Called when the activity is first created. */
@Override/*from  www  . ja  v a  2  s .c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Pair<String, String> pair = getPgnOrFenIntent();
    String intentPgnOrFen = pair.first;
    String intentFilename = pair.second;

    createDirectories();

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    settings.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            handlePrefsChange();
        }
    });

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    setWakeLock(false);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "droidfish");
    wakeLock.setReferenceCounted(false);

    custom1ButtonActions = new ButtonActions("custom1", CUSTOM1_BUTTON_DIALOG, R.string.select_action);
    custom2ButtonActions = new ButtonActions("custom2", CUSTOM2_BUTTON_DIALOG, R.string.select_action);
    custom3ButtonActions = new ButtonActions("custom3", CUSTOM3_BUTTON_DIALOG, R.string.select_action);

    figNotation = Typeface.createFromAsset(getAssets(), "fonts/DroidFishChessNotationDark.otf");
    setPieceNames(PGNOptions.PT_LOCAL);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    initUI();

    gameTextListener = new PgnScreenText(this, pgnOptions);
    if (ctrl != null)
        ctrl.shutdownEngine();
    ctrl = new DroidChessController(this, gameTextListener, pgnOptions);
    egtbForceReload = true;
    readPrefs();
    TimeControlData tcData = new TimeControlData();
    tcData.setTimeControl(timeControl, movesPerSession, timeIncrement);
    ctrl.newGame(gameMode, tcData);
    setAutoMode(AutoMode.OFF);
    {
        byte[] data = null;
        int version = 1;
        if (savedInstanceState != null) {
            data = savedInstanceState.getByteArray("gameState");
            version = savedInstanceState.getInt("gameStateVersion", version);
        } else {
            String dataStr = settings.getString("gameState", null);
            version = settings.getInt("gameStateVersion", version);
            if (dataStr != null)
                data = strToByteArr(dataStr);
        }
        if (data != null)
            ctrl.fromByteArray(data, version);
    }
    ctrl.setGuiPaused(true);
    ctrl.setGuiPaused(false);
    ctrl.startGame();
    if (intentPgnOrFen != null) {
        try {
            ctrl.setFENOrPGN(intentPgnOrFen);
            setBoardFlip(true);
        } catch (ChessParseError e) {
            // If FEN corresponds to illegal chess position, go into edit board mode.
            try {
                TextIO.readFEN(intentPgnOrFen);
            } catch (ChessParseError e2) {
                if (e2.pos != null)
                    startEditBoard(intentPgnOrFen);
            }
        }
    } else if (intentFilename != null) {
        if (intentFilename.toLowerCase(Locale.US).endsWith(".fen")
                || intentFilename.toLowerCase(Locale.US).endsWith(".epd"))
            loadFENFromFile(intentFilename);
        else
            loadPGNFromFile(intentFilename);
    }
}

From source file:io.github.data4all.activity.CameraActivity.java

private boolean getWarning() {
    PreferenceManager.setDefaultValues(this, R.xml.settings, false);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    return (prefs.getBoolean("sensor_warning", true));
}

From source file:io.github.data4all.activity.CameraActivity.java

private void setWarning(boolean show) {
    PreferenceManager.setDefaultValues(this, R.xml.settings, false);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.edit().putBoolean("sensor_warning", show).commit();
}

From source file:com.bookkos.bircle.CaptureActivity.java

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

    _context = getApplicationContext();//from  www.ja v a2  s. c  o  m
    _activity = this;

    currentTime = new Time("Asia/Tokyo");

    //      exceptionHandler = new ExceptionHandler(_context);   
    //      Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

    // sharedPreference???, user_id?group_id?registration_id??
    getUserData();

    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    // ??
    WindowManager window_manager = getWindowManager();
    Display display = window_manager.getDefaultDisplay();
    Point point = new Point();
    display.getSize(point);
    displayWidth = point.x;
    displayHeight = point.y;

    displayInch = getInch();
    // ??4???????
    textSize = 17 * (displayInch / 4);

    actionBar = getActionBar();
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_USE_LOGO);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setDisplayUseLogoEnabled(false);
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayHomeAsUpEnabled(false);
    String title_text = "";
    subGroupText = "";
    groupText = groupName;

    if (displayInch < 4.7) {
        title_text = "<small><small><small>??: </small></small></small>";
        resizeTitleSizeTooSmall();
    } else if (displayInch >= 4.7 && displayInch < 5.5) {
        title_text = "<small><small>??: </small></small>";
        resizeTitleSizeSmall();
    } else if (displayInch >= 5.5 && displayInch < 6.5) {
        title_text = "<small>??: </small>";
        resizeTitleSizeMiddle();
    } else if (displayInch >= 6.5 && displayInch < 8) {
        title_text = "<small>??: </small>";
        resizeTitleSizeLarge();
    } else {
        title_text = "??: ";
    }
    String modify_group_text = title_text + "<font color=#FF0000>" + groupName + "</font>";
    actionBar.setTitle(Html.fromHtml(modify_group_text));

    Resources resources = _context.getResources();
    int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    titleBarHeight = resources.getDimensionPixelSize(resourceId);

    setContentView(R.layout.capture);

    returnBorrowHelpView = (ImageView) findViewById(R.id.return_borrow_help_view);
    returnBorrowHelpView.setImageResource(R.drawable.return_borrow_help);
    returnBorrowHelpView.setTranslationY(displayHeight / 5 + titleBarHeight);
    returnBorrowHelpView.setLayoutParams(new FrameLayout.LayoutParams(displayWidth,
            displayHeight / 5 + titleBarHeight, Gravity.BOTTOM | Gravity.CENTER));

    registHelpView = (ImageView) findViewById(R.id.regist_help_view);
    registHelpView.setImageResource(R.drawable.regist_help);
    registHelpView.setTranslationY(displayHeight / 5 + titleBarHeight);
    registHelpView.setLayoutParams(new FrameLayout.LayoutParams(displayWidth,
            displayHeight / 5 + titleBarHeight, Gravity.BOTTOM | Gravity.CENTER));
    registHelpView.setVisibility(View.GONE);

    leftDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    leftDrawer = (ListView) findViewById(R.id.left_drawer);
    textView = (TextView) findViewById(R.id.textView);

    modeText = (TextView) findViewById(R.id.mode_text);
    modeText.setTextColor(Color.rgb(56, 234, 123));
    modeText.setTextSize(textSize);
    modeText.setTypeface(Typeface.SERIF.MONOSPACE, Typeface.BOLD);
    strokeColor = Color.rgb(56, 234, 123);

    borrowReturnButton = (Button) findViewById(R.id.borrowReturnButton);
    registButton = (Button) findViewById(R.id.registButton);
    returnHistoryButton = (Button) findViewById(R.id.return_history_button);
    helpViewButton = (Button) findViewById(R.id.help_view_button);

    registSelectShelfRelativeLayout = (RelativeLayout) findViewById(R.id.regist_select_shelf_relative_layout);
    textViewLinearLayout = (LinearLayout) findViewById(R.id.text_view_linear_layout);
    buttonLinearLayout = (LinearLayout) findViewById(R.id.button_linear_layout);
    listViewLinearLayout = (LinearLayout) findViewById(R.id.list_view_linear_layout);
    decisionButton = (Button) findViewById(R.id.decision_button);
    cancelButton = (Button) findViewById(R.id.cancel_button);
    shelfListView = (ListView) findViewById(R.id.shelf_list_view);
    tempTextView = (TextView) findViewById(R.id.temp_text_view);
    //      bookListViewAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
    bookListViewAdapter = new BookListViewAdapter(_context, R.layout.book_list_row, this);

    bookRegistRelativeLayout = (RelativeLayout) findViewById(R.id.book_regist_relative_layout);
    bookRegistLinearLayout = (LinearLayout) findViewById(R.id.book_regist_linear_layout);
    bookRegistListViewLinearLayout = (LinearLayout) findViewById(R.id.book_regist_list_view_linear_layout);
    bookRegistListView = (ListView) findViewById(R.id.book_regist_list_view);
    bookRegistTextView = (TextView) findViewById(R.id.book_regist_text_view);
    bookRegistCancelButton = (Button) findViewById(R.id.book_regist_cancel_button);

    registFlag = 0;

    int borrowReturnButton_width = displayWidth / 5 * 2;
    int borrowReturnButton_height = displayHeight / 10;
    int borrowReturnButton_x = ((displayWidth / 2) - borrowReturnButton_width) / 2;
    int borrowReturnButton_y = displayHeight / 2 + titleBarHeight;
    borrowReturnButton.setTranslationX(borrowReturnButton_x);
    borrowReturnButton.setTranslationY(borrowReturnButton_y);
    borrowReturnButton
            .setLayoutParams(new FrameLayout.LayoutParams(borrowReturnButton_width, borrowReturnButton_height));
    borrowReturnButton.setBackgroundColor(Color.rgb(56, 234, 123));
    borrowReturnButton.setText("??\n");
    borrowReturnButton.setTextSize(textSize * 7 / 10);
    borrowReturnButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            arrayList.clear();
            registFlag = 0;

            borrowReturnButton.setText("??\n");
            borrowReturnButton.setEnabled(false);
            borrowReturnButton.setTextColor(Color.WHITE);
            borrowReturnButton.setBackgroundColor(Color.rgb(56, 234, 123));

            registButton.setText("?\n??");
            registButton.setEnabled(true);
            registButton.setTextColor(Color.GRAY);
            registButton.setBackgroundColor(Color.argb(170, 21, 38, 45));

            modeText.setText("??");
            modeText.setTextColor(Color.rgb(56, 234, 123));
            returnBorrowHelpView.setVisibility(View.VISIBLE);
            registHelpView.setVisibility(View.GONE);
            strokeColor = Color.rgb(56, 234, 123);
        }
    });

    int registButton_width = displayWidth / 5 * 2;
    int registButton_height = displayHeight / 10;
    int registButton_x = (displayWidth / 2) + ((displayWidth / 2) - registButton_width) / 2;
    int registButton_y = displayHeight / 2 + titleBarHeight;
    registButton.setTranslationX(registButton_x);
    registButton.setTranslationY(registButton_y);
    registButton.setLayoutParams(new FrameLayout.LayoutParams(registButton_width, registButton_height));
    registButton.setBackgroundColor(Color.argb(170, 21, 38, 45));
    registButton.setTextColor(Color.GRAY);
    registButton.setTextSize(textSize * 7 / 10);
    registButton.setText("?\n??");
    registButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            arrayList.clear();
            registFlag = 1;

            borrowReturnButton.setText("??\n??");
            borrowReturnButton.setEnabled(true);
            borrowReturnButton.setTextColor(Color.GRAY);
            borrowReturnButton.setBackgroundColor(Color.argb(170, 9, 54, 16));

            registButton.setText("?\n");
            registButton.setEnabled(false);
            registButton.setTextColor(Color.WHITE);
            registButton.setBackgroundColor(Color.rgb(62, 162, 229));

            modeText.setText("?");
            modeText.setTextColor(Color.rgb(62, 162, 229));
            returnBorrowHelpView.setVisibility(View.GONE);
            registHelpView.setVisibility(View.VISIBLE);
            strokeColor = Color.rgb(62, 162, 229);
        }
    });

    returnHistoryButton.setText("????");
    returnHistoryButton.setTextSize(textSize * 7 / 10);
    returnHistoryButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            leftDrawerLayout.openDrawer(Gravity.RIGHT);
            //            animateTranslationY(bookRegistRelativeLayout, displayHeight, displayHeight - displayHeight / 4 - titleBarHeight);
        }
    });
    getReturnHistory();
    getCurrentTime();

    setHelpView();
    setScanUnregisterBookView();
    setBookRegistView();

    arrayList = new ArrayList<String>();
    tempRegistIsbn = "";

    initBookRegistUrl = book_register_url + "?user_id=" + userId + "&group_id=" + groupId;
    initLendRegistUrl = lend_register_url + "?user_id=" + userId + "&group_id=" + groupId;
    initTemporaryLendRegistUrl = temporary_lend_register_url + "?user_id=" + userId + "&group_id=" + groupId;
    initCatalogRegistUrl = catalog_register_url + "?group_id=" + groupId + "&book_code=";
    initManuallyCatalogRegistUrl = manually_catalog_register_url + "?group_id=" + groupId + "&book_code=";
    getStatusUrl = get_status_url + "?group_id=" + groupId + "&user_id=" + userId;

    hasSurface = false;

    inactivityTimer = new InactivityTimer(this);
    bircleBeepManager = new BircleBeepManager(this);
    ambientLightManager = new AmbientLightManager(this);

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    toastText = "";
}

From source file:com.gelakinetic.mtgfam.FamiliarActivity.java

/**
 * Set up drawer menu//w w w .  java 2s . co  m
 * Run updater service
 * Check for, and potentially start, round timer
 * Check for TTS support
 *
 * @param savedInstanceState If the activity is being re-initialized after previously being shut down then this
 *                           Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle).
 *                           Note: Otherwise it is null.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PrefsFragment.checkOverrideSystemLanguage(this);
    mPreferenceAdapter = new PreferenceAdapter(this);

    /* Figure out what theme the app is currently in, and change it if necessary */
    int resourceId = getResourceIdFromAttr(R.attr.color_drawer_background);
    String themeString = "";
    int otherTheme = 0;
    if (resourceId == R.color.drawer_background_dark) {
        otherTheme = R.style.Theme_light;
        themeString = getString(R.string.pref_theme_dark);
    } else if (resourceId == R.color.drawer_background_light) {
        otherTheme = R.style.Theme_dark;
        themeString = getString(R.string.pref_theme_light);
    }

    /* Switch the theme if the preference does not match the current theme */
    if (!themeString.equals(mPreferenceAdapter.getTheme())) {
        this.setTheme(otherTheme);
    }

    /* Set the system bar color programatically, for lollipop+ */
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().setStatusBarColor(
                ContextCompat.getColor(this, getResourceIdFromAttr(R.attr.colorPrimaryDark_attr)));
    }

    setContentView(R.layout.activity_main);

    DatabaseManager.initializeInstance(getApplicationContext());

    mRefreshLayout = ((IndeterminateRefreshLayout) findViewById(R.id.fragment_container));
    mRefreshLayout.setColors(ContextCompat.getColor(this, getResourceIdFromAttr(R.attr.color_common)),
            ContextCompat.getColor(this, getResourceIdFromAttr(R.attr.color_uncommon)),
            ContextCompat.getColor(this, getResourceIdFromAttr(R.attr.color_rare)),
            ContextCompat.getColor(this, getResourceIdFromAttr(R.attr.color_mythic)));

    /* Set default preferences manually so that the listener doesn't do weird things on init */
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    /* Set up a listener to update the home screen widget whenever the user changes the preference */
    mPreferenceAdapter.registerOnSharedPreferenceChangeListener(mPreferenceChangeListener);

    /* Create the handler to update the timer in the action bar */
    mRoundTimerUpdateHandler = new Handler();

    /* Check if we should make the timer notification */
    mRoundEndTime = mPreferenceAdapter.getRoundTimerEnd();
    if (mRoundEndTime != -1) {
        RoundTimerFragment.showTimerRunningNotification(this, mRoundEndTime);
        RoundTimerFragment.setOrCancelAlarms(this, mRoundEndTime, true);
    }
    mUpdatingRoundTimer = false;

    /* Get the drawer layout and list */
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    /* set a custom shadow that overlays the main content when the drawer opens */
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    /* set up the drawer's list view with items and click listener */
    mPagesAdapter = new DrawerEntryArrayAdapter(this, mPageEntries);

    mDrawerList.setAdapter(mPagesAdapter);
    mDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            boolean shouldCloseDrawer = false;
            switch (mPageEntries[i].mNameResource) {
            case R.string.main_force_update_title: {
                if (getNetworkState(FamiliarActivity.this, true) != -1) {
                    SQLiteDatabase database = DatabaseManager.getInstance(FamiliarActivity.this, true)
                            .openDatabase(true);
                    try {
                        CardDbAdapter.dropCreateDB(database);
                        mPreferenceAdapter.setLastLegalityUpdate(0);
                        mPreferenceAdapter.setLastIPGUpdate(0);
                        mPreferenceAdapter.setLastMTRUpdate(0);
                        mPreferenceAdapter.setLastJARUpdate(0);
                        mPreferenceAdapter.setLastRulesUpdate(0);
                        mPreferenceAdapter.setLastUpdateTimestamp(0);
                        mPreferenceAdapter.setLegalityTimestamp(0);
                        startService(new Intent(FamiliarActivity.this, DbUpdaterService.class));
                    } catch (FamiliarDbException e) {
                        e.printStackTrace();
                    }
                    DatabaseManager.getInstance(FamiliarActivity.this, true).closeDatabase(true);
                }
                shouldCloseDrawer = true;
                break;
            }
            }

            mDrawerList.setItemChecked(mCurrentFrag, true);
            if (shouldCloseDrawer) {
                (new Handler()).postDelayed(new Runnable() {
                    public void run() {
                        mDrawerLayout.closeDrawer(mDrawerList);
                    }
                }, 50);
                return true;
            }
            return false;
        }
    });
    mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            /* FamiliarFragments will automatically close the drawer when they hit onResume(). It's more precise
               than a delayed handler. Other options have to close the drawer themselves */
            boolean shouldCloseDrawer = false;
            switch (mPageEntries[i].mNameResource) {
            case R.string.main_extras:
            case R.string.main_pages: {
                /* It's a header */
                break; /* don't close the drawer or change a selection */
            }
            case R.string.main_mana_pool:
            case R.string.main_dice:
            case R.string.main_trade:
            case R.string.main_wishlist:
            case R.string.main_decklist:
            case R.string.main_timer:
            case R.string.main_rules:
            case R.string.main_judges_corner:
            case R.string.main_mojhosto:
            case R.string.main_card_search:
            case R.string.main_life_counter:
            case R.string.main_profile: {
                selectItem(mPageEntries[i].mNameResource, null, true, false);
                break;
            }
            case R.string.main_settings_title: {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.addToBackStack(null);
                ft.replace(R.id.fragment_container, new PrefsFragment(), FamiliarActivity.FRAGMENT_TAG);
                ft.commit();
                shouldCloseDrawer = true;
                break;
            }
            case R.string.main_force_update_title: {
                if (getNetworkState(FamiliarActivity.this, true) != -1) {
                    mPreferenceAdapter.setLastLegalityUpdate(0);
                    startService(new Intent(FamiliarActivity.this, DbUpdaterService.class));
                }
                shouldCloseDrawer = true;
                break;
            }
            case R.string.main_donate_title: {
                showDialogFragment(FamiliarActivityDialogFragment.DIALOG_DONATE);
                shouldCloseDrawer = true;
                break;
            }
            case R.string.main_about: {
                showDialogFragment(FamiliarActivityDialogFragment.DIALOG_ABOUT);
                shouldCloseDrawer = true;
                break;
            }
            case R.string.main_whats_new_title: {
                showDialogFragment(FamiliarActivityDialogFragment.DIALOG_CHANGE_LOG);
                shouldCloseDrawer = true;
                break;
            }
            case R.string.main_export_data_title: {
                ZipUtils.exportData(FamiliarActivity.this);
                shouldCloseDrawer = true;
                break;
            }
            case R.string.main_import_data_title: {
                ZipUtils.importData(FamiliarActivity.this);
                shouldCloseDrawer = true;
                break;
            }
            }

            mDrawerList.setItemChecked(mCurrentFrag, true);
            if (shouldCloseDrawer) {
                (new Handler()).postDelayed(new Runnable() {
                    public void run() {
                        mDrawerLayout.closeDrawer(mDrawerList);
                    }
                }, 50);
            }
        }
    });

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        //toolbar.setCollapsible(true);
        /* I don't like styling in java, but I can't get it to work other ways */
        if (mPreferenceAdapter.getTheme().equals(getString(R.string.pref_theme_light))) {
            toolbar.setPopupTheme(R.style.ThemeOverlay_AppCompat_Light);
        } else {
            toolbar.setPopupTheme(R.style.ThemeOverlay_AppCompat);
        }
        toolbar.setSubtitleTextColor(ContextCompat.getColor(this, android.R.color.white));
        toolbar.setTitleTextColor(ContextCompat.getColor(this, android.R.color.white));
        setSupportActionBar(toolbar);
    }
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
            R.string.main_drawer_open, /* "open drawer" description for accessibility */
            R.string.main_drawer_close /* "close drawer" description for accessibility */
    ) {

        /**
         * When the drawer is opened, make sure to hide the keyboard
         * @param drawerView the drawer view, ignored
         */
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            hideKeyboard();
        }

        /**
         * If the menu is visible and the menu is open(ing), or the menu is not visible and the drawer is closed,
         * invalidate the options menu to either hide or show the action bar icons
         *
         * @param drawerView The drawer view, ignored
         * @param slideOffset How open the sliding menu is, between 0 and 1
         */
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            if ((mIsMenuVisible && slideOffset > 0) || (slideOffset == 0 && !mIsMenuVisible)) {
                supportInvalidateOptionsMenu();
            }
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setTitle("");

    boolean isDeepLink = false;

    /* The activity can be launched a few different ways. Check the intent and show the appropriate fragment */
    /* Only launch a fragment if the app isn't being recreated, i.e. savedInstanceState is null */
    if (savedInstanceState == null) {
        isDeepLink = processIntent(getIntent());
    }

    /* Check to see if the change log should be shown */
    if (!isDeepLink) {
        PackageInfo pInfo;
        try {
            assert getPackageManager() != null;
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

            int lastVersion = mPreferenceAdapter.getLastVersion();
            if (pInfo.versionCode != lastVersion) {
                /* Clear the spice cache on upgrade. This way, no cached values w/o foil prices will exist*/
                try {
                    mSpiceManager.removeAllDataFromCache();
                } catch (NullPointerException e) {
                    /* eat it. tasty */
                }
                if (lastVersion != 0) {
                    showDialogFragment(FamiliarActivityDialogFragment.DIALOG_CHANGE_LOG);
                }
                mPreferenceAdapter.setLastVersion(pInfo.versionCode);

                /* Clear the mtr and ipg on update, to replace them with the newly colored versions, but only if we're
                 * updating to 3.0.1 (v24) */
                if (pInfo.versionCode <= 24) {
                    File mtr = new File(getFilesDir(), JudgesCornerFragment.MTR_LOCAL_FILE);
                    File ipg = new File(getFilesDir(), JudgesCornerFragment.IPG_LOCAL_FILE);
                    File jar = new File(getFilesDir(), JudgesCornerFragment.JAR_LOCAL_FILE);
                    if (mtr.exists()) {
                        if (!mtr.delete()) {
                            ToastWrapper.makeText(this, mtr.getName() + " " + getString(R.string.not_deleted),
                                    ToastWrapper.LENGTH_LONG).show();
                        }
                        if (!ipg.delete()) {
                            ToastWrapper.makeText(this, ipg.getName() + " " + getString(R.string.not_deleted),
                                    ToastWrapper.LENGTH_LONG).show();
                        }
                        if (!jar.delete()) {
                            ToastWrapper.makeText(this, jar.getName() + " " + getString(R.string.not_deleted),
                                    ToastWrapper.LENGTH_LONG).show();
                        }
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            /* Eat it, don't show change log */
        }
    }

    /* Run the updater service if there is a network connection */
    if (getNetworkState(FamiliarActivity.this, false) != -1 && mPreferenceAdapter.getAutoUpdate()) {
        /* Only update the banning list if it hasn't been updated recently */
        long curTime = System.currentTimeMillis();
        int updateFrequency = Integer.valueOf(mPreferenceAdapter.getUpdateFrequency());
        int lastLegalityUpdate = mPreferenceAdapter.getLastLegalityUpdate();
        /* days to ms */
        if (((curTime / 1000) - lastLegalityUpdate) > (updateFrequency * 24 * 60 * 60)) {
            startService(new Intent(this, DbUpdaterService.class));
        }
    }

    /* Set up the image cache */
    ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR);
    cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory
    cacheParams.diskCacheSize = 1024 * 1024 * mPreferenceAdapter.getImageCacheSize();
    addImageCache(getSupportFragmentManager(), cacheParams);

    /* Set up app indexing */
    mAppIndexingWrapper = new AppIndexingWrapper(this);
    mAppIndexingWrapper.connectIfDisconnected();
}

From source file:github.daneren2005.dsub.activity.SubsonicFragmentActivity.java

private void loadSettings() {
    PreferenceManager.setDefaultValues(this, R.xml.settings, false);
    SharedPreferences prefs = Util.getPreferences(this);
    if (!prefs.contains(Constants.PREFERENCES_KEY_CACHE_LOCATION)
            || prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null) == null) {
        resetCacheLocation(prefs);//from   w ww. j a  v a2s  .c om
    } else {
        String path = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null);
        File cacheLocation = new File(path);
        if (!FileUtil.verifyCanWrite(cacheLocation)) {
            // Only warn user if there is a difference saved
            if (resetCacheLocation(prefs)) {
                Util.info(this, R.string.common_warning, R.string.settings_cache_location_reset);
            }
        }
    }

    if (!prefs.contains(Constants.PREFERENCES_KEY_OFFLINE)) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(Constants.PREFERENCES_KEY_OFFLINE, false);

        editor.putString(Constants.PREFERENCES_KEY_SERVER_NAME + 1, "Demo Server");
        editor.putString(Constants.PREFERENCES_KEY_SERVER_URL + 1, "http://demo.subsonic.org");
        editor.putString(Constants.PREFERENCES_KEY_USERNAME + 1, "guest");
        editor.putString(Constants.PREFERENCES_KEY_PASSWORD + 1, "guest");
        editor.putInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        editor.commit();
    }
    if (!prefs.contains(Constants.PREFERENCES_KEY_SERVER_COUNT)) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, 1);
        editor.commit();
    }
}

From source file:com.if3games.chessonline.DroidFish.java

/** Called when the activity is first created. */
@Override//from   w w  w . j  a  v a2  s  .  c  o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int isGMS = getIntent().getExtras().getInt("gms");
    if (isGMS != 1) {
        isSinglePlayer = true;
    } else {
        isSinglePlayer = false;

        GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this);
        builder.addApi(Games.API).addApi(Plus.API).addApi(AppStateManager.API).addScope(Games.SCOPE_GAMES)
                .addScope(Plus.SCOPE_PLUS_LOGIN).addScope(AppStateManager.SCOPE_APP_STATE);
        mClient = builder.build();

        loadLocal();

        if (isSignedIn()) {
            //onFetchPlayerScoreAndAchive();
            //displayPlayerNameScoreRank();
            //Toast.makeText(this, "I Connected", Toast.LENGTH_SHORT).show();
        }
    }

    Pair<String, String> pair = getPgnOrFenIntent();
    String intentPgnOrFen = pair.first;
    String intentFilename = pair.second;

    createDirectories();

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    settings.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            try {
                handlePrefsChange();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    });

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    setWakeLock(false);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "droidfish");
    wakeLock.setReferenceCounted(false);

    custom1ButtonActions = new ButtonActions("custom1", CUSTOM1_BUTTON_DIALOG, R.string.select_action);
    custom2ButtonActions = new ButtonActions("custom2", CUSTOM2_BUTTON_DIALOG, R.string.select_action);
    custom3ButtonActions = new ButtonActions("custom3", CUSTOM3_BUTTON_DIALOG, R.string.select_action);

    figNotation = Typeface.createFromAsset(getAssets(), "fonts/DroidFishChessNotationDark.otf");
    setPieceNames(PGNOptions.PT_LOCAL);
    //requestWindowFeature(Window.FEATURE_NO_TITLE);
    initUI();

    gameTextListener = new PgnScreenText(pgnOptions);
    if (ctrl != null)
        ctrl.shutdownEngine();
    ctrl = new DroidChessController(this, gameTextListener, pgnOptions);
    egtbForceReload = true;
    readPrefs();
    TimeControlData tcData = new TimeControlData();
    tcData.setTimeControl(timeControl, movesPerSession, timeIncrement);
    if (isSinglePlayer) {
        myTurn = true;
        ctrl.newGame(gameMode, tcData);
        {
            byte[] data = null;
            int version = 1;
            if (savedInstanceState != null) {
                data = savedInstanceState.getByteArray("gameState");
                version = savedInstanceState.getInt("gameStateVersion", version);
            } else {
                String dataStr = settings.getString("gameState", null);
                version = settings.getInt("gameStateVersion", version);
                if (dataStr != null)
                    data = strToByteArr(dataStr);
            }
            if (data != null)
                ctrl.fromByteArray(data, version);
        }
        ctrl.setGuiPaused(true);
        ctrl.setGuiPaused(false);
        ctrl.startGame();
        //startNewGame(0);
        if (intentPgnOrFen != null) {
            try {
                ctrl.setFENOrPGN(intentPgnOrFen);
                setBoardFlip(true);
            } catch (ChessParseError e) {
                // If FEN corresponds to illegal chess position, go into edit board mode.
                try {
                    TextIO.readFEN(intentPgnOrFen);
                } catch (ChessParseError e2) {
                    if (e2.pos != null)
                        startEditBoard(intentPgnOrFen);
                }
            }
        } else if (intentFilename != null) {
            if (intentFilename.toLowerCase(Locale.US).endsWith(".fen")
                    || intentFilename.toLowerCase(Locale.US).endsWith(".epd"))
                loadFENFromFile(intentFilename);
            else
                loadPGNFromFile(intentFilename);
        }
    } else {
        int rnd = new Random().nextInt(2);
        startMultiplayerGameMode(rnd);
    }
}

From source file:github.popeen.dsub.activity.SubsonicFragmentActivity.java

private void loadSettings() {
    PreferenceManager.setDefaultValues(this, R.xml.settings_appearance, false);
    PreferenceManager.setDefaultValues(this, R.xml.settings_cache, false);
    PreferenceManager.setDefaultValues(this, R.xml.settings_drawer, false);
    PreferenceManager.setDefaultValues(this, R.xml.settings_sync, false);
    PreferenceManager.setDefaultValues(this, R.xml.settings_playback, false);

    SharedPreferences prefs = Util.getPreferences(this);
    if (!prefs.contains(Constants.PREFERENCES_KEY_CACHE_LOCATION)
            || prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null) == null) {
        resetCacheLocation(prefs);/* w  w w.  j  a v a2 s . com*/
    } else {
        String path = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null);
        File cacheLocation = new File(path);
        if (!FileUtil.verifyCanWrite(cacheLocation)) {
            // Only warn user if there is a difference saved
            if (resetCacheLocation(prefs)) {
                Util.info(this, R.string.common_warning, R.string.settings_cache_location_reset);
            }
        }
    }

    if (!prefs.contains(Constants.PREFERENCES_KEY_OFFLINE)) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(Constants.PREFERENCES_KEY_OFFLINE, false);

        editor.putString(Constants.PREFERENCES_KEY_SERVER_NAME + 1, "Demo Server");
        editor.putString(Constants.PREFERENCES_KEY_SERVER_URL + 1, "http://demo.subsonic.org");
        editor.putString(Constants.PREFERENCES_KEY_USERNAME + 1, "guest");
        editor.putString(Constants.PREFERENCES_KEY_PASSWORD + 1, "guest");
        editor.putInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        editor.commit();
    }
    if (!prefs.contains(Constants.PREFERENCES_KEY_SERVER_COUNT)) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, 1);
        editor.commit();
    }
}

From source file:com.softanalle.scma.MainActivity.java

private void resetSettings() {
    logger.debug("resetSettings()");
    PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
    Toast.makeText(getApplicationContext(), "Settings reseted", Toast.LENGTH_LONG).show();
    logger.debug("reset settings");
}