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:io.jawg.osmcontributor.ui.activities.MapActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    ((OsmTemplateApplication) getApplication()).init(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    ((OsmTemplateApplication) getApplication()).getOsmTemplateComponent().inject(this);
    ButterKnife.bind(this);

    PreferenceManager.setDefaultValues(this, R.xml.pref_accessibility, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_connection, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_data_sync, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_notification, false);
    setSupportActionBar(toolbar);/*w w w  .  j  a  va  2  s .  c o  m*/

    eventBus.post(new UpdateFirstConnectionEvent());
    checkFirstStart();

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            switch (menuItem.getGroupId()) {
            case R.id.drawer_options_group:
                onOptionsClick(menuItem);
                break;
            case R.id.sync:
                onOptionsSyncClick(menuItem);
                break;
            }
            return true;
        }
    });
    filterView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            if (menuItem.getItemId() == R.id.select_all_item) {
                selectAllMenuItem.setChecked(!selectAllMenuItem.isChecked());
                onSelectAllClick();
            } else if (menuItem.getItemId() != R.id.display_open_notes_item
                    && menuItem.getItemId() != R.id.display_closed_notes_item
                    && menuItem.getItemId() != R.id.display_yes_accessibility
                    && menuItem.getItemId() != R.id.display_limited_accessibility
                    && menuItem.getItemId() != R.id.display_no_accessibility
                    && menuItem.getItemId() != R.id.display_unknown_accessibility) {
                menuItem.setChecked(!menuItem.isChecked());
                onFilterItemClick(menuItem);
            } else {
                menuItem.setChecked(!menuItem.isChecked());
                onOtherItemClick(menuItem);
            }
            return true;
        }
    });

    selectAllMenuItem = filterView.getMenu().findItem(R.id.select_all_item);

    if (configManager.hasPoiAddition()) {
        navigationView.getMenu().findItem(R.id.replay_tuto_menu).setVisible(true);
    }

    navigationView.getMenu().findItem(R.id.save_changes).setEnabled(false);

    drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {

        }

        @Override
        public void onDrawerOpened(View drawerView) {
            eventBus.post(new PleaseTellIfDbChanges());
        }

        @Override
        public void onDrawerClosed(View drawerView) {

        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    });

    if (FlavorUtils.isBus()) {
        eventBus.post(new PleaseApplyNoteFilterEvent(false, false));
        List<Poi.AccessibilityType> accessibilityTypesToHide = new ArrayList<>();
        eventBus.post(new PleaseApplyAccessibilityFilter(accessibilityTypesToHide));
    }
    navigationView.getMenu().findItem(R.id.manage_poi_types)
            .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    startPoiTypeEditionActivity();
                    return true;
                }
            });

    // Get the arpi fragment.
    arpiGlFragment = (ArpiGlFragment) getFragmentManager().findFragmentById(R.id.engine_fragment);
    getFragmentManager().beginTransaction().hide(arpiGlFragment).commit();

    if (sharedPreferences.getBoolean(getString(R.string.easter_egg), false)) {
        navigationView.getMenu().findItem(R.id.arpi_view).setVisible(true);
    }
}

