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.baumann.hhsmoodle.data_todo.Todo_Fragment.java

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

    PreferenceManager.setDefaultValues(getActivity(), R.xml.user_settings, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());

    imgHeader = (ImageView) rootView.findViewById(R.id.imageView_header);
    helper_main.setImageHeader(getActivity(), imgHeader);

    filter_layout = (RelativeLayout) rootView.findViewById(R.id.filter_layout);
    filter_layout.setVisibility(View.GONE);
    lv = (ListView) rootView.findViewById(R.id.listNotes);
    filter = (EditText) rootView.findViewById(R.id.myFilter);
    viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);

    ImageButton ib_hideKeyboard = (ImageButton) rootView.findViewById(R.id.ib_hideKeyboard);
    ib_hideKeyboard.setOnClickListener(new View.OnClickListener() {
        @Override//  w  w w  .j  av a 2 s .  c  o m
        public void onClick(View view) {
            if (filter.getText().length() > 0) {
                filter.setText("");
            } else {
                setTitle();
                helper_main.hideFilter(getActivity(), filter_layout, imgHeader);
                setTodoList();
            }
        }
    });

    fabLayout1 = (LinearLayout) rootView.findViewById(R.id.fabLayout1);
    fabLayout2 = (LinearLayout) rootView.findViewById(R.id.fabLayout2);
    fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
    FloatingActionButton fab1 = (FloatingActionButton) rootView.findViewById(R.id.fab1);
    FloatingActionButton fab2 = (FloatingActionButton) rootView.findViewById(R.id.fab2);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!isFABOpen) {
                showFABMenu();
            } else {
                closeFABMenu();
            }
        }
    });

    fab1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            closeFABMenu();
            Todo_helper.newTodo(getActivity(), "", "", "");
        }
    });

    fab2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            closeFABMenu();
            Intent mainIntent = new Intent(getActivity(), Popup_courseList.class);
            mainIntent.setAction("courseList_todo");
            startActivity(mainIntent);
        }
    });

    //calling Notes_DbAdapter
    db = new Todo_DbAdapter(getActivity());
    db.open();

    setTodoList();
    setHasOptionsMenu(true);

    return rootView;
}

From source file:com.cloudbees.gasp.activity.GaspRESTLoaderActivity.java

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

    // Set main content view for Gasp! Reviews
    setContentView(R.layout.gasp_review_activity);

    // Use the Fragments API to display review data
    FragmentManager fm = getFragmentManager();
    ListFragment list = (ListFragment) fm.findFragmentById(R.id.gasp_review_content);
    if (list == null) {
        list = new ListFragment();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.gasp_review_content, list);
        ft.commit();/*from  w w w.  j a v  a2 s.  c om*/
    }

    // Array adapter provides access to the review list data
    mAdapter = new ArrayAdapter<String>(this, R.layout.gasp_review_list);
    list.setListAdapter(mAdapter);

    // Load shared preferences from res/xml/preferences.xml (first time only)
    // Subsequent activations will use the saved shared preferences from the device
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    SharedPreferences gaspSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    Log.i(TAG, "Using Gasp Server URI: " + gaspSharedPreferences.getString("gasp_endpoint_uri", ""));
    Uri gaspReviewsUri = Uri.parse(gaspSharedPreferences.getString("gasp_endpoint_uri", ""));

    // Loader arguments: LoaderManager will maintain the state of our Loaders
    // and reload if necessary. 
    Bundle args = new Bundle();
    Bundle params = new Bundle();
    args.putParcelable(ARGS_URI, gaspReviewsUri);
    args.putParcelable(ARGS_PARAMS, params);

    // Initialize the Loader.
    getLoaderManager().initLoader(LOADER_GASP_REVIEWS, args, this);

    // Use gasp-mongo REST service
    new ReviewsRequest().execute();

    try {
        LocationsRequest locations = new LocationsRequest(
                new SpatialQuery(new Location(-122.1139858, 37.3774655), 0.005));

        List<GeoLocation> locationList = locations.execute().get();
        for (GeoLocation geoLocation : locationList) {
            Log.i(TAG, geoLocation.getName());
            Log.i(TAG, " " + geoLocation.getFormattedAddress());
            Log.i(TAG, " " + String.valueOf(geoLocation.getLocation().getLng()));
            Log.i(TAG, " " + String.valueOf(geoLocation.getLocation().getLat()));
        }
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
}

