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:zxing.util.CaptureActivity.java

License:asdf

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Window window = getWindow();//from   w w w  .j a v  a 2  s . c om
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.capture);

    backButton = (Button) findViewById(R.id.cancel_capture);
    backButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            CaptureActivity.this.finish();
            Intent backIntent = new Intent(CaptureActivity.this, MainActivity.class);
            startActivity(backIntent);
        }

    });

    hasSurface = false;
    // historyManager = new HistoryManager(this);
    // historyManager.trimHistory();
    inactivityTimer = new InactivityTimer(this);
    beepManager = new BeepManager(this);
    ambientLightManager = new AmbientLightManager(this);

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

From source file:com.nextgis.mobile.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // initialize the default settings
    PreferenceManager.setDefaultValues(this, R.xml.preferences_general, false);
    PreferenceManager.setDefaultValues(this, R.xml.preferences_map, false);
    PreferenceManager.setDefaultValues(this, R.xml.preferences_location, false);
    PreferenceManager.setDefaultValues(this, R.xml.preferences_tracks, false);

    if (!mPreferences.getBoolean(SettingsConstants.KEY_PREF_INTRO, false)) {
        startActivity(new Intent(this, IntroActivity.class));
        finish();/*w w  w .ja  v a 2 s  . c o  m*/
        return;
    }

    setContentView(R.layout.activity_main);
    mMessageReceiver = new MessageReceiver();

    mToolbar = (Toolbar) findViewById(R.id.main_toolbar);
    setSupportActionBar(mToolbar);
    if (null != getSupportActionBar()) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerLayout.setStatusBarBackgroundColor(ControlHelper.getColor(this, R.attr.colorPrimaryDark));

    FragmentManager fm = getSupportFragmentManager();
    mMapFragment = (MapFragment) fm.findFragmentById(R.id.map);
    mMapFragment.getUndoRedoOverlay().setTopToolbar(mToolbar);
    mMapFragment.getEditLayerOverlay().setTopToolbar(mToolbar);
    mMapFragment.getEditLayerOverlay().setBottomToolbar(getBottomToolbar());

    MainApplication app = (MainApplication) getApplication();
    mLayersFragment = (LayersFragment) fm.findFragmentById(R.id.layers);

    if (mLayersFragment != null && null != mLayersFragment.getView()) {
        mLayersFragment.getView().setBackgroundColor(ContextCompat.getColor(this, R.color.color_grey_050));
        // Set up the drawer.
        mLayersFragment.setUp(R.id.layers, drawerLayout, (MapDrawable) app.getMap());
    }

    LayerFillProgressDialogFragment progressFragment = (LayerFillProgressDialogFragment) fm
            .findFragmentByTag(TAG_FRAGMENT_PROGRESS);
    if (progressFragment == null) {
        progressFragment = new LayerFillProgressDialogFragment();
        fm.beginTransaction().add(progressFragment, TAG_FRAGMENT_PROGRESS).commit();
    }

    if (!hasPermissions()) {
        String[] permissions = new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.GET_ACCOUNTS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE };
        requestPermissions(R.string.permissions, R.string.requested_permissions, PERMISSIONS_REQUEST,
                permissions);
    }

    ApkDownloader.check(this, false);
}