From source file:ir.actfun.toofan.activities.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Initialize the associated SharedPreferences file with default values
    PreferenceManager.setDefaultValues(this, R.xml.prefs, false);

    darkTheme = false;/*from www .j  a v a2s .  c o  m*/
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getString("theme", "fresh").equals("dark")) {
        setTheme(R.style.AppTheme_NoActionBar_Dark);
        darkTheme = true;
    } else if (prefs.getString("theme", "fresh").equals("transparent")) {
        setTheme(R.style.AppTheme_NoActionBar_transparent);
    }

    // Initiate activity
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrolling);
    appView = findViewById(R.id.viewApp);

    progressDialog = new ProgressDialog(MainActivity.this);

    // Load toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (darkTheme) {
        toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
    }

    YoYo.with(Techniques.ZoomIn).duration(2000).playOn(findViewById(R.id.todayIcon));

    // Initialize textboxes
    todayTemperature = (TextView) findViewById(R.id.todayTemperature);
    todayDescription = (TextView) findViewById(R.id.todayDescription);
    todayWind = (TextView) findViewById(R.id.todayWind);
    todayPressure = (TextView) findViewById(R.id.todayPressure);
    todayHumidity = (TextView) findViewById(R.id.todayHumidity);
    todaySunrise = (TextView) findViewById(R.id.todaySunrise);
    todaySunset = (TextView) findViewById(R.id.todaySunset);
    lastUpdate = (TextView) findViewById(R.id.lastUpdate);
    todayIcon = (TextView) findViewById(R.id.todayIcon);
    weatherFont = Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf");
    todayIcon.setTypeface(weatherFont);

    // Initialize viewPager
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabs);

    //setting view pager animations
    viewPager.setPageTransformer(true, new RotateUpTransformer());

    destroyed = false;

    initMappings();

    // Preload data from cache
    preloadWeather();
    updateLastUpdateTime();

    // Set autoupdater
    AlarmReceiver.setRecurringAlarm(this);

    //implementing the side bar
    crossfadeDrawerLayout = new CrossfadeDrawerLayout(this);

    //Create the drawer
    result = new DrawerBuilder().withActivity(this).withToolbar(toolbar)
            .withSliderBackgroundDrawableRes(R.drawable.weather)
            //provide the custom crossfadeDrawerLaoyout
            .withDrawerLayout(crossfadeDrawerLayout).withHasStableIds(true)
            //define the width to the width of our smaller view
            .withDrawerWidthDp(72)
            //generate the MiniDrawer which is used for the smaller view
            .withGenerateMiniDrawer(true)
            //add some items, those are alo automatically added to the MiniDrawer
            .addDrawerItems(
                    new PrimaryDrawerItem().withIdentifier(1).withName(R.string.today_weather)
                            .withIcon(R.drawable.today_weather_icon).withTextColorRes(R.color.menu_text_color)
                            .withTypeface(Typeface.createFromAsset(
                                    getApplicationContext().getAssets(), "fonts/iransans_light.ttf")),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(2).withName(R.string.forecast_weather)
                            .withIcon(R.drawable.forecast_weather_icon)
                            .withTextColorRes(R.color.menu_text_color)
                            .withTypeface(Typeface.createFromAsset(
                                    getApplicationContext().getAssets(), "fonts/iransans_light.ttf")),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(3).withName(R.string.gps_finder)
                            .withIcon(R.drawable.gps_finder_icon).withTextColorRes(R.color.menu_text_color)
                            .withTypeface(Typeface.createFromAsset(
                                    getApplicationContext().getAssets(), "fonts/iransans_light.ttf")),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(4).withName(R.string.manual_search)
                            .withIcon(R.drawable.serach_city_icon).withTextColorRes(R.color.menu_text_color)
                            .withTypeface(Typeface.createFromAsset(
                                    getApplicationContext().getAssets(), "fonts/iransans_light.ttf")),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(5).withName(R.string.settings)
                            .withIcon(R.drawable.settings_icon).withTextColorRes(R.color.menu_text_color)
                            .withTypeface(Typeface.createFromAsset(
                                    getApplicationContext().getAssets(), "fonts/iransans_light.ttf")),
                    new DividerDrawerItem(),
                    new PrimaryDrawerItem().withIdentifier(6).withName(R.string.about_dev)
                            .withIcon(R.drawable.aboud_dev_icon).withTextColorRes(R.color.menu_text_color)
                            .withTypeface(Typeface.createFromAsset(getApplicationContext().getAssets(),
                                    "fonts/iransans_light.ttf"))

            ).withSelectedItem(2)
            //the listener which is called when an item inside the drawer or miniDrawer is clicked
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                    if (drawerItem != null) {

                        if (drawerItem.getIdentifier() == 1) { //NowWeatherPage
                            Intent intent = new Intent(MainActivity.this, NowWeatherPage.class);
                            startActivity(intent);
                            result.setSelection(2);

                        } else if (drawerItem.getIdentifier() == 2) {

                        } else if (drawerItem.getIdentifier() == 3) {
                            getCityByLocation();
                            result.setSelection(2);
                        } else if (drawerItem.getIdentifier() == 4) {
                            searchCities();
                            universal_flag = true;
                            result.setSelection(2);

                        } else if (drawerItem.getIdentifier() == 5) {
                            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                            startActivity(intent);
                            result.setSelection(2);

                        } else if (drawerItem.getIdentifier() == 6) {
                            aboutDialog();
                            result.setSelection(2);
                        }

                    }
                    return false;
                }
            }).withCloseOnClick(true).withSavedInstance(savedInstanceState).build();
    result.setSelection(2, false);
    result.addItem(new DividerDrawerItem());
    result.addStickyFooterItem(new PrimaryDrawerItem().withName("         Developed By Methoz").withTypeface(
            Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/copperplate.ttf")));

    //define maxDrawerWidth (this is the width in the complete opened state)
    crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this));

    //add second view (which is the miniDrawer)
    MiniDrawer miniResult = result.getMiniDrawer();
    //build the view for the MiniDrawer
    View view = miniResult.build(this);
    //set the background of the MiniDrawer as this would be transparent
    view.setBackgroundColor(getResources().getColor(R.color.mini_drawer_static_color));
    //we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here
    crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);

    //define the crossfader to be used with the miniDrawer. This is required to be able to automatically toggle open / close
    miniResult.withCrossFader(new ICrossfader() {
        @Override
        public void crossfade() {
            crossfadeDrawerLayout.crossfade(400);
            //only close the drawer if we were already faded and want to close it now
            if (isCrossfaded()) {
                result.getDrawerLayout().closeDrawer(GravityCompat.START);
            }
        }

        @Override
        public boolean isCrossfaded() {
            return crossfadeDrawerLayout.isCrossfaded();
        }
    });

    //End of OnCreate Method.

}

