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:de.grobox.liberario.activities.MainActivity.java

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

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

    final TransportNetwork network = Preferences.getTransportNetwork(this);

    // Handle Toolbar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from   w  w w .  j  av  a  2 s  .  c  om

    // Accounts aka TransportNetworks
    accountHeader = new AccountHeaderBuilder().withActivity(this)
            .withHeaderBackground(R.drawable.account_header_background).withSelectionListEnabled(false)
            .withThreeSmallProfileImages(true)
            .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                @Override
                public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
                    if (currentProfile) {
                        return true;
                    } else if (profile != null && profile instanceof ProfileDrawerItem) {
                        TransportNetwork network = (TransportNetwork) ((ProfileDrawerItem) profile).getTag();
                        if (network != null) {
                            // save new network
                            Preferences.setNetworkId(getContext(), network.getId());

                            // notify everybody of this change
                            onNetworkProviderChanged();
                        }
                    }
                    return false;
                }
            }).build();

    // Drawer
    drawer = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withAccountHeader(accountHeader)
            .addDrawerItems(getDrawerItem(DirectionsFragment.TAG, R.drawable.ic_menu_directions),
                    getDrawerItem(RecentTripsFragment.TAG, R.drawable.ic_tab_recents),
                    getDrawerItem(DeparturesFragment.TAG, R.drawable.ic_action_departures),
                    getDrawerItem(NearbyStationsFragment.TAG, R.drawable.ic_tab_stations),
                    new DividerDrawerItem(), getDrawerItem(SettingsFragment.TAG, R.drawable.ic_action_settings),
                    getDrawerItem(TransportrChangeLog.TAG, R.drawable.ic_action_changelog),
                    getDrawerItem(AboutMainFragment.TAG, R.drawable.ic_action_about))
            .withOnDrawerListener(new Drawer.OnDrawerListener() {
                @Override
                public void onDrawerOpened(View drawerView) {
                    KeyboardUtil.hideKeyboard(MainActivity.this);
                }

                @Override
                public void onDrawerClosed(View drawerView) {
                }

                @Override
                public void onDrawerSlide(View drawerView, float slideOffset) {
                }
            }).withFireOnInitialOnClick(false).withSavedInstance(savedInstanceState).build();

    if (savedInstanceState == null) {
        // make the user select a transport network, if none is selected
        ensureTransportNetworkAvailable(network);

        // update drawer items to reflect network capabilities
        updateDrawerItems(network);

        // show network name in toolbar subtitle
        if (network != null) {
            toolbar.setSubtitle(network.getName(this));
        }

        // add initial fragment
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, new DirectionsFragment(), DirectionsFragment.TAG).commit();
    } else {
        // restore toolbar title
        String tag = getCurrentFragmentTag();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
            actionBar.setTitle(getFragmentName(tag));

        if (network != null && !tag.equals(AboutMainFragment.TAG) && !tag.equals(SettingsFragment.TAG)) {
            toolbar.setSubtitle(network.getName(this));
        }

        processIntent();
    }

    getSupportFragmentManager().addOnBackStackChangedListener(this);

    // add transport networks to header
    addAccounts(network);

    // show Changelog if something is new
    TransportrChangeLog cl = new TransportrChangeLog(this, Preferences.darkThemeEnabled(this));
    if (cl.isFirstRun() && !cl.isFirstRunEver()) {
        cl.getLogDialog().show();
    }

    // create Android 7.1 shortcut
    registerNougatShortcuts();
}

From source file:com.abhijitvalluri.android.fitnotifications.HomeFragment.java

private void initializeSettings() {
    PreferenceManager.setDefaultValues(mContext, R.xml.main_settings, false);
    mPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    mDismissPlaceholderNotif = mPreferences.getBoolean(getString(R.string.dismiss_placeholder_notif_key),
            false);//w w w .  j  a  va 2s  .c  o  m
    mPlaceholderNotifDismissDelayMillis = mPreferences.getInt(getString(R.string.placeholder_dismiss_delay_key),
            Constants.DEFAULT_DELAY_SECONDS) * 1000;
}