From source file:uk.org.downiesoft.slideshow.SlideShowActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Window win = getWindow();/* w w w.j av a 2 s . c o  m*/
    win.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
            WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    win.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
            WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    win.requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    mUiHider = new UiHider(this);
    getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(mUiHider);
    mCacheManager = ThumbnailCacheManager.getInstance(this);
    SlideShowActivity.debug(1, TAG, "onCreate: %s",
            savedInstanceState == null ? "null" : savedInstanceState.toString());
    setContentView(R.layout.activity_slide_show);
    PreferenceManager.setDefaultValues(this, R.xml.view_preferences, false);
    PreferenceManager.setDefaultValues(this, R.xml.slideshow_preferences, false);
    PreferenceManager.setDefaultValues(this, R.xml.cache_preferences, false);
    PreferenceManager.setDefaultValues(this, R.xml.wallpaper_preferences, false);
    PreferenceManager.setDefaultValues(this, R.xml.other_preferences, false);
    mSlideshowSettings = PreferenceManager.getDefaultSharedPreferences(this);
    int thumbSize = Integer.parseInt(mSlideshowSettings.getString(getString(R.string.PREFS_THUMBSIZE), "1"));
    // Hack to convert old hard-coded thumbsize settings to platform dependent sizes
    if (thumbSize > 2) {
        thumbSize = thumbSize / 90;
        SharedPreferences.Editor editor = mSlideshowSettings.edit();
        editor.putString(getString(R.string.PREFS_THUMBSIZE), Integer.toString(thumbSize));
        editor.apply();
    }
    FragmentManager fm = getFragmentManager();
    int cacheLimit = Integer
            .parseInt(mSlideshowSettings.getString(getString(R.string.PREFS_CACHE_LIMIT), "10"));
    mPreviewButton = (ImageView) findViewById(R.id.slideShowImageButton);
    mPreviewView = (FrameLayout) findViewById(R.id.previewContainer);
    RelativeLayout divider = (RelativeLayout) findViewById(R.id.frameDivider);
    if (divider != null) {
        divider.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                return mGestureDetector.onTouchEvent(event) || view.onTouchEvent(event);
            }
        });
    }
    mPreviewFragment = (PreviewFragment) fm.findFragmentByTag(PreviewFragment.TAG);
    if (mPreviewView != null && mPreviewFragment == null) {
        mPreviewFragment = new PreviewFragment();
        fm.beginTransaction().replace(R.id.previewContainer, mPreviewFragment, PreviewFragment.TAG).commit();
    }
    mGridViewFragment = (GridViewFragment) fm.findFragmentByTag(GridViewFragment.TAG);
    if (mGridViewFragment == null) {
        mGridViewFragment = new GridViewFragment();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.fragmentContainer, mGridViewFragment, GridViewFragment.TAG);
        ft.commit();
    }
    mGestureDetector = new GestureDetector(this, new DividerGestureListener());
    // restart/stop service as required
    Intent intent = getIntent();
    if (intent != null && intent.getAction() != null && intent.getAction().equals(ACTION_STOP_WALLPAPER)
            && isServiceRunning()) {
        stopWallpaperService();
        finish();
    } else {
        if (!mSlideshowSettings.getBoolean(getString(R.string.PREFS_WALLPAPER_ENABLE), false)) {
            if (isServiceRunning()) {
                stopWallpaperService();
            }
        } else {
            if (!isServiceRunning()) {
                Intent startIntent = new Intent(SlideShowActivity.this, WallpaperService.class);
                startService(startIntent);
                invalidateOptionsMenu();
            }
        }
    }
    mCacheManager.tidyCache(cacheLimit);
    BitmapManager.setDisplayMetrics(getResources().getDisplayMetrics());
}

From source file:org.nsdev.apps.superhappyhackmap.activities.MainActivity.java