From source file:org.runnerup.view.MainLayout.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.main);//from   www. j  a va 2s  . c o m

    int versionCode = 0;
    UpgradeState upgradeState = UpgradeState.UNKNOWN;
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    Editor editor = pref.edit();
    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        versionCode = pInfo.versionCode;
        int version = pref.getInt("app-version", -1);
        if (version == -1) {
            upgradeState = UpgradeState.NEW;
        } else if (versionCode == version) {
            upgradeState = UpgradeState.SAME;
        } else if (versionCode > version) {
            upgradeState = UpgradeState.UPGRADE;
        } else if (versionCode < version) {
            upgradeState = UpgradeState.DOWNGRADE;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    editor.putInt("app-version", versionCode);
    boolean km = Formatter.getUseKilometers(getResources(), pref, editor);

    if (upgradeState == UpgradeState.NEW) {
        editor.putString(getResources().getString(R.string.pref_autolap),
                Double.toString(km ? Formatter.km_meters : Formatter.mi_meters));
    }
    editor.commit();

    // clear basicTargetType between application startup/shutdown
    pref.edit().remove(getString(R.string.pref_basic_target_type)).commit();

    Log.e(getClass().getName(),
            "app-version: " + versionCode + ", upgradeState: " + upgradeState + ", km: " + km);

    // convert pref_mute to pref_mute_bool
    Resources res = getResources();
    try {
        if (pref.contains(res.getString(R.string.pref_mute))) {
            String v = pref.getString(res.getString(R.string.pref_mute), "no");
            editor.putBoolean(res.getString(R.string.pref_mute_bool), v.equalsIgnoreCase("yes"));
            editor.remove(res.getString(R.string.pref_mute));
            editor.commit();
        }
    } catch (Exception e) {
    }

    PreferenceManager.setDefaultValues(this, R.xml.settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.audio_cue_settings, true);

    TabHost tabHost = getTabHost(); // The activity TabHost

    tabHost.addTab(tabHost.newTabSpec("Start")
            .setIndicator(getString(R.string.Start), myGetDrawable(R.drawable.ic_tab_main))
            .setContent(new Intent(this, StartActivity.class)));

    tabHost.addTab(tabHost.newTabSpec("Feed")
            .setIndicator(getString(R.string.feed), myGetDrawable(R.drawable.ic_tab_feed))
            .setContent(new Intent(this, FeedActivity.class)));

    tabHost.addTab(tabHost.newTabSpec("History")
            .setIndicator(getString(R.string.History), myGetDrawable(R.drawable.ic_tab_history))
            .setContent(new Intent(this, HistoryActivity.class)));

    tabHost.addTab(tabHost.newTabSpec("Settings")
            .setIndicator(getString(R.string.Settings), myGetDrawable(R.drawable.ic_tab_setup))
            .setContent(new Intent(this, SettingsActivity.class)));

    tabHost.setCurrentTab(0);
    WidgetUtil.addLegacyOverflowButton(getWindow());

    if (upgradeState == UpgradeState.UPGRADE) {
        whatsNew();
    }
    //GPS is essential, always nag user if not granted
    requestGpsPermissions(this, tabHost.getCurrentView());

    //Import workouts/schemes. No permission needed
    handleBundled(getApplicationContext().getAssets(), "bundled", getFilesDir().getPath() + "/..");

    // if we were called from an intent-filter because user opened "runnerup.db.export", load it
    final Uri data = getIntent().getData();
    if (data != null) {
        if (SettingsActivity.requestReadStoragePermissions(MainLayout.this)) {
            String filePath = null;
            if ("content".equals(data.getScheme())) {
                Cursor cursor = this.getContentResolver().query(data,
                        new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null,
                        null);
                cursor.moveToFirst();
                filePath = cursor.getString(0);
                cursor.close();
            } else {
                filePath = data.getPath();
            }
            Log.i(getClass().getSimpleName(), "Importing database from " + filePath);
            DBHelper.importDatabase(MainLayout.this, filePath);
        } else {
            Toast.makeText(this, "Storage permission not granted in Android settings, db is not imported.",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

From source file:org.hfoss.posit.android.web.Communicator.java

public Communicator(Context _context) {
    mContext = _context;// w w w  .j  a  v a  2 s  . co m
    mTotalTime = 0;
    mStart = 0;

    mHttpParams = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(mHttpParams, CONNECTION_TIMEOUT);

    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(mHttpParams, SOCKET_TIMEOUT);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    mConnectionManager = new ThreadSafeClientConnManager(mHttpParams, registry);
    mHttpClient = new DefaultHttpClient(mConnectionManager, mHttpParams);

    PreferenceManager.setDefaultValues(mContext, R.xml.posit_preferences, false);
    applicationPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    setApplicationAttributes(applicationPreferences.getString("AUTHKEY", ""),
            applicationPreferences.getString("SERVER_ADDRESS", server),
            applicationPreferences.getInt("PROJECT_ID", projectId));
    TelephonyManager manager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    imei = manager.getDeviceId();

}

From source file:net.grobas.blizzardleaderboards.app.ui.MainActivity.java

@Override
protected void onResume() {
    super.onResume();

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String currentHost = sharedPref.getString(Constants.PREFERENCES_HOST_NAME, Constants.EU_HOST);

    LeaderboardDataService.getInstance().setHost(currentHost);
    startLoading();// w w  w . j  a v a 2s . c o  m
    setDataFromService(false);
}

From source file:com.coact.kochzap.CaptureActivity.java

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

    Window window = getWindow();/*from   ww  w .  j a va2s.c om*/
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.capture);

    hasSurface = false;
    inactivityTimer = new InactivityTimer(this);
    beepManager = new BeepManager(this);
    ambientLightManager = new AmbientLightManager(this);

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

From source file:org.artoolkit.ar.unity.UnityARPlayerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // For Epson Moverio BT-200.
    if (Build.MANUFACTURER.equals("EPSON") && Build.MODEL.equals("embt2")) {
        mDisplayControl = new DisplayControl(this);
        //private static final int FLAG_SMARTFULLSCREEN = 0x80000000; // For Epson Moverio BT-200.
        getWindow().addFlags(0x80000000);
    }/*from   ww  w.ja  v  a 2s  .  co m*/

    super.onCreate(savedInstanceState);

    // This needs to be done just only the very first time the application is run,
    // or whenever a new preference is added (e.g. after an application upgrade).
    int resID = getResources().getIdentifier("preferences", "xml", getPackageName());
    PreferenceManager.setDefaultValues(this, resID, false);

    //Request permission to use the camera on android 23+
    int permissionCheck = ContextCompat.checkSelfPermission(this.getApplicationContext(),
            Manifest.permission.CAMERA);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA },
                PERMISSION_REQUEST_CAMERA);
    }
}