From source file:de.lespace.apprtc.activity.ConnectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_connect);

    // Get setting keys.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    keyprefFrom = getString(R.string.pref_from_key);
    keyprefVideoCallEnabled = getString(R.string.pref_videocall_key);
    keyprefResolution = getString(R.string.pref_resolution_key);
    keyprefFps = getString(R.string.pref_fps_key);
    keyprefCaptureQualitySlider = getString(R.string.pref_capturequalityslider_key);
    keyprefVideoBitrateType = getString(R.string.pref_startvideobitrate_key);
    keyprefVideoBitrateValue = getString(R.string.pref_startvideobitratevalue_key);
    keyprefVideoCodec = getString(R.string.pref_videocodec_key);
    keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key);
    keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key);
    keyprefAudioBitrateType = getString(R.string.pref_startaudiobitrate_key);
    keyprefAudioBitrateValue = getString(R.string.pref_startaudiobitratevalue_key);
    keyprefAudioCodec = getString(R.string.pref_audiocodec_key);
    keyprefNoAudioProcessingPipeline = getString(R.string.pref_noaudioprocessing_key);
    keyprefAecDump = getString(R.string.pref_aecdump_key);
    keyprefOpenSLES = getString(R.string.pref_opensles_key);
    keyprefDisplayHud = getString(R.string.pref_displayhud_key);
    keyprefTracing = getString(R.string.pref_tracing_key);
    keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key);
    keyprefRoomList = getString(R.string.pref_room_list_key);

    // Video call enabled flag.
    boolean videoCallEnabled = sharedPref.getBoolean(keyprefVideoCallEnabled,
            Boolean.valueOf(getString(R.string.pref_videocall_default)));

    String wssUrl = sharedPref.getString(keyprefRoomServerUrl,
            getString(R.string.pref_room_server_url_default));
    from = sharedPref.getString(keyprefFrom, getString(R.string.pref_from_default));
    // Get default codecs.
    String videoCodec = sharedPref.getString(keyprefVideoCodec, getString(R.string.pref_videocodec_default));
    String audioCodec = sharedPref.getString(keyprefAudioCodec, getString(R.string.pref_audiocodec_default));

    // Check HW codec flag.
    boolean hwCodec = sharedPref.getBoolean(keyprefHwCodecAcceleration,
            Boolean.valueOf(getString(R.string.pref_hwcodec_default)));

    // Check Capture to texture.
    boolean captureToTexture = sharedPref.getBoolean(keyprefCaptureToTexture,
            Boolean.valueOf(getString(R.string.pref_capturetotexture_default)));

    // Check Disable Audio Processing flag.
    boolean noAudioProcessing = sharedPref.getBoolean(keyprefNoAudioProcessingPipeline,
            Boolean.valueOf(getString(R.string.pref_noaudioprocessing_default)));

    // Check Disable Audio Processing flag.
    boolean aecDump = sharedPref.getBoolean(keyprefAecDump,
            Boolean.valueOf(getString(R.string.pref_aecdump_default)));

    // Check OpenSL ES enabled flag.
    boolean useOpenSLES = sharedPref.getBoolean(keyprefOpenSLES,
            Boolean.valueOf(getString(R.string.pref_opensles_default)));

    // Check for mandatory permissions.
    missingPermissions = new ArrayList();

    for (String permission : MANDATORY_PERMISSIONS) {
        if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(permission);
        }/*from   w  ww .  j  av  a  2  s.co m*/
    }
    requestPermission();

    networkchangeBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getFlags() == 0) {
                SignalingService.appRTCClient.resetWebsocket();
            }
            if (intent.getFlags() == 1) {
                SignalingService.appRTCClient.reconnect();
                Toast.makeText(context, "network is online:" + intent.getFlags(), Toast.LENGTH_LONG).show();
            }
        }
    };

    // Registering BroadcastReceiver
    registerNetworkChangeReceiver();

    // Get video resolution from settings.
    int videoWidth = 0;
    int videoHeight = 0;
    String resolution = sharedPref.getString(keyprefResolution, getString(R.string.pref_resolution_default));
    String[] dimensions = resolution.split("[ x]+");
    if (dimensions.length == 2) {
        try {
            videoWidth = Integer.parseInt(dimensions[0]);
            videoHeight = Integer.parseInt(dimensions[1]);
        } catch (NumberFormatException e) {
            videoWidth = 0;
            videoHeight = 0;
            Log.e(TAG, "Wrong video resolution setting: " + resolution);
        }
    }

    // Get camera fps from settings.
    int cameraFps = 0;
    String fps = sharedPref.getString(keyprefFps, getString(R.string.pref_fps_default));
    String[] fpsValues = fps.split("[ x]+");
    if (fpsValues.length == 2) {
        try {
            cameraFps = Integer.parseInt(fpsValues[0]);
        } catch (NumberFormatException e) {
            Log.e(TAG, "Wrong camera fps setting: " + fps);
        }
    }

    // Check capture quality slider flag.
    boolean captureQualitySlider = sharedPref.getBoolean(keyprefCaptureQualitySlider,
            Boolean.valueOf(getString(R.string.pref_capturequalityslider_default)));

    // Get video and audio start bitrate.
    int videoStartBitrate = 0;
    String bitrateTypeDefault = getString(R.string.pref_startvideobitrate_default);
    String bitrateType = sharedPref.getString(keyprefVideoBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefVideoBitrateValue,
                getString(R.string.pref_startvideobitratevalue_default));
        videoStartBitrate = Integer.parseInt(bitrateValue);
    }
    int audioStartBitrate = 0;
    bitrateTypeDefault = getString(R.string.pref_startaudiobitrate_default);
    bitrateType = sharedPref.getString(keyprefAudioBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefAudioBitrateValue,
                getString(R.string.pref_startaudiobitratevalue_default));
        audioStartBitrate = Integer.parseInt(bitrateValue);
    }

    // Check statistics display option.
    boolean displayHud = sharedPref.getBoolean(keyprefDisplayHud,
            Boolean.valueOf(getString(R.string.pref_displayhud_default)));

    boolean tracing = sharedPref.getBoolean(keyprefTracing,
            Boolean.valueOf(getString(R.string.pref_tracing_default)));

    // Log.d(TAG, "Connecting from " + from + " at URL " + wssUrl);

    if (validateUrl(wssUrl)) {
        Uri uri = Uri.parse(wssUrl);
        intent = new Intent(this, ConnectActivity.class);
        intent.setData(uri);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CALL, videoCallEnabled);
        intent.putExtra(CallActivity.EXTRA_VIDEO_WIDTH, videoWidth);
        intent.putExtra(CallActivity.EXTRA_VIDEO_HEIGHT, videoHeight);
        intent.putExtra(CallActivity.EXTRA_VIDEO_FPS, cameraFps);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CAPTUREQUALITYSLIDER_ENABLED, captureQualitySlider);
        intent.putExtra(CallActivity.EXTRA_VIDEO_BITRATE, videoStartBitrate);
        intent.putExtra(CallActivity.EXTRA_VIDEOCODEC, videoCodec);
        intent.putExtra(CallActivity.EXTRA_HWCODEC_ENABLED, hwCodec);
        intent.putExtra(CallActivity.EXTRA_CAPTURETOTEXTURE_ENABLED, captureToTexture);
        intent.putExtra(CallActivity.EXTRA_NOAUDIOPROCESSING_ENABLED, noAudioProcessing);
        intent.putExtra(CallActivity.EXTRA_AECDUMP_ENABLED, aecDump);
        intent.putExtra(CallActivity.EXTRA_OPENSLES_ENABLED, useOpenSLES);
        intent.putExtra(CallActivity.EXTRA_AUDIO_BITRATE, audioStartBitrate);
        intent.putExtra(CallActivity.EXTRA_AUDIOCODEC, audioCodec);
        intent.putExtra(CallActivity.EXTRA_DISPLAY_HUD, displayHud);
        intent.putExtra(CallActivity.EXTRA_TRACING, tracing);
        intent.putExtra(CallActivity.EXTRA_RUNTIME, runTimeMs);
    }

    roomListView = (ListView) findViewById(R.id.room_listview);
    roomListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    connectButton = (ImageButton) findViewById(R.id.connect_button);
    connectButton.setOnClickListener(connectListener);

    // If an implicit VIEW intent is launching the app, go directly to that URL.
    //final Intent intent = getIntent();
    Uri wsurl = Uri.parse(wssUrl);
    //intent.getData();
    // Log.d(TAG, "connecting to:" + wsurl.toString());
    if (wsurl == null) {
        logAndToast(getString(R.string.missing_wsurl));
        Log.e(TAG, "Didn't get any URL in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    if (from == null || from.length() == 0) {
        logAndToast(getString(R.string.missing_from));
        Log.e(TAG, "Incorrect from in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    peerConnectionParameters = new PeerConnectionClient.PeerConnectionParameters(videoCallEnabled, tracing,
            videoWidth, videoHeight, cameraFps, videoStartBitrate, videoCodec, hwCodec, captureToTexture,
            audioStartBitrate, audioCodec, noAudioProcessing, aecDump, useOpenSLES);

    Intent intent = getIntent();
    Log.i(TAG, "created apprtc with uri:" + wsurl.toString() + " from:" + from);

    Log.i(TAG, "intent.EXTRA_TO:" + intent.getStringExtra(RTCConnection.EXTRA_TO));
    Log.i(TAG, "intent.EXTRA_FROM:" + intent.getStringExtra(RTCConnection.EXTRA_FROM));
    Log.i(TAG, "intent.EXTRA_INITIATOR:" + intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR, false));

    if (intent.getStringExtra(RTCConnection.EXTRA_TO) != null
            && !intent.getStringExtra(RTCConnection.EXTRA_TO).equals("")) {

        RTCConnection.to = intent.getStringExtra(RTCConnection.EXTRA_TO);
        RTCConnection.from = intent.getStringExtra(RTCConnection.EXTRA_FROM);
        RTCConnection.initiator = intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR, false);
        ;
        connectToUser();
    }

    /*  if(intent.getStringExtra(RTCConnection.EXTRA_TO)!=null
            && !intent.getStringExtra(RTCConnection.EXTRA_TO).equals("")){
            
          RTCConnection.to = intent.getStringExtra(RTCConnection.EXTRA_TO);
         // RTCConnection.from = intent.getStringExtra(RTCConnection.EXTRA_FROM);
          RTCConnection.initiator = intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR,false);;
            
      Intent serviceIntent = new Intent(this,SignalingService.class);
      serviceIntent.putExtra(RTCConnection.EXTRA_FROM, RTCConnection.to);
            
     //WebRTC-Signaling
     startService(intent);
    }*/

}