/**
 * Called when the activity is first created.
 *
 * @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). <b>Note: Otherwise it is null.</b>
 *///from   www  . jav a2  s . c om
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, "onCreate");

    setContentView(R.layout.main);

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

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(googleMap -> {
        map = googleMap;
        setupMap();
        HackTimerApp.getBus().post(new HackDatabaseUpdatedEvent());
    });

    int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (errorCode != ConnectionResult.SUCCESS) {
        GooglePlayServicesUtil.getErrorDialog(errorCode, this, 0).show();
        return;
    }

    checkPermissions(66, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, () -> {
        Intent i = new Intent(getBaseContext(), LocationLockService.class);
        i.setAction(LocationLockService.ACTION_MONITOR_LOCATION);
        startService(i);
    }, requestPermissionsRunnable -> {
        requestPermissionsRunnable.run();
    }, () -> {
        // Show Error
        Toast.makeText(this, R.string.permissions_location_error, Toast.LENGTH_LONG).show();
    });

    // Obtain the FirebaseAnalytics instance.
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    HackReceiver.trigger(getBaseContext());
}

From source file:net.homelinux.penecoptero.android.citybikes.donation.app.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from   w ww . j  a va  2s  .co m*/
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    mapView = (MapView) findViewById(R.id.mapview);
    mSlidingDrawer = (StationSlidingDrawer) findViewById(R.id.drawer);
    infoLayer = (InfoLayer) findViewById(R.id.info_layer);
    scale = getResources().getDisplayMetrics().density;
    //Log.i("CityBikes","ON CREATEEEEEEEEE!!!!!");
    infoLayerPopulator = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == InfoLayer.POPULATE) {
                infoLayer.inflateStation(stations.getCurrent());

            }
            if (msg.what == CityBikes.BOOKMARK_CHANGE) {
                int id = msg.arg1;
                boolean bookmarked;
                if (msg.arg2 == 0) {
                    bookmarked = false;
                } else {
                    bookmarked = true;
                }
                StationOverlay station = stations.getById(id);
                try {
                    BookmarkManager bm = new BookmarkManager(getApplicationContext());
                    bm.setBookmarked(station.getStation(), !bookmarked);
                } catch (Exception e) {
                    Log.i("CityBikes", "Error bookmarking station");
                    e.printStackTrace();
                }

                if (!view_all) {
                    view_near();
                }
                mapView.postInvalidate();
            }
        }
    };

    infoLayer.setHandler(infoLayerPopulator);
    RelativeLayout.LayoutParams zoomControlsLayoutParams = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    zoomControlsLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    zoomControlsLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

    mapView.addView(mapView.getZoomControls(), zoomControlsLayoutParams);

    modeButton = (ToggleButton) findViewById(R.id.mode_button);

    modeButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            changeMode(!getBike);
        }

    });

    applyMapViewLongPressListener(mapView);

    settings = getSharedPreferences(CityBikes.PREFERENCES_NAME, 0);

    List<Overlay> mapOverlays = mapView.getOverlays();

    locator = new Locator(this, new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == Locator.LOCATION_CHANGED) {
                GeoPoint point = new GeoPoint(msg.arg1, msg.arg2);
                hOverlay.moveCenter(point);
                mapView.getController().animateTo(point);
                mDbHelper.setCenter(point);
                // Location has changed
                try {
                    mDbHelper.updateDistances(point);
                    infoLayer.update();
                    if (!view_all) {
                        view_near();
                    }
                } catch (Exception e) {

                }
                ;
            }
        }
    });

    hOverlay = new HomeOverlay(locator.getCurrentGeoPoint(), new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HomeOverlay.MOTION_CIRCLE_STOP) {
                try {
                    if (!view_all) {
                        view_near();
                    }
                    mapView.postInvalidate();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });

    stations = new StationOverlayList(mapOverlays, new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //Log.i("CityBikes","Message: "+Integer.toString(msg.what)+" "+Integer.toString(msg.arg1));
            if (msg.what == StationOverlay.TOUCHED && msg.arg1 != -1) {
                // One station has been touched
                stations.setCurrent(msg.arg1, getBike);
                infoLayer.inflateStation(stations.getCurrent());
                //Log.i("CityBikes","Station touched: "+Integer.toString(msg.arg1));
            }
        }
    });

    stations.addOverlay(hOverlay);

    mNDBAdapter = new NetworksDBAdapter(getApplicationContext());

    mDbHelper = new StationsDBAdapter(this, mapView, new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case StationsDBAdapter.FETCH:
                break;
            case StationsDBAdapter.UPDATE_MAP:
                progressDialog.dismiss();
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("reload_network", false);
                editor.commit();
            case StationsDBAdapter.UPDATE_DATABASE:
                StationOverlay current = stations.getCurrent();
                if (current == null) {
                    infoLayer.inflateMessage(getString(R.string.no_bikes_around));
                }
                if (current != null) {
                    current.setSelected(true, getBike);
                    infoLayer.inflateStation(current);
                    if (view_all)
                        view_all();
                    else
                        view_near();
                } else {

                }
                mapView.invalidate();
                infoLayer.update();
                ////Log.i("openBicing", "Database updated");
                break;
            case StationsDBAdapter.NETWORK_ERROR:
                ////Log.i("openBicing", "Network error, last update from " + mDbHelper.getLastUpdated());
                Toast toast = Toast.makeText(getApplicationContext(),
                        getString(R.string.network_error) + " " + mDbHelper.getLastUpdated(),
                        Toast.LENGTH_LONG);
                toast.show();
                break;
            }
        }
    }, stations);

    mDbHelper.setCenter(locator.getCurrentGeoPoint());

    mSlidingDrawer.setHandler(new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case StationSlidingDrawer.ITEMCLICKED:
                StationOverlay clicked = (StationOverlay) msg.obj;
                stations.setCurrent(msg.arg1, getBike);
                Message tmp = new Message();
                tmp.what = InfoLayer.POPULATE;
                tmp.arg1 = msg.arg1;
                infoLayerPopulator.dispatchMessage(tmp);
                mapView.getController().animateTo(clicked.getCenter());
            }
        }
    });

    if (savedInstanceState != null) {
        locator.unlockCenter();
        hOverlay.setRadius(savedInstanceState.getInt("homeRadius"));
        this.view_all = savedInstanceState.getBoolean("view_all");
    } else {
        updateHome();
    }

    try {
        mDbHelper.loadStations();
        if (savedInstanceState == null) {
            String strUpdated = mDbHelper.getLastUpdated();

            Boolean dirty = settings.getBoolean("reload_network", false);

            if (strUpdated == null || dirty) {
                this.fillData(view_all);
            } else {
                Toast toast = Toast.makeText(this.getApplicationContext(),
                        "Last Updated: " + mDbHelper.getLastUpdated(), Toast.LENGTH_LONG);
                toast.show();
                Calendar cal = Calendar.getInstance();
                long now = cal.getTime().getTime();
                if (Math.abs(now - mDbHelper.getLastUpdatedTime()) > 60000 * 5)
                    this.fillData(view_all);
            }
        }

    } catch (Exception e) {
        ////Log.i("openBicing", "SHIT ... SUCKS");
    }
    ;

    if (view_all)
        view_all();
    else
        view_near();
    ////Log.i("openBicing", "CREATE!");
}