From source file:com.scooter1556.sms.android.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Retrieve preferences if they exist
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.registerOnSharedPreferenceChangeListener(onPreferencesChanged);

    // Set volume control to media
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // Initialise database
    db = new ConnectionDatabase(this);

    // Load default settings
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Action Bar
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayShowHomeEnabled(false);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Navigation Drawer
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.navigation_drawer_list);

    NavigationDrawerListItem[] drawerListItems = new NavigationDrawerListItem[3];
    drawerListItems[MENU_MEDIA_BROWSER] = new NavigationDrawerListItem(R.drawable.ic_media_browser,
            getResources().getStringArray(R.array.navigation_drawer_list_items)[MENU_MEDIA_BROWSER]);
    drawerListItems[MENU_SETTINGS] = new NavigationDrawerListItem(R.drawable.ic_settings,
            getResources().getStringArray(R.array.navigation_drawer_list_items)[MENU_SETTINGS]);
    drawerListItems[MENU_EXIT] = new NavigationDrawerListItem(R.drawable.ic_close,
            getResources().getStringArray(R.array.navigation_drawer_list_items)[MENU_EXIT]);
    NavigationDrawerListItemAdapter drawerAdapter = new NavigationDrawerListItemAdapter(this,
            R.layout.drawer_list_item, drawerListItems);
    drawerList.setAdapter(drawerAdapter);
    drawerList.setOnItemClickListener(new DrawerItemClickListener());

    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open,
            R.string.navigation_drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            getSupportActionBar().setTitle(title);
        }/*from  w  ww  . j  a v  a  2s  . c o m*/

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            title = getSupportActionBar().getTitle().toString();
            getSupportActionBar().setTitle(getString(R.string.navigation_drawer_title));
        }
    };

    // Set the drawer toggle as the DrawerListener
    drawerLayout.setDrawerListener(drawerToggle);

    // Sliding Panel
    slidingPanel = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
    slidingPanel.setPanelHeight((int) getResources().getDimension(R.dimen.audio_player_small_fragment_height));

    PanelSlideListener slidingPanelListener = new SlidingUpPanelLayout.PanelSlideListener() {
        @Override
        public void onPanelAnchored(final View panel) {
        }

        @Override
        public void onPanelCollapsed(final View panel) {
            View audioPlayerSmallContainer = findViewById(R.id.sliding_panel_small_container);
            View audioPlayerContainer = findViewById(R.id.sliding_panel_container);
            audioPlayerSmallContainer.setVisibility(View.VISIBLE);
            audioPlayerSmallContainer.setAlpha(1.0f);
            audioPlayerContainer.setVisibility(View.GONE);
            audioPlayerContainer.setAlpha(1.0f);

            // Update menu items
            audioPlayerFragment.setMenuVisibility(false);
            audioPlaylistFragment.setMenuVisibility(false);
            mediaBrowserFragment.setMenuVisibility(true);

            //Update action bar title
            getSupportActionBar().setTitle(title);
        }

        @Override
        public void onPanelExpanded(final View panel) {
            View audioPlayerSmallContainer = findViewById(R.id.sliding_panel_small_container);
            View audioPlayerContainer = findViewById(R.id.sliding_panel_container);
            audioPlayerSmallContainer.setVisibility(View.GONE);
            audioPlayerSmallContainer.setAlpha(1.0f);
            audioPlayerContainer.setVisibility(View.VISIBLE);
            audioPlayerContainer.setAlpha(1.0f);

            // Update menu items
            audioPlayerFragment.setMenuVisibility(slidingPanelFragment == SLIDING_PANEL_PLAYER);
            audioPlaylistFragment.setMenuVisibility(slidingPanelFragment == SLIDING_PANEL_PLAYLIST);
            mediaBrowserFragment.setMenuVisibility(false);

            //Update action bar title
            getSupportActionBar().setTitle(slidingPanelTitle);
        }

        @Override
        public void onPanelHidden(final View view) {
        }

        @Override
        public void onPanelSlide(final View panel, final float slideOffset) {
            View audioPlayerSmallContainer = findViewById(R.id.sliding_panel_small_container);
            View audioPlayerContainer = findViewById(R.id.sliding_panel_container);

            if (slideOffset < 1.0f) {
                audioPlayerSmallContainer.setVisibility(View.VISIBLE);
                audioPlayerContainer.setVisibility(View.VISIBLE);
            } else {
                audioPlayerSmallContainer.setVisibility(View.GONE);
                audioPlayerContainer.setVisibility(View.VISIBLE);
            }

            audioPlayerSmallContainer.setAlpha(1.0f - slideOffset);
            audioPlayerContainer.setAlpha(slideOffset);
        }
    };

    slidingPanel.setPanelSlideListener(slidingPanelListener);

    if (savedInstanceState == null) {
        // Initialise main view
        mediaBrowserFragment = new MediaFolderFragment();
        mediaBrowserTitle = title = getString(R.string.media_title);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.main_container, mediaBrowserFragment, Integer.toString(MENU_MEDIA_BROWSER)).commit();
        assert getSupportActionBar() != null;
        getSupportActionBar().setTitle(getString(R.string.media_title));
        updateDrawer(MENU_MEDIA_BROWSER);

        // Initialise small audio player sliding panel fragment
        audioPlayerSmallFragment = new AudioPlayerSmallFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.sliding_panel_small_container,
                audioPlayerSmallFragment, Integer.toString(SLIDING_PANEL_SMALL_PLAYER)).commit();

        // Initialise audio player fragment
        audioPlayerFragment = new AudioPlayerFragment();
        audioPlayerFragment.setMenuVisibility(false);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.sliding_panel_container, audioPlayerFragment, Integer.toString(SLIDING_PANEL_PLAYER))
                .commit();
        slidingPanelTitle = getString(R.string.audio_player_title);
        slidingPanelFragment = SLIDING_PANEL_PLAYER;

        // Initialise audio playlist fragment
        audioPlaylistFragment = new AudioPlaylistFragment();
        audioPlaylistFragment.setMenuVisibility(false);
        getSupportFragmentManager().beginTransaction().add(R.id.sliding_panel_container, audioPlaylistFragment,
                Integer.toString(SLIDING_PANEL_PLAYLIST)).hide(audioPlaylistFragment).commit();

        // Check connection
        long id = sharedPreferences.getLong("Connection", -1);

        if (id < 0) {
            Intent connectionsIntent = new Intent(this, ConnectionActivity.class);
            startActivityForResult(connectionsIntent, RESULT_CODE_CONNECTIONS);
        } else {
            Connection connection = db.getConnection(id);
            RESTService.getInstance().setConnection(connection);
        }
    } else {
        // Reload fragments
        mediaBrowserFragment = getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(MENU_MEDIA_BROWSER));
        audioPlayerSmallFragment = (AudioPlayerSmallFragment) getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(SLIDING_PANEL_SMALL_PLAYER));
        audioPlayerFragment = (AudioPlayerFragment) getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(SLIDING_PANEL_PLAYER));
        audioPlaylistFragment = (AudioPlaylistFragment) getSupportFragmentManager()
                .findFragmentByTag(Integer.toString(SLIDING_PANEL_PLAYLIST));

        // Restore activity state variables
        slidingPanelFragment = savedInstanceState.getInt(STATE_SLIDING_PANEL_FRAGMENT);
        slidingPanelTitle = savedInstanceState.getString(STATE_SLIDING_PANEL_TITLE);
        title = savedInstanceState.getString(STATE_MAIN_TITLE);

        if (savedInstanceState.getSerializable(STATE_SLIDING_PANEL) == PanelState.EXPANDED) {
            slidingPanel.setPanelState(PanelState.EXPANDED);
            slidingPanelListener.onPanelSlide(slidingPanel, 1.0f);
            slidingPanelListener.onPanelExpanded(slidingPanel);
        } else {
            slidingPanel.setPanelState(PanelState.COLLAPSED);
            slidingPanelListener.onPanelSlide(slidingPanel, 0.0f);
            slidingPanelListener.onPanelCollapsed(slidingPanel);
        }
    }

    // Add fragment back stack listener
    getSupportFragmentManager().addOnBackStackChangedListener(this);
}