From source file:org.digitalcampus.oppia.activity.OppiaMobileActivity.java

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

    setContentView(R.layout.activity_main);

    initializeDagger();/*from  www  . ja v  a  2 s .co m*/

    PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
    prefs.registerOnSharedPreferenceChangeListener(this);

    // set preferred lang to the default lang
    if ("".equals(prefs.getString(PrefsActivity.PREF_LANGUAGE, ""))) {
        prefs.edit().putString(PrefsActivity.PREF_LANGUAGE, Locale.getDefault().getLanguage()).apply();
    }

    messageContainer = this.findViewById(R.id.home_messages);
    messageText = (TextView) this.findViewById(R.id.home_message);
    messageButton = (Button) this.findViewById(R.id.message_action_button);

    courses = new ArrayList<>();
    courseListAdapter = new CourseListAdapter(this, courses);
    courseList = (ListView) findViewById(R.id.course_list);
    courseList.setAdapter(courseListAdapter);

    //the alternative of registerForContextMenu(courseList);
    CourseContextMenuCustom courseMenu = new CourseContextMenuCustom(this);
    courseMenu.registerForContextMenu(courseList, this);

    courseList.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Course selectedCourse = courses.get(position);
            Intent i = new Intent(OppiaMobileActivity.this, CourseIndexActivity.class);
            Bundle tb = new Bundle();
            tb.putSerializable(Course.TAG, selectedCourse);
            i.putExtras(tb);
            startActivity(i);
        }
    });

    llNone = (LinearLayout) this.findViewById(R.id.no_courses);
    initialCourseListPadding = courseList.getPaddingTop();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Initializing Drawer Layout and ActionBarToggle
    final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    ((TextView) navigationView.getHeaderView(0).findViewById(R.id.drawer_user_fullname))
            .setText(SessionManager.getUserDisplayName(this));
    ((TextView) navigationView.getHeaderView(0).findViewById(R.id.drawer_username))
            .setText(SessionManager.getUsername(this));
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            boolean result = onOptionsItemSelected(menuItem);
            menuItem.setChecked(false);
            drawerLayout.closeDrawers();
            return result;
        }
    });

    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.open, R.string.close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
}