From source file:damo.three.ie.activity.PrepayCreditActivity.java

/**
 * Called when the activity is first created or re-created due to configuration change. e.g. device rotation
 *
 * @param savedInstanceState Saved Bundle
 *//*from   ww  w  .ja  va2 s . c  o m*/
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        refreshedOnStart = savedInstanceState.getBoolean("refreshed_on_start", false);
        refreshDoneSinceLoadingPersistedData = savedInstanceState.getBoolean("loaded_persisted_on_start",
                false);
    }

    PreferenceManager.setDefaultValues(this, R.xml.settings, false);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    usageSharedPreferences = getSharedPreferences("damo.three.ie.previous_usage", Context.MODE_PRIVATE);

    // Register or clear background update alarms depending if they are enabled or not.
    boolean backgroundUpdate = sharedPreferences.getBoolean(getString(R.string.backgroundupdate), true);
    UsageUtils.setupBackgroundUpdateAlarms(getApplicationContext(), backgroundUpdate);

    ActionBar actionBar = getSupportActionBar();
    actionBar.show();

    setContentView(R.layout.main_usage_layout);
    lastRefreshed = (TextView) findViewById(R.id.textview_last_refreshed);
    lastRefreshed.setOnClickListener(new OnLastRefreshedTextViewClickListener());

    errorLayout = (RelativeLayout) findViewById(R.id.error_layout);

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setOnRefreshListener(new OnSwipeRefreshLayoutListener());
    swipeRefreshLayout.setColorSchemeResources(R.color.holo_purple, R.color.holo_green_light,
            R.color.holo_orange_light, R.color.holo_red_light);

    scrollView = (ExtendedScrollView) findViewById(R.id.usage_scroll_view);
    scrollView.setOnScrollViewListener(new ExtendedScrollView.OnScrollViewListener() {
        @Override
        public void onScrollChanged(ExtendedScrollView v, int l, int t, int oldl, int oldt) {
            View view = scrollView.getChildAt(0);
            // If we are at top of scrollview, enable the swipe refresh layout again, else keep disabled to prevent
            // scrolling the scrollview triggering a refresh.
            if (view.getTop() == scrollView.getScrollY()) {
                swipeRefreshLayout.setEnabled(true);
            } else {
                swipeRefreshLayout.setEnabled(false);
            }
        }
    });

    baseUsageView = (LinearLayout) findViewById(R.id.usage_layout);

    // maybe user rotated the device and fragment already exists?
    FragmentManager fm = getSupportFragmentManager();
    updateFragment = (UpdateFragment) fm.findFragmentByTag("usage_fetcher");

    if (updateFragment == null) {
        updateFragment = new UpdateFragment();
        // consider that activity may be destroyed
        fm.beginTransaction().add(updateFragment, "usage_fetcher").commitAllowingStateLoss();
    }

    // if we had already fetched usages, show them on the newly created activity
    if (updateFragment.getItems() != null) {
        displayUsages(updateFragment.getItems());
        updateLastRefreshedTextView(
                new PrettyTime().format(new Date((updateFragment.getDateTime().getMillis()))));
    }

    //####################################################################################
    /**
     * Temporary bug workaround for:
     * https://code.google.com/p/android/issues/detail?id=77712
     */
    TypedValue typed_value = new TypedValue();
    getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, typed_value, true);
    swipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
    //####################################################################################

    /**
     * if screen was rotated and Activity was re-created while we were fetching usage info, then enable the swipe
     * refresh animation.
     */
    if (updateFragment.isWorking()) {
        swipeRefreshLayout.setRefreshing(true);
        working = true;
    }
}