From source file:com.hypodiabetic.happ.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    activity = this;
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    ins = this;/*  w w w.  j a v  a2  s . c o m*/
    PreferenceManager.setDefaultValues(this, R.xml.pref_aps, false); //Sets default APS Preferences if the user has not

    //xdrip start
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    checkEula();

    startService(new Intent(getApplicationContext(), DataCollectionService.class));

    PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_bg_notification, false);
    //xdrip end

    setContentView(R.layout.activity_main);
    extendedGraphBuilder = new ExtendedGraphBuilder(this);

    //Setup menu
    tickWhite = getDrawable(R.drawable.checkbox_marked_circle);
    clockWhite = getDrawable(R.drawable.clock);
    tickWhite.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
    clockWhite.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);

    insulinIntegrationApp_status = (TextView) findViewById(R.id.insulinIntegrationApp_status);
    insulinIntegrationApp_icon = (ImageView) findViewById(R.id.insulinIntegrationApp_icon);
    mDrawerList = (ListView) findViewById(R.id.navList);
    String[] osArray = { "Cancel Temp", "Settings", "Integration Report" };
    mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
    mDrawerList.setAdapter(mAdapter);
    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 0:
                pumpAction.cancelTempBasal(MainActivity.activity);
                break;
            case 1:
                startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
                break;
            case 2:
                startActivity(new Intent(getApplicationContext(), Integration_Report.class));
                break;
            }
            mDrawerLayout.closeDrawers();
        }
    });
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerLinear = (LinearLayout) findViewById(R.id.left_drawer);
    mActivityTitle = getTitle().toString();
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.getInstace());
            Date now = new Date();
            Profile p = new Profile(now, MainActivity.getInstace());
            //Local device based Integrations
            String insulin_Integration_App = prefs.getString("insulin_integration", "");

            //Insulin Integration App, try and connect
            if (!insulin_Integration_App.equals("")) {
                InsulinIntegrationApp insulinIntegrationApp = new InsulinIntegrationApp(
                        MainActivity.getInstace(), insulin_Integration_App, "TEST");
                insulinIntegrationApp.connectInsulinTreatmentApp();
                insulinIntegrationApp_status.setText("Connecting...");
                insulinIntegrationApp_icon.setBackground(clockWhite);

                //listens out for connection
                insulinIntegrationAppUpdate = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        insulinIntegrationApp_status.setText(intent.getStringExtra("MSG"));
                        insulinIntegrationApp_icon.setBackground(tickWhite);

                    }
                };
                LocalBroadcastManager.getInstance(MainActivity.getInstace()).registerReceiver(
                        insulinIntegrationAppUpdate, new IntentFilter("INSULIN_INTEGRATION_TEST"));
            } else {
                insulinIntegrationApp_status.setText("No app selected or not in Closed Loop");
                insulinIntegrationApp_icon.setBackgroundResource(R.drawable.alert_circle);
            }
        }

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    mDrawerToggle.syncState();
    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Create the adapter that will return a fragment for each of the 4 primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) this.findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    //mViewPager.setOffscreenPageLimit(4);                                                        //Do not destroy any Fragments, // TODO: 14/09/2015 casues an issue with bvb chart rendering, not sure why
    //Build Fragments
    openAPSFragmentObject = new openAPSFragment();
    iobcobActiveFragmentObject = new iobcobActiveFragment();
    iobcobFragmentObject = new iobcobFragment();
    basalvsTempBasalObject = new basalvsTempBasalFragment();

    //Updates notifications every 60 seconds
    updateEvery60Seconds = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            APSResult apsResult = APSResult.last();
            Notifications.updateCard(context, apsResult);
        }
    };
    registerReceiver(updateEvery60Seconds, new IntentFilter(Intent.ACTION_TIME_TICK));

}