From source file:de.eidottermihi.rpicheck.activity.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // assigning Shared Preferences
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    // init intents
    settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
    newRaspiIntent = new Intent(MainActivity.this, NewRaspiActivity.class);
    editRaspiIntent = new Intent(MainActivity.this, EditRaspiActivity.class);
    commandIntent = new Intent(MainActivity.this, CustomCommandActivity.class);

    // assigning refreshable root scrollview
    initSwipeRefreshLayout();/*from   w  w w .j  ava 2  s  .c  o m*/

    boolean isDebugLogging = sharedPrefs.getBoolean(SettingsActivity.KEY_PREF_DEBUG_LOGGING, false);
    LoggingHelper.changeLogger(isDebugLogging);

    // Changelog
    final ChangeLog changeLog = new ChangeLog(this);
    if (changeLog.firstRun()) {
        changeLog.getLogDialog().show();
    }

    // init device database
    deviceDb = new DeviceDbHelper(this);
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            deviceCursor = deviceDb.getFullDeviceCursor();
            return null;
        }

        @Override
        protected void onPostExecute(Void r) {
            if (deviceCursor.getCount() == 0) {
                MainActivity.this.startActivityForResult(newRaspiIntent, NewRaspiActivity.REQUEST_SAVE);
            } else {
                // init spinner
                initSpinner();
            }
        }
    }.execute();
}