From source file:com.benlinskey.greekreference.MainActivity.java

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

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

    // Restore any saved state.
    if (null == savedInstanceState) {
        mTitle = getString(R.string.title_lexicon);
        mSubtitle = getString(R.string.title_lexicon_browse);
    } else {/*w  w  w . java 2s .c o  m*/
        mTitle = savedInstanceState.getString(KEY_TITLE);
        mSubtitle = savedInstanceState.getString(KEY_SUBTITLE);
        mMode = Mode.getModeFromName(savedInstanceState.getString(KEY_MODE));
    }

    mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
            .findFragmentById(R.id.navigation_drawer);

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));

    if (findViewById(R.id.item_detail_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-large and
        // res/values-sw600dp)..
        mTwoPane = true;
    }

    checkTabletDisplayMode();
    handleIntent(getIntent());
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    UIUtilities.configureActionBar(this, false, true, R.string.narrative_list_header, 0);
    setContentView(R.layout.narrative_browser);

    // load previous id on screen rotation
    if (savedInstanceState != null) {
        mPreviousSavedState = savedInstanceState; // for horizontal scroll position loading (NarrativeAdapter)
        mCurrentSelectedNarrativeId = savedInstanceState.getString(getString(R.string.extra_internal_id));
        // mScrollNarrativesToEnd = savedInstanceState.getInt(getString(R.string.extra_start_scrolled_to_end), 0);
    } else {/*w  w w .  ja  va 2 s  .  c  o m*/
        // initialise preferences on first run, and perform an upgrade if applicable
        PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
        UpgradeManager.upgradeApplication(NarrativeBrowserActivity.this);

        // delete old media on startup (but not on screen rotation) - immediate task so we don't block the queue
        runImmediateBackgroundTask(getMediaCleanupRunnable());
    }

    initialiseNarrativesView();
}