From source file:ca.ualberta.cs.drivr.MainActivity.java

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

    userManager.setConnectivityManager((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE));

    /**//from w w  w. j av a2 s .  co  m
     * This calls the login activity a the beginning if there is no local user stored
     */
    if (userManager.getUser().getUsername().isEmpty()) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    context = getApplicationContext();
    PreferenceManager.setDefaultValues(this, R.xml.pref_driver_mode, false);

    setSupportActionBar(toolbar);

    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    }

    mFragment = (SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.main_map);
    mFragment.getMapAsync(this);

    autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager()
            .findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            ConcretePlace concretePlace = new ConcretePlace(place);
            Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();
            if (userManager.getUserMode().equals(UserMode.RIDER)) {
                Intent intent = new Intent(MainActivity.this, NewRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(NewRequestActivity.EXTRA_PLACE, concretePlaceJson);
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);

            } else if (userManager.getUserMode().equals(UserMode.DRIVER)) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, concretePlaceJson);
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, "");
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);
            }
        }

        @Override
        public void onError(Status status) {
            // Do nothing
        }
    });

    // Using the floating action button menu system
    final FloatingActionMenu fabMenu = (FloatingActionMenu) findViewById(R.id.main_fab_menu);
    FloatingActionButton fabSettings = (FloatingActionButton) findViewById(R.id.fabSettings);
    FloatingActionButton fabRequests = (FloatingActionButton) findViewById(R.id.main_fab_requests);
    FloatingActionButton fabProfile = (FloatingActionButton) findViewById(R.id.main_fab_profile);
    FloatingActionButton fabHistory = (FloatingActionButton) findViewById(R.id.main_fah_history);
    FloatingActionButton fabLogin = (FloatingActionButton) findViewById(R.id.main_fab_login);
    final FloatingActionButton fabDriver = (FloatingActionButton) findViewById(R.id.main_driver_mode);
    final FloatingActionButton fabRider = (FloatingActionButton) findViewById(R.id.main_rider_mode);

    // Hide the settings FAB
    fabSettings.setVisibility(View.GONE);

    /*
    Change between user and driver mode. Will probably be replaced with an option in settings.
    For now the visibility of this is set to gone because we should not have too many FABs.
    Having too many FABs may cause confusion and rendering issues on small screens.
    */
    keywordEditText = (EditText) findViewById(R.id.main_keyword_edit_text);
    FloatingActionButton fabMode = (FloatingActionButton) findViewById(R.id.main_fab_mode);
    fabMode.setVisibility(View.GONE);
    if (userManager.getUserMode().equals(UserMode.RIDER)) {
        fabRider.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.GONE);
    } else {
        fabDriver.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.VISIBLE);
    }

    keywordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, "");
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, keywordEditText.getText().toString());
                keywordEditText.setText("");
                keywordEditText.clearFocus();
                startActivity(intent);
            }
            return true;
        }
    });

    fabMode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked mode fab");
            /*
            Will be able to implement code below once elasticSearch is up and running
            UserManager userManager = null; // Once elasticSearch is working will replace with finding a User
            if (userManager.getUserMode() == UserMode.DRIVER) {
            userManager.setUserMode(UserMode.RIDER);
            }
            else if (userManager.getUserMode() == UserMode.RIDER) {
            userManager.setUserMode(UserMode.DRIVER);
            //Will have to implement a method "FindNearbyRequests" to get requests whose source
            // is nearby and display it on the map
            //Intent intent = new Intent((MainActivity.this, FindNearbyRequests.class);)
            //startActivity(intent);
            }*/
        }
    });

    fabDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (userManager.getUser().getVehicleDescription().isEmpty()) {
                /*
                * From: http://stackoverflow.com/a/29048271
                * Author: Syeda Zunairah
                * Accessed: November 29, 2016
                * Creates a dialog box with an edit text to get the vehicle description.
                */
                AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
                final EditText edittext = new EditText(v.getContext());
                edittext.setText("Vechicle Make");
                edittext.clearComposingText();
                alert.setTitle("Become a Driver!");
                alert.setMessage(
                        "Drivers are require to enter vehicle information!\n\nPlease enter your vehicle's make");

                alert.setView(edittext);

                alert.setPositiveButton("Save Description", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String vehicleDescription = edittext.getText().toString();
                        if (!vehicleDescription.isEmpty()) {
                            userManager.getUser().setVehicleDescription(vehicleDescription);
                            userManager.notifyObservers();
                            userManager.setUserMode(UserMode.DRIVER);
                            ElasticSearch elasticSearch = new ElasticSearch(
                                    userManager.getConnectivityManager());
                            elasticSearch.updateUser(userManager.getUser());
                            keywordEditText.setVisibility(View.VISIBLE);
                            fabDriver.setVisibility(View.GONE);
                            fabRider.setVisibility(View.VISIBLE);
                            fabMenu.close(true);
                        }
                        dialog.dismiss();
                    }
                });

                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });

                AlertDialog newAlert = alert.create();
                newAlert.show();
            }
            if (!userManager.getUser().getVehicleDescription().isEmpty()) {
                userManager.setUserMode(UserMode.DRIVER);
                keywordEditText.setVisibility(View.VISIBLE);
                fabDriver.setVisibility(View.GONE);
                fabRider.setVisibility(View.VISIBLE);
                fabMenu.close(true);
            }
        }
    });

    fabRider.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            userManager.setUserMode(UserMode.RIDER);
            keywordEditText.setVisibility(View.GONE);
            fabRider.setVisibility(View.GONE);
            fabDriver.setVisibility(View.VISIBLE);
            fabMenu.close(true);
        }
    });

    fabLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked settings fab");
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked profile fab");
            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    fabHistory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked history fab");
            Intent intent = new Intent(MainActivity.this, RequestHistoryActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabRequests.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked requests fab");
            Intent intent = new Intent(MainActivity.this, RequestsListActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    setNotificationAlarm(context);
}

From source file:io.mapsquare.osmcontributor.ui.activities.MapActivity.java

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

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

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    setSupportActionBar(toolbar);//  www  . ja  va  2s . c  om

    eventBus.post(new UpdateFirstConnectionEvent());

    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.setChecked(!menuItem.isChecked());
                onFilterItemClick(menuItem);
            } else {
                menuItem.setChecked(!menuItem.isChecked());
                onNoteItemClick(menuItem);
            }
            return true;
        }
    });

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

    if (!FlavorUtils.isPoiStorage() && configManager.hasPoiModification()) {
        navigationView.getMenu().findItem(R.id.edit_way).setVisible(true);
    }

    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) {

        }
    });

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