From source file:com.mantz_it.rfanalyzer.ui.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    toaster = new Toaster(this);

    setContentView(R.layout.activity_main);
    this.savedInstanceState = savedInstanceState;

    // Set default Settings on first run:
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Get reference to the shared preferences:
    preferences = PreferenceManager.getDefaultSharedPreferences(this); // todo: separate preferences files for different PreferenceUsers
    // Overwrite defaults for file paths in the preferences:
    String extStorage = Environment.getExternalStorageDirectory().getAbsolutePath(); // get the path to the ext. storage
    // File Source file:
    String defaultFile = getString(R.string.pref_filesource_file_default);
    if (preferences.getString(getString(R.string.pref_filesource_file), "").equals(defaultFile))
        preferences.edit().putString(getString(R.string.pref_filesource_file), extStorage + "/" + defaultFile)
                .apply();//  ww  w .  ja va2  s. com
    // Log file:
    defaultFile = getString(R.string.pref_logfile_default);
    if (preferences.getString(getString(R.string.pref_logfile), "").equals(defaultFile))
        preferences.edit().putString(getString(R.string.pref_logfile), extStorage + "/" + defaultFile).apply();

    // Start logging if enabled:
    if (preferences.getBoolean(getString(R.string.pref_logging), false)) {
        if (ContextCompat.checkSelfPermission(this,
                "android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
            try {
                File logfile = new File(preferences.getString(getString(R.string.pref_logfile), ""));
                logfile.getParentFile().mkdir(); // Create folder
                logcat = Runtime.getRuntime().exec("logcat -f " + logfile);
                Log.i("MainActivity", "onCreate: started logcat (" + logcat.toString() + ") to " + logfile);
            } catch (Exception e) {
                Log.e("MainActivity", "onCreate: Failed to start logging!");
            }
        } else {
            preferences.edit().putBoolean(getString(R.string.pref_logging), false).apply();
            Log.i(LOGTAG, "onCreate: deactivate logging because of missing storage permission.");
        }
    }
    // Get version name:
    try {
        versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        Log.i(LOGTAG, "This is RF Analyzer " + versionName + " by Dennis Mantz (modified).");
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(LOGTAG, "onCreate: Cannot read version name: " + e.getMessage());
    }

    // Get references to the GUI components:
    fl_analyzerFrame = (FrameLayout) findViewById(R.id.fl_analyzerFrame);

    // Create a analyzer surface:
    analyzerSurface = new AnalyzerSurface(this, this);
    analyzerSurface.init(preferences);

    // Put the analyzer surface in the analyzer frame of the layout:
    fl_analyzerFrame.addView(analyzerSurface);

    // Restore / Initialize the running state and the demodulator mode:
    if (savedInstanceState != null) {
        running = savedInstanceState.getBoolean(getString(R.string.save_state_running));
        demodulationMode = savedInstanceState.getInt(getString(R.string.save_state_demodulatorMode));

        /* BUGFIX / WORKAROUND:
         * The RTL2832U driver will not allow to close the socket and immediately start the driver
         * again to reconnect after an orientation change / app kill + restart.
         * It will report back in onActivityResult() with a -1 (not specified).
         *
         * Work-around:
         * 1) We won't restart the Analyzer if the current source is set to a local RTL-SDR instance:
         * 2) Delay the restart of the Analyzer after the driver was shut down correctly...
         */
        if (running
                && Integer.parseInt(
                        preferences.getString(getString(R.string.pref_sourceType), "1")) == RTLSDR_SOURCE
                && !preferences.getBoolean(getString(R.string.pref_rtlsdr_externalServer), false)) {
            // 1) don't start Analyzer immediately
            running = false;

            // Just inform the user about what is going on (why does this take so long? ...)
            toaster.showShort("Stopping and restarting RTL2832U driver...");

            // 2) Delayed start of the Analyzer:
            // todo: can we use notifyAll() instead of this?

            Thread timer = new Thread(() -> {
                try {
                    Thread.sleep(1500);
                    startAnalyzer();
                } catch (InterruptedException e) {
                    Log.e(LOGTAG, "onCreate: (timer thread): Interrupted while sleeping.");
                }
            }, "Timer Thread");

            timer.start();
        }

    } else {
        // Set running to true if autostart is enabled (this will start the analyzer in onStart() )
        running = preferences.getBoolean((getString(R.string.pref_autostart)), false);
    }

    // Set the hardware volume keys to work on the music audio stream:
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:fr.steren.climbtracker.ClimbTrackerActivity.java

private void initPreferences() {
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String gradeSystemTypePref = sharedPref.getString(Path.PREF_GRAD_SYSTEM_TYPE, GradeList.SYSTEM_DEFAULT);
    sendGradeSystemToWear(gradeSystemTypePref);
}

From source file:org.madmatrix.zxing.android.CaptureActivity.java

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

    // ?????//from w  ww. j  a va  2s.c  o  m
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.capture);

    // ????onResume
    hasSurface = false;
    inactivityTimer = new InactivityTimer(this);

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