From source file:com.andrew67.ddrfinder.activity.MapViewer.java

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

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

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.map_viewer);

    progressBar = (CircleProgressBar) findViewById(R.id.progressBar);
    onCreateSavedInstanceState = savedInstanceState;

    ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
}

From source file:com.jakefallin.rhsapp.MainActivity.java

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

    SharedPreferences s = AppController.getAppContext().getSharedPreferences("app", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = s.edit();
    editor.putBoolean("firstTimeSchedule", false);

    PreferenceManager.setDefaultValues(this, R.xml.settings, false);
    boolean firstTime = s.getBoolean("first", true);
    date = s.getString("date", "2016-06-06");

    lastDayOfSchool = Calendar.getInstance();
    lastDayOfSchool.set(2016, 5, 20);//from  ww  w . j av a  2  s .c o m
    firstDayOfSchool = Calendar.getInstance();
    firstDayOfSchool.set(2015, 8, 8);
    current = Calendar.getInstance();

    //Adapter to make tab load a specific fragment within viewpager
    FragmentPagerItemAdapter a = new FragmentPagerItemAdapter(getSupportFragmentManager(),
            FragmentPagerItems.with(this).add("Schedule", ScheduleFragment.class)
                    .add("Absences", AbsencesFragment.class).add("Announcements", AnnouncementsFragment.class)
                    .create());

    //instantiate UI elements
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpagertab);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    backFab = findViewById(R.id.backwardFab);
    forwardFab = findViewById(R.id.forwardFab);
    calFab = findViewById(R.id.calFab);
    fabLayout = (FABToolbarLayout) findViewById(R.id.fabtoolbar);
    containerFab = findViewById(R.id.fabtoolbar_fab);
    dummy = findViewById(R.id.dummy);

    backFab.setOnClickListener(this);
    forwardFab.setOnClickListener(this);
    calFab.setOnClickListener(this);
    containerFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fabLayout.show();
        }
    });
    dummy.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            fabLayout.hide();
            return false;
        }
    });

    //this is fine, UI elements will never be null (hopefully)
    //used to ignore error messages
    assert viewPager != null;
    assert viewPagerTab != null;
    assert navigationView != null;

    //viewpager uses FragmentPagerItemAdapter
    viewPager.setAdapter(a);
    //tab uses fragments (switching with tap/swiping) lifecycle
    viewPagerTab.setViewPager(viewPager);
    //start toolbar
    setSupportActionBar(toolbar);
    setupViewPager(viewPager);

    //setup actionbar with toolbar icons and properties
    ActionBar supportActionBar = getSupportActionBar();
    if (supportActionBar != null) {
        supportActionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
        supportActionBar.setDisplayHomeAsUpEnabled(true);
    }

    //on any click of the navigation view items
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //highlight which item is selected
            int id = menuItem.getItemId();

            //load TeacherSearch activity
            if (id == R.id.teachers) {
                Intent intent = new Intent(MainActivity.this, TeachersActivity.class);
                startActivity(intent);
            }
            //load chat activity
            else if (id == R.id.settings) {
                Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(intent);
            }

            // Closing drawer on item click
            mDrawerLayout.closeDrawers();
            return true;
        }
    });
}