From source file:weathernotificationservice.wns.activities.MainActivity.java

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    setTheme(theme = getTheme(prefs.getString("theme", "fresh")));
    boolean darkTheme = theme == R.style.AppTheme_NoActionBar_Dark
            || theme == R.style.AppTheme_NoActionBar_Classic_Dark;

    // 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);//from w w  w  .jav  a 2 s  . c om
    if (darkTheme) {
        toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
    }

    // 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);

    destroyed = false;

    initMappings();

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

    // Set autoupdater
    AlarmReceiver.setRecurringAlarm(this);

}

From source file:net.vexelon.bgrates.ui.activities.MainActivity.java

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

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setTitle(R.string.app_name_pure);
    // actionBar.setDisplayUseLogoEnabled(true);
    // actionBar.setLogo(R.drawable.icon);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override/*from  ww  w .  ja v a  2 s .  c o  m*/
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar
                .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

    // load default values
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    // Start Service
    startService();
}

From source file:com.jaguarlandrover.auto.remote.vehicleentry.LockActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        Intent intent = new Intent();
        intent.setClass(LockActivity.this, AdvancedPreferenceActivity.class);
        startActivityForResult(intent, 0);
        return true;
    } else if (id == R.id.action_reset) {
        PreferenceManager.getDefaultSharedPreferences(this).edit().clear().apply(); //reset
        PreferenceManager.setDefaultValues(this, R.xml.advanced, true);
        return true;
    } else if (id == R.id.action_quit) {
        Intent i = new Intent(this, RviService.class);
        stopService(i);// w w  w  .  j  av  a2s  .c om
        finish();
    }

    return super.onOptionsItemSelected(item);
}

From source file:org.asnelt.derandom.MainActivity.java