From source file:com.QuarkLabs.BTCeClient.MainActivity.java

private void onVersionUpdate(final SharedPreferences sharedPreferences) {
    final String keyToCheck = "needNotifyAboutNewSecuritySystem";
    boolean needNotify = sharedPreferences.getBoolean(keyToCheck, true);
    if (needNotify) {
        //getting old values
        String key = sharedPreferences.getString("key", "");
        String secret = sharedPreferences.getString("secret", "");
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (key.length() != 0) {
            editor.putString(SettingsFragment.KEY_API_KEY,
                    SecurityManager.getInstance(this).encryptString(key));
        }//w  ww . ja  va  2  s.  c o  m
        if (secret.length() != 0) {
            editor.putString(SettingsFragment.KEY_API_SECRET,
                    SecurityManager.getInstance(this).encryptString(secret));
        }
        editor.putString("key", "");
        editor.putString("secret", "");
        editor.commit();
        String messageTitle = "New security system";
        String message = "New security system is added with this update. "
                + "Now sensitive API credentials will be stored in encrypted state, "
                + "it will save them from the leak even if device is rooted.";
        new AlertDialog.Builder(this).setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean(keyToCheck, false);
                editor.commit();
            }
        }).setTitle(messageTitle).setMessage(message).show();
    }
}