From source file:file_manager.Activity_files.java

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
    }/*from www.ja  va 2s  .  c  o  m*/

    PackageManager pm = getPackageManager();
    boolean isInstalled = isPackageInstalled("de.baumann.pdfcreator", pm);

    if (isInstalled) {
        PackageManager p = getPackageManager();
        p.setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
        Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("de.baumann.pdfcreator");
        LaunchIntent.setAction("pdf_openFolder");
        startActivity(LaunchIntent);
        finish();
    }

    setContentView(R.layout.activity_file_manager);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit()
            .putString("files_startFolder",
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath())
            .apply();

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

    listView = (ListView) findViewById(R.id.listNotes);
    filter_layout = (RelativeLayout) findViewById(R.id.filter_layout);
    filter_layout.setVisibility(View.GONE);
    filter = (EditText) findViewById(R.id.myFilter);

    ImageButton ib_hideKeyboard = (ImageButton) findViewById(R.id.ib_hideKeyboard);
    ib_hideKeyboard.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            filter_layout.setVisibility(View.GONE);
            setFilesList();
        }
    });

    //calling Notes_DbAdapter
    db = new DbAdapter_Files(this);
    db.open();

    setTitle();
    setFilesList();
}

From source file:org.centum.android.MainActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    setTheme(Themes.get(this).getCurrentTheme());
    sqlHelper = StacksDatabaseHelper.get(this);
    setContentView(R.layout.main_activity);

    adFrameLayout = (FrameLayout) findViewById(R.id.ad_frameLayout);

    if (!isProVersion()) {
        adView = new AdView(this);
        adView.setAdSize(AdSize.SMART_BANNER);
        adView.setAdUnitId(KEYS.AD_UNIT_ID);
        adFrameLayout.addView(adView);/*from   w ww  .j  a v a  2 s .  c o  m*/
        AdRequest adRequest = new AdRequest.Builder().addTestDevice(KEYS.TEST_DEVICE).build();
        adView.loadAd(adRequest);
        adView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adView.setAdListener(new AdListener() {
                    @Override
                    public void onAdLoaded() {
                        super.onAdLoaded();
                        adView.setVisibility(View.VISIBLE);
                    }
                });
                adView.setVisibility(View.GONE);
            }
        });
    } else {
        adView = null;
        adFrameLayout.setVisibility(View.GONE);
    }

    slidingPane = (SlidingPaneLayout) findViewById(R.id.slidingPane);
    slidingPane.setCoveredFadeColor(getResources().getColor(android.R.color.transparent));
    slidingPane.setSliderFadeColor(getResources().getColor(android.R.color.transparent));
    slidingPane.setPanelSlideListener(this);

    stackFragment = (StackFragment) getFragmentManager().findFragmentById(R.id.stackFragment);
    cardFragment = (CardFragment) getFragmentManager().findFragmentById(R.id.cardFragment);

    setupUncaughtExceptionHandler();

    if (savedInstanceState != null) {
        dataLoaded = savedInstanceState.getBoolean("dataLoaded", false);

        if (savedInstanceState.containsKey("stack")
                && StackManager.get().getStack(savedInstanceState.getString("stack")) != null) {
            cardFragment.setStack(StackManager.get().getStack(savedInstanceState.getString("stack")));
        }

        if (savedInstanceState.getBoolean("stacksOpened")) {
            showStacks();
            onPanelOpened(null);
        } else {
            showCards();
            onPanelClosed(null);
        }
    } else {
        showStacks();
        onPanelOpened(null);
    }

    if (!dataLoaded || (StackManager.get().getArchivedStackList().size() == 0
            && StackManager.get().getStackList().size() == 0)) {
        loadData();
    }

    getSharedPreferences("properties", MODE_PRIVATE).edit().putInt("version", VERSION).apply();
}