/**
 * Initializes this activity and eventually recovers its state.
 * @param savedInstanceState Bundle with saved state
 *///from ww w . j  a  v  a 2s  .com
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    textHistoryInput = (HistoryView) findViewById(R.id.text_history_input);
    textHistoryInput.setHistoryViewListener(this);
    textHistoryPrediction = (HistoryView) findViewById(R.id.text_history_prediction);
    textHistoryPrediction.setHistoryViewListener(this);
    textPrediction = (TextView) findViewById(R.id.text_prediction);
    textInput = (EditText) findViewById(R.id.text_input);
    spinnerInput = (Spinner) findViewById(R.id.spinner_input);
    spinnerGenerator = (Spinner) findViewById(R.id.spinner_generator);
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);

    textInput.setRawInputType(InputType.TYPE_CLASS_NUMBER);
    textHistoryInput.setHorizontallyScrolling(true);
    textHistoryPrediction.setHorizontallyScrolling(true);
    textPrediction.setHorizontallyScrolling(true);
    textHistoryInput.setMovementMethod(new ScrollingMovementMethod());
    textHistoryPrediction.setMovementMethod(new ScrollingMovementMethod());
    textPrediction.setMovementMethod(new ScrollingMovementMethod());

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setIcon(R.drawable.ic_launcher);
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    processingFragment = (ProcessingFragment) fragmentManager.findFragmentByTag(TAG_PROCESSING_FRAGMENT);
    // Generate new fragment if there is no retained fragment
    if (processingFragment == null) {
        processingFragment = new ProcessingFragment();
        fragmentManager.beginTransaction().add(processingFragment, TAG_PROCESSING_FRAGMENT).commit();
    }
    // Apply predictions length preference
    int predictionLength = getNumberPreference(SettingsActivity.KEY_PREF_PREDICTION_LENGTH);
    processingFragment.setPredictionLength(predictionLength);
    // Apply server port preference
    int serverPort = getNumberPreference(SettingsActivity.KEY_PREF_SOCKET_PORT);
    processingFragment.setServerPort(serverPort);
    // Apply history length preference
    int historyLength = getNumberPreference(SettingsActivity.KEY_PREF_HISTORY_LENGTH);
    textHistoryInput.setCapacity(historyLength);
    textHistoryPrediction.setCapacity(historyLength);
    processingFragment.setCapacity(historyLength);
    // Apply color preference
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (sharedPreferences.getBoolean(SettingsActivity.KEY_PREF_COLORED_PAST, true)) {
        textHistoryPrediction.enableColor(null);
    }
    // Apply auto-detect preference
    boolean autoDetect = sharedPreferences.getBoolean(SettingsActivity.KEY_PREF_AUTO_DETECT, true);
    processingFragment.setAutoDetect(autoDetect);

    // Eventually recover state
    if (savedInstanceState != null) {
        Layout layout = textHistoryInput.getLayout();
        if (layout != null) {
            textHistoryInput.scrollTo(0, layout.getHeight());
        }
        layout = textHistoryPrediction.getLayout();
        if (layout != null) {
            textHistoryPrediction.scrollTo(0, layout.getHeight());
        }
        textPrediction.scrollTo(0, 0);
        Uri inputUri = processingFragment.getInputUri();
        if (inputUri != null) {
            disableDirectInput(inputUri);
        }
        if (processingFragment.getInputSelection() == INDEX_SOCKET_INPUT) {
            disableDirectInput(null);
        }
    }

    // Create an ArrayAdapter using the string array and a default spinner layout
    String[] inputNames = new String[3];
    inputNames[INDEX_DIRECT_INPUT] = getResources().getString(R.string.input_direct_name);
    inputNames[INDEX_FILE_INPUT] = getResources().getString(R.string.input_file_name);
    inputNames[INDEX_SOCKET_INPUT] = getResources().getString(R.string.input_socket_name);
    ArrayAdapter<String> spinnerInputAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,
            inputNames);
    // Specify the layout to use when the list of choices appears
    spinnerInputAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinnerInput.setAdapter(spinnerInputAdapter);
    spinnerInput.setOnItemSelectedListener(this);
    if (spinnerInput.getSelectedItemPosition() != processingFragment.getInputSelection()) {
        spinnerInput.setSelection(processingFragment.getInputSelection());
    }

    // Create an ArrayAdapter using the string array and a default spinner layout
    String[] generatorNames = processingFragment.getGeneratorNames();
    ArrayAdapter<String> spinnerGeneratorAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_item, generatorNames);
    // Specify the layout to use when the list of choices appears
    spinnerGeneratorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinnerGenerator.setAdapter(spinnerGeneratorAdapter);
    spinnerGenerator.setOnItemSelectedListener(this);

    if (processingFragment.isMissingUpdate()) {
        // The activity missed an update while it was reconstructed
        processingFragment.updateAll();
    }
    onProgressUpdate();
}