From source file:com.nextgis.ngm_clink_monitoring.activities.MainActivity.java

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

    if (getIntent().getBooleanExtra(FoclConstants.NO_SDCARD, false)) {

        YesNoDialog dialog = new YesNoDialog();
        dialog.setCancelable(false);/*from w w w  .j a  va2s  .c  om*/
        dialog.setKeepInstance(true).setIcon(R.drawable.ic_action_warning).setTitle(R.string.warning)
                .setMessage(getString(R.string.no_sdcard_exit_app)).setPositiveText(R.string.ok)
                .setOnPositiveClickedListener(new YesNoDialog.OnPositiveClickedListener() {
                    @Override
                    public void onPositiveClicked() {
                        // show Home screen
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                        System.exit(0);
                    }
                }).show(getSupportFragmentManager(), FoclConstants.FRAGMENT_YES_NO_DIALOG + "NoSdCard");
        return;
    }

    final GISApplication app = (GISApplication) getApplication();

    mGpsEventSource = app.getGpsEventSource();
    if (null != mGpsEventSource) {
        mGpsEventSource.addListener(this);
    }

    // initialize the default settings
    PreferenceManager.setDefaultValues(this, R.xml.preferences_general, false);

    mSyncStatusObserver = new SyncStatusObserver() {
        @Override
        public void onStatusChanged(int which) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Account account = app.getAccount();

                    if (null != account) {
                        mIsSyncing = AccountUtil.isSyncActive(account, FoclSettingsConstantsUI.AUTHORITY);
                        switchMenuView();
                    }
                }
            });
        }
    };

    setContentView(R.layout.activity_main);

    mMainToolbar = (Toolbar) findViewById(R.id.main_toolbar_cl);
    mMainToolbar.setTitle(""); // needed for screen rotation
    mMainToolbar.getBackground().setAlpha(255);
    setSupportActionBar(mMainToolbar);

    mBottomToolbar = (Toolbar) findViewById(R.id.bottom_toolbar_cl);
    mBottomToolbar.setContentInsetsAbsolute(0, 0);
    mBottomToolbar.getBackground().setAlpha(255);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        // Inflate a custom action bar that contains the "done" button
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View customActionBarView = inflater.inflate(R.layout.editor_custom_action_bar, null);

        mCustomToolbarTitle = (TextView) customActionBarView.findViewById(R.id.custom_toolbar_title);
        mCustomToolbarButton = (TextView) customActionBarView.findViewById(R.id.custom_toolbar_button);
        mCustomToolbarImage = (ImageView) customActionBarView.findViewById(R.id.custom_toolbar_image);

        actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setCustomView(customActionBarView);
    }

    // TODO: remove it
    //        FragmentManager fm = getSupportFragmentManager();
    //        mStatusBarFragment =
    //                (StatusBarFragment) fm.findFragmentByTag(FoclConstants.FRAGMENT_STATUS_BAR);
    //        if (null == mStatusBarFragment) {
    //            mStatusBarFragment = new StatusBarFragment();
    //            FragmentTransaction ft = fm.beginTransaction();
    //            ft.replace(
    //                    R.id.status_bar_fragment, mStatusBarFragment,
    //                    FoclConstants.FRAGMENT_STATUS_BAR);
    //            ft.hide(mStatusBarFragment);
    //            ft.commit();
    //        }

    if (null == savedInstanceState) {
        if (!app.hasAccount()) {
            mViewState = VIEW_STATE_LOGIN;
        } else if (null == app.getFoclProject()) {
            mViewState = VIEW_STATE_1ST_SYNC;
        } else {
            mViewState = VIEW_STATE_OBJECTS;
        }
    } else {
        if (savedInstanceState.containsKey(FoclConstants.VIEW_STATE)) {
            mViewState = savedInstanceState.getInt(FoclConstants.VIEW_STATE);
        }
    }

    setActivityView();

    // workaround for YesNoDialog destroying by the screen rotation
    FragmentManager fm = getSupportFragmentManager();
    Fragment fr = fm.findFragmentByTag(FoclConstants.FRAGMENT_YES_NO_DIALOG + "CancelObjectCreating");
    if (null != fr) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.remove(fr);
        ft.commit();
    }
}

