List of usage examples for android.os Bundle getInt
public int getInt(String key)
From source file:me.willowcheng.makerthings.ui.OpenHABMainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()"); // Check if we are in development mode perPreferences = getSharedPreferences("pref", this.MODE_PRIVATE); isDeveloper = false;// www . ja v a 2s .c om // Set default values, false means do it one time during the very first launch PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Set non-persistent HABDroid version preference to current version from application package try { Log.d(TAG, "App version = " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.PREFERENCE_APPVERSION, getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit(); } catch (PackageManager.NameNotFoundException e1) { if (e1 != null) Log.d(TAG, e1.getMessage()); } checkDiscoveryPermissions(); checkVoiceRecognition(); // initialize loopj async http client mAsyncHttpClient = new MyAsyncHttpClient(this); // Set the theme to one from preferences mSettings = PreferenceManager.getDefaultSharedPreferences(this); // Disable screen timeout if set in preferences if (mSettings.getBoolean(Constants.PREFERENCE_SCREENTIMEROFF, false)) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } // Fetch openHAB service type name from strings.xml openHABServiceType = getString(R.string.openhab_service_type); // Get username/password from preferences openHABUsername = mSettings.getString(Constants.PREFERENCE_USERNAME, null); openHABPassword = mSettings.getString(Constants.PREFERENCE_PASSWORD, null); mAsyncHttpClient.setBasicAuth(openHABUsername, openHABPassword, true); mAsyncHttpClient.setTimeout(30000); if (!isDeveloper) Util.initCrittercism(getApplicationContext(), "5117659f59e1bd4ba9000004"); Util.setActivityTheme(this); super.onCreate(savedInstanceState); if (!isDeveloper) ((HABDroid) getApplication()).getTracker(HABDroid.TrackerName.APP_TRACKER); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.openhab_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // ProgressBar layout params inside the toolbar have to be done programmatically // because it doesn't work through layout file :-( mProgressBar = (SwipeRefreshLayout) findViewById(R.id.toolbar_progress_bar); mProgressBar.setColorSchemeColors(getResources().getColor(R.color.theme_accent)); mProgressBar.setEnabled(false); mProgressBar.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mProgressBar.setRefreshing(false); } }); // mProgressBar.setLayoutParams(new Toolbar.LayoutParams(Gravity.RIGHT)); startProgressIndicator(); gcmRegisterBackground(); // Enable app icon in action bar work as 'home' // this.getActionBar().setHomeButtonEnabled(true); pager = (OpenHABViewPager) findViewById(R.id.pager); pager.setScrollDurationFactor(2.5); pager.setOffscreenPageLimit(1); pagerAdapter = new OpenHABFragmentPagerAdapter(getSupportFragmentManager()); pagerAdapter.setColumnsNumber(getResources().getInteger(R.integer.pager_columns)); pagerAdapter.setOpenHABUsername(openHABUsername); pagerAdapter.setOpenHABPassword(openHABPassword); pager.setAdapter(pagerAdapter); pager.setOnPageChangeListener(pagerAdapter); MemorizingTrustManager.setResponder(this); // pager.setPageMargin(1); // pager.setPageMarginDrawable(android.R.color.darker_gray); // Check if we have openHAB page url in saved instance state? if (savedInstanceState != null) { openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl"); sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl"); mStartedWithNetworkConnectivityInfo = savedInstanceState .getParcelable("startedWithNetworkConnectivityInfo"); mOpenHABVersion = savedInstanceState.getInt("openHABVersion"); mSitemapList = savedInstanceState.getParcelableArrayList("sitemapList"); } mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name) { public void onDrawerClosed(View view) { Log.d(TAG, "onDrawerClosed"); getSupportActionBar().setTitle(pagerAdapter.getPageTitle(pager.getCurrentItem())); } public void onDrawerOpened(View drawerView) { Log.d(TAG, "onDrawerOpened"); getSupportActionBar().setTitle("Makerthings"); loadSitemapList(OpenHABMainActivity.this.openHABBaseUrl); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); if (mSitemapList == null) mSitemapList = new ArrayList<OpenHABSitemap>(); mDrawerItemList = new ArrayList<OpenHABDrawerItem>(); mDrawerAdapter = new OpenHABDrawerAdapter(this, R.layout.openhabdrawer_sitemap_item, mDrawerItemList); mDrawerAdapter.setOpenHABUsername(openHABUsername); mDrawerAdapter.setOpenHABPassword(openHABPassword); mDrawerList.setAdapter(mDrawerAdapter); mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int item, long l) { Log.d(TAG, "Drawer selected item " + String.valueOf(item)); if (mDrawerItemList != null && mDrawerItemList.get(item) .getItemType() == OpenHABDrawerItem.DrawerItemType.SITEMAP_ITEM) { Log.d(TAG, "This is sitemap " + mDrawerItemList.get(item).getSiteMap().getLink()); mDrawerLayout.closeDrawers(); openSitemap(mDrawerItemList.get(item).getSiteMap().getHomepageLink()); } else { Log.d(TAG, "This is not sitemap"); if (mDrawerItemList.get(item).getTag() == DRAWER_NOTIFICATIONS) { Log.d(TAG, "Notifications selected"); mDrawerLayout.closeDrawers(); OpenHABMainActivity.this.openNotifications(); } else if (mDrawerItemList.get(item).getTag() == DRAWER_BINDINGS) { Log.d(TAG, "Bindings selected"); mDrawerLayout.closeDrawers(); OpenHABMainActivity.this.openBindings(); } else if (mDrawerItemList.get(item).getTag() == DRAWER_INBOX) { Log.d(TAG, "Inbox selected"); mDrawerLayout.closeDrawers(); OpenHABMainActivity.this.openDiscoveryInbox(); } } } }); loadDrawerItems(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); if (getIntent() != null) { Log.d(TAG, "Intent != null"); if (getIntent().getAction() != null) { Log.d(TAG, "Intent action = " + getIntent().getAction()); if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) { Log.d(TAG, "This is NFC action"); if (getIntent().getDataString() != null) { Log.d(TAG, "NFC data = " + getIntent().getDataString()); mNfcData = getIntent().getDataString(); } } else if (getIntent().getAction().equals("org.openhab.notification.selected")) { onNotificationSelected(getIntent()); } else if (getIntent().getAction().equals("android.intent.action.VIEW")) { Log.d(TAG, "This is URL Action"); String URL = getIntent().getDataString(); mNfcData = URL; } } } /** * If we are 4.4 we can use fullscreen mode and Daydream features */ supportsKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; boolean fullScreen = mSettings.getBoolean("default_openhab_fullscreen", false); if (supportsKitKat && fullScreen) { registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STARTED")); registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STOPPED")); checkFullscreen(); } }
From source file:com.owncloud.android.authentication.AuthenticatorActivity.java
/** * {@inheritDoc}//from ww w.ja va 2 s.c om * * IMPORTANT ENTRY POINT 1: activity is shown to the user */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.account_setup); mAuthMessage = (TextView) findViewById(R.id.auth_message); mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput); mHostUrlInput.setText(getString(R.string.server_url)); // valid although // R.string.server_url // is an empty // string mUsernameInput = (EditText) findViewById(R.id.account_username); mPasswordInput = (EditText) findViewById(R.id.account_password); mPasswordInput2 = (EditText) findViewById(R.id.account_password2); mOAuthAuthEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_1); mOAuthTokenEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_2); mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check); mOkButton = findViewById(R.id.buttonOK); mAuthStatusLayout = (TextView) findViewById(R.id.auth_status_text); // / set Host Url Input Enabled mHostUrlInputEnabled = getResources().getBoolean(R.bool.show_server_url_input); locationSpinner = (Spinner) findViewById(R.id.spinner1); // / complete label for 'register account' button Button b = (Button) findViewById(R.id.account_register); if (b != null) { b.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name))); } // / initialization mAccountMgr = AccountManager.get(this); mNewCapturedUriFromOAuth2Redirection = null; mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE); mAccount = null; mHostBaseUrl = ""; location = " ";//locationSpinner.getSelectedItem(); locationSpinner.setOnItemSelectedListener(this); boolean refreshButtonEnabled = false; // URL input configuration applied if (!mHostUrlInputEnabled) { findViewById(R.id.hostUrlFrame).setVisibility(View.GONE); mRefreshButton = findViewById(R.id.centeredRefreshButton); } else { mRefreshButton = findViewById(R.id.embeddedRefreshButton); } if (savedInstanceState == null) { mResumed = false; // / connection state and info mAuthMessageVisibility = View.GONE; mServerStatusText = mServerStatusIcon = 0; mServerIsValid = false; mServerIsChecked = false; mIsSslConn = false; mAuthStatusText = mAuthStatusIcon = 0; // / retrieve extras from intent mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT); if (mAccount != null) { String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION); Log.d("!!!!!!!!!!!!!!!!!!!!!!!!! ", mAccount.name); if (ocVersion != null) { mDiscoveredVersion = new OwnCloudVersion(ocVersion); } mHostBaseUrl = normalizeUrl( mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL)); mHostUrlInput.setText(mHostBaseUrl); String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@')); Log.d("!!!!!!!!!!!!!!!!!!!!!!!!!4234 ", userName); mUsernameInput.setText(userName); } initAuthorizationMethod(); // checks intent and setup.xml to // determine mCurrentAuthorizationMethod mJustCreated = true; if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) { checkOcServer(); } } else { mResumed = true; // / connection state and info mAuthMessageVisibility = savedInstanceState.getInt(KEY_AUTH_MESSAGE_VISIBILITY); mAuthMessageText = savedInstanceState.getString(KEY_AUTH_MESSAGE_TEXT); mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID); mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED); mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT); mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON); mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN); mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT); mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON); if (savedInstanceState.getBoolean(KEY_PASSWORD_VISIBLE, false)) { showPassword(); } // / server data String ocVersion = savedInstanceState.getString(KEY_OC_VERSION); if (ocVersion != null) { mDiscoveredVersion = new OwnCloudVersion(ocVersion); } mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT); // account data, if updating mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT); // Log.d("////////////////// ",mAccount.name); mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE); if (mAuthTokenType == null) { mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD; } // check if server check was interrupted by a configuration change if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) { checkOcServer(); } // refresh button enabled refreshButtonEnabled = savedInstanceState.getBoolean(KEY_REFRESH_BUTTON_ENABLED); } if (mAuthMessageVisibility == View.VISIBLE) { showAuthMessage(mAuthMessageText); } else { hideAuthMessage(); } adaptViewAccordingToAuthenticationMethod(); showServerStatus(); showAuthStatus(); if (mAction == ACTION_UPDATE_TOKEN) { // / lock things that should not change mHostUrlInput.setEnabled(false); mHostUrlInput.setFocusable(false); mUsernameInput.setEnabled(false); mUsernameInput.setFocusable(false); mOAuth2Check.setVisibility(View.GONE); } // if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled) // showRefreshButton(); if (mServerIsChecked && !mServerIsValid && refreshButtonEnabled) showRefreshButton(); mOkButton.setEnabled(mServerIsValid); // state not automatically // recovered in configuration // changes if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) || !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) { mOAuth2Check.setVisibility(View.GONE); } mPasswordInput.setText(""); // clean password to avoid social hacking // (disadvantage: password in removed if the // device is turned aside) // / bind view elements to listeners and other friends mHostUrlInput.setOnFocusChangeListener(this); mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT); mHostUrlInput.setOnEditorActionListener(this); mHostUrlInput.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) { mOkButton.setEnabled(false); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!mResumed) { mAuthStatusIcon = 0; mAuthStatusText = 0; showAuthStatus(); } mResumed = false; } }); mPasswordInput.setOnFocusChangeListener(this); mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE); mPasswordInput.setOnEditorActionListener(this); mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() { @Override public boolean onDrawableTouch(final MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { AuthenticatorActivity.this.onViewPasswordClick(); } return true; } }); findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) && mHostUrlInput.hasFocus()) { checkOcServer(); } } return false; } }); }
From source file:android.app.Activity.java
/** * Called when the activity is starting. This is where most initialization * should go: calling {@link #setContentView(int)} to inflate the * activity's UI, using {@link #findViewById} to programmatically interact * with widgets in the UI, calling//from w w w . j a v a2 s. c o m * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve * cursors for data being displayed, etc. * * <p>You can call {@link #finish} from within this function, in * which case onDestroy() will be immediately called without any of the rest * of the activity lifecycle ({@link #onStart}, {@link #onResume}, * {@link #onPause}, etc) executing. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @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 {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> * * @see #onStart * @see #onSaveInstanceState * @see #onRestoreInstanceState * @see #onPostCreate */ protected void onCreate(Bundle savedInstanceState) { if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState); if (mLastNonConfigurationInstances != null) { mAllLoaderManagers = mLastNonConfigurationInstances.loaders; } if (mActivityInfo.parentActivityName != null) { if (mActionBar == null) { mEnableDefaultActionBarUp = true; } else { mActionBar.setDefaultDisplayHomeAsUpEnabled(true); } } if (isAvailable()) { /* if this device can use the platform */ Log.w("MIGRATOR", "This is " + getLocalClassName()); Intent intent = getIntent(); Bundle tmpBundle = intent.getBundleExtra("MIGRATED"); ArrayList<Bundle> stacked = intent.getParcelableArrayListExtra("MIGRATED STACK"); if (tmpBundle != null) { /* true if this Activity was migrated */ if (stacked != null) { /* true if this Activity called next Activity */ Intent next = new Intent(); Bundle nextBundle = stacked.get(0); next.setClassName(nextBundle.getString("MIGRATED PNAME"), nextBundle.getString("MIGRATED CNAME")); next.putExtra("MIGRATED", nextBundle); stacked.remove(0); int code = tmpBundle.getInt("MIGRATED REQUEST CODE"); Bundle option = nextBundle.getBundle("MIGRATED REQUEST OPTIONS"); if (!stacked.isEmpty()) { /* store for next Activity */ next.putParcelableArrayListExtra("MIGRATED STACK", stacked); } Log.w("MIGRATOR", "Start ForResult: code=" + code); mReceiverStackFlag = true; mStackedNextIntent = next; mStackedNextCode = code; mStackedNextOption = option; } else { /* for debug */ Log.w("MIGRATOR", "stack is null"); } savedInstanceState = null; mMigFlag = true; migratedState = tmpBundle; Intent tmpIntent = tmpBundle.getParcelable("MIGRATED_INTENT"); if (tmpIntent != null) { tmpIntent.setAction(Intent.ACTION_MIGRATE); setIntent(tmpIntent); } /* File handling */ ArrayList<String> tmpNames = tmpBundle.getStringArrayList("TARGET_FILE_NAME"); if (tmpNames != null) { FileWorker fw = new FileWorker(tmpNames.toArray(new String[tmpNames.size()]), FileWorker.WRITE_MODE); fw.start(); tmpNames = null; } Log.w("MIGRATOR", "successed migaration: " + tmpBundle.toString()); tmpBundle = null; } else { /* for debug */ Log.w("MIGRATOR", "tmpBundle is null"); } } if (savedInstanceState != null) { Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG); mFragments.restoreAllState(p, mLastNonConfigurationInstances != null ? mLastNonConfigurationInstances.fragments : null); } mFragments.dispatchCreate(); getApplication().dispatchActivityCreated(this, savedInstanceState); mCalled = true; }
From source file:com.guardtrax.ui.screens.HomeScreen.java
public void onCreate(Bundle savedInstanceState) { ctx = this.getApplicationContext(); super.onCreate(savedInstanceState); //restore saved instances if necessary if (savedInstanceState != null) { Toast.makeText(HomeScreen.this, savedInstanceState.getString("message"), Toast.LENGTH_LONG).show(); GTConstants.darfileName = savedInstanceState.getString("darfileName"); GTConstants.tarfileName = savedInstanceState.getString("tarfileName"); GTConstants.trpfilename = savedInstanceState.getString("trpfilename"); GTConstants.srpfileName = savedInstanceState.getString("srpfileName"); Utility.setcurrentState(savedInstanceState.getString("currentState")); Utility.setsessionStart(savedInstanceState.getString("getsessionStart")); selectedCode = savedInstanceState.getString("selectedCode"); lunchTime = savedInstanceState.getString("lunchTime"); breakTime = savedInstanceState.getString("breakTime"); signaturefileName = savedInstanceState.getString("signaturefileName"); GTConstants.tourName = savedInstanceState.getString("tourName"); tourTime = savedInstanceState.getString("tourTime"); tourEnd = savedInstanceState.getLong("tourEnd"); lunchoutLocation = savedInstanceState.getInt("lunchoutLocation"); breakoutLocation = savedInstanceState.getInt("breakoutLocation"); touritemNumber = savedInstanceState.getInt("touritemNumber"); chekUpdate = savedInstanceState.getBoolean("chekUpdate"); GTConstants.sendData = savedInstanceState.getBoolean("send_data"); GTConstants.isTour = savedInstanceState.getBoolean("isTour"); GTConstants.isGeoFence = savedInstanceState.getBoolean("isGeoFence"); } else {/*from w ww. j a va2 s .co m*/ //set the current state Utility.setcurrentState(GTConstants.offShift); //set the default startup code to start shift selectedCode = "start_shift"; } /* //Determine screen size if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) { Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show(); } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) { Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show(); } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) { Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show(); } //initialize receiver to monitor for screen on / off /* IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); BroadcastReceiver mReceiver = new ScreenReceiver(); registerReceiver(mReceiver, filter); */ setContentView(R.layout.homescreen); //Create object to call the Database class myDatabase = new GuardTraxDB(this); preferenceDB = new PreferenceDB(this); ftpdatabase = new ftpDataBase(this); gtDB = new GTParams(this); aDB = new accountsDB(this); trafficDB = new trafficDataBase(this); tourDB = new tourDataBase(this); //check for updates if (chekUpdate) { //reset the preference value chekUpdate = false; //check for application updates checkUpdate(); } //initialize the message timer //initializeOnModeTimerEvent(); //get the version number and set it in constants String version_num = ""; PackageManager manager = this.getPackageManager(); try { PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); version_num = info.versionName.toString(); } catch (NameNotFoundException e) { version_num = "0.00.00"; } GTConstants.version = version_num; //final TextView version = (TextView) findViewById(R.id.textVersion); //version.setText(version_num); //set up the animation animation.setDuration(500); // duration - half a second animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in buttonClick.setDuration(50); // duration - half a second buttonClick.setInterpolator(new LinearInterpolator()); // do not alter animation rate buttonClick.setRepeatCount(1); // Repeat animation once buttonClick.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in textWarning = (TextView) findViewById(R.id.txtWarning); textWarning.setWidth(500); textWarning.setGravity(Gravity.CENTER); //allow the text to be clicked if necessary textWarning.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (GTConstants.isTour && GTConstants.tourName.length() > 1) displaytourInfo(); } }); //goto scan page button btn_scan_screen = (Button) findViewById(R.id.btn_goto_scan); btn_scan_screen.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { btn_scan_screen.startAnimation(buttonClick); //Utility.showScan(HomeScreen.this); scan_click(false); } }); //goto report page button btn_report_screen = (Button) findViewById(R.id.btn_goto_report); btn_report_screen.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { btn_report_screen.startAnimation(buttonClick); report_click(); } }); //goto dial page button btn_dial_screen = (Button) findViewById(R.id.btn_goto_dial); btn_dial_screen.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { btn_dial_screen.startAnimation(buttonClick); dial_click(); } }); //microphone button btn_mic = (Button) findViewById(R.id.btn_mic); btn_mic.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { btn_mic.startAnimation(buttonClick); voice_click(); } }); //camera button btn_camera = (Button) findViewById(R.id.btn_camera); btn_camera.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { btn_camera.startAnimation(buttonClick); camera_click(); } }); //video button btn_video = (Button) findViewById(R.id.btn_video); btn_video.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { btn_video.startAnimation(buttonClick); video_click(); } }); // Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable. btn_send = (Button) findViewById(R.id.btn_Send); btn_send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //prevent multiple fast clicking if (SystemClock.elapsedRealtime() - mLastClickTime < 2000) return; mLastClickTime = SystemClock.elapsedRealtime(); incidentcodeSent = true; btn_send.startAnimation(buttonClick); //if start shift has not been sent then the device is in do not send data mode. Warn the user if (Utility.getcurrentState().equals(GTConstants.offShift) && !selectedCode.equals("start_shift")) { show_alert_title = "Error"; show_alert_message = "You must start your shift!"; showAlert(show_alert_title, show_alert_message, true); //set spinner back to start shift spinner.setSelection(0); } else { if (Utility.deviceRegistered()) { show_alert_title = "Success"; show_alert_message = "Action success"; } else { show_alert_title = "Warning"; show_alert_message = "You are NOT registered!"; showAlert(show_alert_title, show_alert_message, true); } if (selectedCode.equals("start_shift")) { //if shift already started if (Utility.getcurrentState().equals(GTConstants.onShift)) { show_alert_title = "Warning"; show_alert_message = "You must end shift!"; showAlert(show_alert_title, show_alert_message, true); //set spinner back to all clear spinner.setSelection(2); } else { ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER, (ViewGroup) findViewById(R.id.toast_layout_root)); pdialog = ProgressDialog.show(HomeScreen.this, "Please wait", "Starting shift ...", true); //set the current state Utility.setcurrentState(GTConstants.onShift); setuserBanner(); //wait for start shift actions to complete (or timeout occurs) before dismissing wait dialog new CountDownTimer(5000, 1000) { @Override public void onTick(long millisUntilFinished) { if (start_shift_wait) pdialog.dismiss(); } @Override public void onFinish() { if (!(pdialog == null)) pdialog.dismiss(); } }.start(); //create dar file try { //create the dar file name GTConstants.darfileName = GTConstants.LICENSE_ID.substring(7) + "_" + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".dar"; //write the version to the dar file Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName, "Version;" + GTConstants.version + "\r\n", false); //write the start shift event to the dar file Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName, "Start shift;" + GTConstants.currentBatteryPercent + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); //create the tar file name if module installed if (GTConstants.isTimeandAttendance) { GTConstants.tarfileName = GTConstants.LICENSE_ID.substring(7) + "_" + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".tar"; //write the start shift event to the tar file Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName, "Name;" + GTConstants.report_name + "\r\n" + "Start shift;" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", false); } } catch (Exception e) { Toast.makeText(HomeScreen.this, "error = " + e, Toast.LENGTH_LONG).show(); } GTConstants.sendData = true; //if not time and attendance then send start shift event now, otherwise wait till after location scan send_event("11"); //set the session start time SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yy HH:mm:ss"); Utility.setsessionStart(sdf.format(new Date())); //reset the server connection flag Utility.resetisConnecting(); //start the GPS location service MainService.openLocationListener(); //set spinner back to all clear spinner.setSelection(2); setwarningText(""); if (GTConstants.isTimeandAttendance) { show_taa_scan(true, false); } } } else if (selectedCode.equals("end_shift")) { if (!Utility.getcurrentState().equals(GTConstants.onShift) && GTConstants.isTimeandAttendance) { show_alert_title = "Error"; show_alert_message = "You must end your Lunch / Break!"; showAlert(show_alert_title, show_alert_message, true); //set spinner back to start shift spinner.setSelection(2); } else { btn_send.setEnabled(false); if (GTConstants.isTimeandAttendance) { show_taa_scan(false, true); } else endshiftCode(); } } else { if (Utility.isselectionValid(HomeScreen.this, selectedCode)) { //if time and attendance then write to file if (selectedCode.equalsIgnoreCase(GTConstants.lunchin) || selectedCode.equalsIgnoreCase(GTConstants.lunchout) || selectedCode.equalsIgnoreCase(GTConstants.startbreak) || selectedCode.equalsIgnoreCase(GTConstants.endbreak)) { if (GTConstants.isTimeandAttendance) Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName, spinner.getSelectedItem().toString() + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)) { Utility.setcurrentState(GTConstants.onLunch); Utility.setlunchStart(true); setuserBanner(); } if (selectedCode.equalsIgnoreCase(GTConstants.startbreak)) { Utility.setcurrentState(GTConstants.onBreak); Utility.setbreakStart(true); setuserBanner(); } if (selectedCode.equalsIgnoreCase(GTConstants.lunchout)) { Utility.setcurrentState(GTConstants.onShift); lunchTime = Utility.gettimeDiff(Utility.getlunchStart(), Utility.getLocalDateTime()); setuserBanner(); } if (selectedCode.equalsIgnoreCase(GTConstants.endbreak)) { Utility.setcurrentState(GTConstants.onShift); breakTime = Utility.gettimeDiff(Utility.getbreakStart(), Utility.getLocalDateTime()); setuserBanner(); } } ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER, (ViewGroup) findViewById(R.id.toast_layout_root)); //save the event description as may be needed for incident report incidentDescription = spinner.getSelectedItem().toString(); //write to dar Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.darfileName, "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); //write to srp if (GTConstants.srpfileName.length() > 1) Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.srpfileName, "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true); //send the data send_event(selectedCode); //ask if user wants to create an incident report. If the last character is a space, that indicates not to ask for report if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ') && !trafficIncident) showYesNoAlert("Report", "Create an Incident Report?", incidentreportScreen); if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ') && trafficIncident) showYesNoAlert("Report", "Create a Traffic Violation?", incidentreportScreen); //if last two characters are spaces then ask to write a note if (incidentDescription.charAt(incidentDescription.length() - 1) == ' ' && incidentDescription.charAt(incidentDescription.length() - 2) == ' ') showYesNoAlert("Report", "Create a Note?", createNote); } //set spinner back to required state if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)) spinner.setSelection(lunchoutLocation); else if (selectedCode.equalsIgnoreCase(GTConstants.startbreak)) spinner.setSelection(breakoutLocation); else spinner.setSelection(2); } } } }); //Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle). spinner = (Spinner) findViewById(R.id.spinner_list); //method initialize the spinner action initializeSpinnerControl(); if (GTConstants.service_intent == null) { //Condition to check whether the Database exist and if so load data into constants try { if (preferenceDB.checkDataBase()) { preferenceDB.open(); Cursor cursor = preferenceDB.getRecordByRowID("1"); preferenceDB.close(); if (cursor == null) loadPreferenceDataBase(); else { saveInConstants(cursor); cursor.close(); } syncDB(); syncFTP(); syncftpUpload(); } else { preferenceDB.open(); preferenceDB.close(); //Toast.makeText(HomeScreen.this, "Path = " + preferenceDB.get_path(), Toast.LENGTH_LONG).show(); //Toast.makeText(HomeScreen.this, "No database found", Toast.LENGTH_LONG).show(); loadPreferenceDataBase(); syncDB(); syncFTP(); syncftpUpload(); } } catch (Exception e) { preferenceDB.createDataBase(); loadPreferenceDataBase(); Toast.makeText(HomeScreen.this, "Creating database", Toast.LENGTH_LONG).show(); } //setup the auxiliary databases if (!aDB.checkDataBase()) { aDB.open(); aDB.close(); } if (!ftpdatabase.checkDataBase()) { ftpdatabase.open(); ftpdatabase.close(); } if (!gtDB.checkDataBase()) { gtDB.open(); gtDB.close(); } if (!trafficDB.checkDataBase()) { trafficDB.open(); trafficDB.close(); } if (!tourDB.checkDataBase()) { tourDB.open(); tourDB.close(); } //get the parameters from the parameter database loadGTParams(); //this code starts the main service running which contains all the event timers if (Utility.deviceRegistered()) { //this is the application started event - sent once when application starts up if (savedInstanceState == null) send_event("PU"); initService(); } } //if device not registered than go straight to scan screen if (!Utility.deviceRegistered()) { newRegistration = true; //send_data = true; scan_click(false); } //setup the user banner setuserBanner(); //set the warning text setwarningText(""); }
From source file:de.sourcestream.movieDB.MainActivity.java
/** * First configure the Universal Image Downloader, * then we set the main layout to be activity_main.xml * and we add the slide menu items.//from ww w . ja v a 2 s . co m * * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitle = mDrawerTitle = getTitle(); // load slide menu items navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.list_slidermenu); ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.drawer_header, null, false); ImageView drawerBackButton = (ImageView) header.findViewById(R.id.drawerBackButton); drawerBackButton.setOnClickListener(onDrawerBackButton); mDrawerList.addHeaderView(header); mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); // setting the nav drawer list adapter mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, R.id.title, navMenuTitles)); toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); toolbar.bringToFront(); } mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ toolbar, R.string.app_name, // nav drawer open - description for accessibility R.string.app_name // nav drawer close - description for accessibility ) { public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); // calling onPrepareOptionsMenu() to show search view invalidateOptionsMenu(); syncState(); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); // calling onPrepareOptionsMenu() to hide search view invalidateOptionsMenu(); syncState(); } // updates the title, toolbar transparency and search view public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, slideOffset); if (slideOffset > .55 && !isDrawerOpen) { // opening drawer // mDrawerTitle is app title getSupportActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); isDrawerOpen = true; } else if (slideOffset < .45 && isDrawerOpen) { // closing drawer // mTitle is title of the current view, can be movies, tv shows or movie title getSupportActionBar().setTitle(mTitle); invalidateOptionsMenu(); isDrawerOpen = false; } } }; mDrawerLayout.setDrawerListener(mDrawerToggle); // Get the action bar title to set padding TextView titleTextView = null; try { Field f = toolbar.getClass().getDeclaredField("mTitleTextView"); f.setAccessible(true); titleTextView = (TextView) f.get(toolbar); } catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { } if (titleTextView != null) { float scale = getResources().getDisplayMetrics().density; titleTextView.setPadding((int) scale * 15, 0, 0, 0); } phone = getResources().getBoolean(R.bool.portrait_only); searchDB = new SearchDB(getApplicationContext()); if (savedInstanceState == null) { // Check orientation and lock to portrait if we are on phone if (phone) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } // on first time display view for first nav item displayView(1); // Use hockey module to check for updates checkForUpdates(); // Universal Loader options and configuration. DisplayImageOptions options = new DisplayImageOptions.Builder() // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888. .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false) .showImageOnLoading(R.drawable.placeholder_default) .showImageForEmptyUri(R.drawable.placeholder_default) .showImageOnFail(R.drawable.placeholder_default).cacheOnDisk(true).build(); Context context = this; File cacheDir = StorageUtils.getCacheDirectory(context); // Create global configuration and initialize ImageLoader with this config ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) .diskCache(new UnlimitedDiscCache(cacheDir)) // default .defaultDisplayImageOptions(options).build(); ImageLoader.getInstance().init(config); // Check cache size long size = 0; File[] filesCache = cacheDir.listFiles(); for (File file : filesCache) { size += file.length(); } if (cacheDir.getUsableSpace() < MinFreeSpace || size > CacheSize) { ImageLoader.getInstance().getDiskCache().clear(); searchDB.cleanSuggestionRecords(); } } else { oldPos = savedInstanceState.getInt("oldPos"); currentMovViewPagerPos = savedInstanceState.getInt("currentMovViewPagerPos"); currentTVViewPagerPos = savedInstanceState.getInt("currentTVViewPagerPos"); restoreMovieDetailsState = savedInstanceState.getBoolean("restoreMovieDetailsState"); restoreMovieDetailsAdapterState = savedInstanceState.getBoolean("restoreMovieDetailsAdapterState"); movieDetailsBundle = savedInstanceState.getParcelableArrayList("movieDetailsBundle"); castDetailsBundle = savedInstanceState.getParcelableArrayList("castDetailsBundle"); tvDetailsBundle = savedInstanceState.getParcelableArrayList("tvDetailsBundle"); currOrientation = savedInstanceState.getInt("currOrientation"); lastVisitedSimMovie = savedInstanceState.getInt("lastVisitedSimMovie"); lastVisitedSimTV = savedInstanceState.getInt("lastVisitedSimTV"); lastVisitedMovieInCredits = savedInstanceState.getInt("lastVisitedMovieInCredits"); saveInMovieDetailsSimFragment = savedInstanceState.getBoolean("saveInMovieDetailsSimFragment"); FragmentManager fm = getFragmentManager(); // prevent the following bug: go to gallery preview -> swap orientation -> // go to movies list -> swap orientation -> action bar bugged // so if we are not on gallery preview we show toolbar if (fm.getBackStackEntryCount() == 0 || !fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("galleryList")) { new Handler().post(new Runnable() { @Override public void run() { if (getSupportActionBar() != null && !getSupportActionBar().isShowing()) getSupportActionBar().show(); } }); } } // Get reference for the imageLoader imageLoader = ImageLoader.getInstance(); // Options used for the backdrop image in movie and tv details and gallery optionsWithFade = new DisplayImageOptions.Builder() // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888. .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500)) .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false).showImageOnLoading(R.color.black) .showImageForEmptyUri(R.color.black).showImageOnFail(R.color.black).cacheOnDisk(true).build(); optionsWithoutFade = new DisplayImageOptions.Builder() // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888. .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false) .showImageOnLoading(R.color.black).showImageForEmptyUri(R.color.black) .showImageOnFail(R.color.black).cacheOnDisk(true).build(); // Options used for the backdrop image in movie and tv details and gallery backdropOptionsWithFade = new DisplayImageOptions.Builder() // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888. .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500)) .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false) .showImageOnLoading(R.drawable.placeholder_backdrop) .showImageForEmptyUri(R.drawable.placeholder_backdrop) .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build(); backdropOptionsWithoutFade = new DisplayImageOptions.Builder() // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888. .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false) .showImageOnLoading(R.drawable.placeholder_backdrop) .showImageForEmptyUri(R.drawable.placeholder_backdrop) .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build(); trailerListView = new TrailerList(); galleryListView = new GalleryList(); if (currOrientation != getResources().getConfiguration().orientation) orientationChanged = true; currOrientation = getResources().getConfiguration().orientation; iconConstantSpecialCase = 0; if (phone) { iconMarginConstant = 0; iconMarginLandscape = 0; DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int width = displayMetrics.widthPixels; int height = displayMetrics.heightPixels; if (width <= 480 && height <= 800) iconConstantSpecialCase = -70; // used in MovieDetails, CastDetails, TVDetails onMoreIconClick // to check whether the animation should be in up or down direction threeIcons = 128; threeIconsToolbar = 72; twoIcons = 183; twoIconsToolbar = 127; oneIcon = 238; oneIconToolbar = 182; } else { if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { iconMarginConstant = 232; iconMarginLandscape = 300; threeIcons = 361; threeIconsToolbar = 295; twoIcons = 416; twoIconsToolbar = 351; oneIcon = 469; oneIconToolbar = 407; } else { iconMarginConstant = 82; iconMarginLandscape = 0; threeIcons = 209; threeIconsToolbar = 146; twoIcons = 264; twoIconsToolbar = 200; oneIcon = 319; oneIconToolbar = 256; } } dateFormat = android.text.format.DateFormat.getDateFormat(this); }
From source file:cw.kop.autobackground.sources.SourceInfoFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle arguments = getArguments(); sourcePosition = (Integer) arguments.get("position"); int colorFilterInt = AppSettings.getColorFilterInt(appContext); View view = inflater.inflate(R.layout.source_info_fragment, container, false); headerView = inflater.inflate(R.layout.source_info_header, null, false); settingsContainer = (RelativeLayout) headerView.findViewById(R.id.source_settings_container); sourceImage = (ImageView) headerView.findViewById(R.id.source_image); sourceTitle = (EditText) headerView.findViewById(R.id.source_title); sourcePrefix = (EditText) headerView.findViewById(R.id.source_data_prefix); sourceData = (EditText) headerView.findViewById(R.id.source_data); sourceSuffix = (EditText) headerView.findViewById(R.id.source_data_suffix); sourceNum = (EditText) headerView.findViewById(R.id.source_num); ViewGroup.LayoutParams params = sourceImage.getLayoutParams(); params.height = (int) ((container.getWidth() - 2f * getResources().getDimensionPixelSize(R.dimen.side_margin)) / 16f * 9); sourceImage.setLayoutParams(params); cancelButton = (Button) view.findViewById(R.id.cancel_button); saveButton = (Button) view.findViewById(R.id.save_button); sourcePrefix.setTextColor(colorFilterInt); sourceSuffix.setTextColor(colorFilterInt); cancelButton.setTextColor(colorFilterInt); saveButton.setTextColor(colorFilterInt); // Adjust alpha to get faded hint color from regular text color int hintColor = Color.argb(0x88, Color.red(colorFilterInt), Color.green(colorFilterInt), Color.blue(colorFilterInt)); sourceTitle.setHintTextColor(hintColor); sourceData.setHintTextColor(hintColor); sourceNum.setHintTextColor(hintColor); sourceData.setOnClickListener(new View.OnClickListener() { @Override/*www.j a va 2 s . c o m*/ public void onClick(View v) { switch (type) { case AppSettings.FOLDER: selectSource(getPositionOfType(AppSettings.FOLDER)); break; case AppSettings.GOOGLE_ALBUM: selectSource(getPositionOfType(AppSettings.GOOGLE_ALBUM)); break; } Log.i(TAG, "Data launched folder fragment"); } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveSource(); } }); sourceSpinnerText = (TextView) headerView.findViewById(R.id.source_spinner_text); sourceSpinner = (Spinner) headerView.findViewById(R.id.source_spinner); timePref = (CustomSwitchPreference) findPreference("source_time"); timePref.setChecked(arguments.getBoolean("use_time")); timePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (!(Boolean) newValue) { return true; } DialogFactory.TimeDialogListener startTimeListener = new DialogFactory.TimeDialogListener() { @Override public void onTimeSet(TimePicker view, int hour, int minute) { startHour = hour; startMinute = minute; DialogFactory.TimeDialogListener endTimeListener = new DialogFactory.TimeDialogListener() { @Override public void onTimeSet(TimePicker view, int hour, int minute) { endHour = hour; endMinute = minute; timePref.setSummary(String.format("Time active: %02d:%02d - %02d:%02d", startHour, startMinute, endHour, endMinute)); } }; DialogFactory.showTimeDialog(appContext, "End time?", endTimeListener, startHour, startMinute); } }; DialogFactory.showTimeDialog(appContext, "Start time?", startTimeListener, startHour, startMinute); return true; } }); if (savedInstanceState != null) { if (sourcePosition == -1) { sourceSpinner .setSelection(getPositionOfType(savedInstanceState.getString("type", AppSettings.WEBSITE))); } } if (sourcePosition == -1) { sourceImage.setVisibility(View.GONE); sourceSpinnerText.setVisibility(View.VISIBLE); sourceSpinner.setVisibility(View.VISIBLE); SourceSpinnerAdapter adapter = new SourceSpinnerAdapter(appContext, R.layout.spinner_row, Arrays.asList(getResources().getStringArray(R.array.source_menu))); sourceSpinner.setAdapter(adapter); sourceSpinner.setSelection(0); sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectSource(position); Log.i(TAG, "Spinner launched folder fragment"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); type = AppSettings.WEBSITE; hint = "URL"; prefix = ""; suffix = ""; startHour = 0; startMinute = 0; endHour = 0; endMinute = 0; } else { sourceImage.setVisibility(View.VISIBLE); sourceSpinnerText.setVisibility(View.GONE); sourceSpinner.setVisibility(View.GONE); type = arguments.getString("type"); folderData = arguments.getString("data"); String data = folderData; hint = AppSettings.getSourceDataHint(type); prefix = AppSettings.getSourceDataPrefix(type); suffix = ""; switch (type) { case AppSettings.GOOGLE_ALBUM: sourceTitle.setFocusable(false); sourceData.setFocusable(false); sourceNum.setFocusable(false); case AppSettings.FOLDER: data = Arrays.toString(folderData.split(AppSettings.DATA_SPLITTER)); break; case AppSettings.TUMBLR_BLOG: suffix = ".tumblr.com"; break; } sourceTitle.setText(arguments.getString("title")); sourceNum.setText("" + arguments.getInt("num")); sourceData.setText(data); if (imageDrawable != null) { sourceImage.setImageDrawable(imageDrawable); } boolean showPreview = arguments.getBoolean("preview"); if (showPreview) { sourceImage.setVisibility(View.VISIBLE); } ((CustomSwitchPreference) findPreference("source_show_preview")).setChecked(showPreview); String[] timeArray = arguments.getString("time").split(":|[ -]+"); try { startHour = Integer.parseInt(timeArray[0]); startMinute = Integer.parseInt(timeArray[1]); endHour = Integer.parseInt(timeArray[2]); endMinute = Integer.parseInt(timeArray[3]); timePref.setSummary(String.format("Time active: %02d:%02d - %02d:%02d", startHour, startMinute, endHour, endMinute)); } catch (NumberFormatException e) { e.printStackTrace(); startHour = 0; startMinute = 0; endHour = 0; endMinute = 0; } } setDataWrappers(); sourceUse = (Switch) headerView.findViewById(R.id.source_use_switch); sourceUse.setChecked(arguments.getBoolean("use")); if (AppSettings.getTheme().equals(AppSettings.APP_LIGHT_THEME)) { view.setBackgroundColor(getResources().getColor(R.color.LIGHT_THEME_BACKGROUND)); } else { view.setBackgroundColor(getResources().getColor(R.color.DARK_THEME_BACKGROUND)); } ListView listView = (ListView) view.findViewById(android.R.id.list); listView.addHeaderView(headerView); if (savedInstanceState != null) { sourceTitle.setText(savedInstanceState.getString("title", "")); sourceData.setText(savedInstanceState.getString("data", "")); sourceNum.setText(savedInstanceState.getString("num", "")); } return view; }
From source file:net.homelinux.penecoptero.android.citybikes.app.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);/*from w w w .java2 s . c o 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) { 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:net.homelinux.penecoptero.android.citybikes.donation.app.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);/*from ww w .j a va 2 s .c o 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!"); }