From source file:com.android.gpstest.GpsTestActivity.java

/** Called when the activity is first created. */
@Override//from w w w.j a v a2 s.c  om
public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);
    sInstance = this;

    // Set the default values from the XML file if this is the first
    // execution of the app
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    mService = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Permission Denied
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
        finish();
        return;
    } else {
        mProvider = mService.getProvider(LocationManager.GPS_PROVIDER);
        if (mProvider == null) {
            Log.e(TAG, "Unable to get GPS_PROVIDER");
            Toast.makeText(this, getString(R.string.gps_not_supported), Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
    }
    mService.addGpsStatusListener(this);

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    // If we have a large screen, show all the fragments in one layout
    if (GpsTestUtil.isLargeScreen(this)) {
        setContentView(R.layout.activity_main_large_screen);
        mIsLargeScreen = true;
    } else {
        setContentView(R.layout.activity_main);
    }

    initActionBar(savedInstanceState);

    SharedPreferences settings = Application.getPrefs();

    double tempMinTime = Double.valueOf(settings.getString(getString(R.string.pref_key_gps_min_time),
            getString(R.string.pref_gps_min_time_default_sec)));
    minTime = (long) (tempMinTime * SECONDS_TO_MILLISECONDS);
    minDistance = Float.valueOf(settings.getString(getString(R.string.pref_key_gps_min_distance),
            getString(R.string.pref_gps_min_distance_default_meters)));

    if (settings.getBoolean(getString(R.string.pref_key_auto_start_gps), true)) {
        gpsStart();
    }
}