List of usage examples for android.widget Spinner setSelection
@Override public void setSelection(int position)
From source file:com.mantz_it.rfanalyzer.MainActivity.java
public void showRecordingDialog() { if (!running || scheduler == null || demodulator == null || source == null) { Toast.makeText(MainActivity.this, "Analyzer must be running to start recording", Toast.LENGTH_LONG) .show();//from www . j a v a 2 s . c o m return; } // Check for the WRITE_EXTERNAL_STORAGE permission: if (ContextCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { "android.permission.WRITE_EXTERNAL_STORAGE" }, PERMISSION_REQUEST_RECORDING_WRITE_FILES); return; // wait for the permission response (handled in onRequestPermissionResult()) } final String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath(); final int[] supportedSampleRates = source.getSupportedSampleRates(); final double maxFreqMHz = source.getMaxFrequency() / 1000000f; // max frequency of the source in MHz final int sourceType = Integer.valueOf(preferences.getString(getString(R.string.pref_sourceType), "1")); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US); // Get references to the GUI components: final ScrollView view = (ScrollView) this.getLayoutInflater().inflate(R.layout.start_recording, null); final EditText et_filename = (EditText) view.findViewById(R.id.et_recording_filename); final EditText et_frequency = (EditText) view.findViewById(R.id.et_recording_frequency); final Spinner sp_sampleRate = (Spinner) view.findViewById(R.id.sp_recording_sampleRate); final TextView tv_fixedSampleRateHint = (TextView) view.findViewById(R.id.tv_recording_fixedSampleRateHint); final CheckBox cb_stopAfter = (CheckBox) view.findViewById(R.id.cb_recording_stopAfter); final EditText et_stopAfter = (EditText) view.findViewById(R.id.et_recording_stopAfter); final Spinner sp_stopAfter = (Spinner) view.findViewById(R.id.sp_recording_stopAfter); // Setup the sample rate spinner: final ArrayAdapter<Integer> sampleRateAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_list_item_1); for (int sampR : supportedSampleRates) sampleRateAdapter.add(sampR); sampleRateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp_sampleRate.setAdapter(sampleRateAdapter); // Add listener to the frequency textfield, the sample rate spinner and the checkbox: et_frequency.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (et_frequency.getText().length() == 0) return; double freq = Double.valueOf(et_frequency.getText().toString()); if (freq < maxFreqMHz) freq = freq * 1000000; et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_" + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq"); } }); sp_sampleRate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (et_frequency.getText().length() == 0) return; double freq = Double.valueOf(et_frequency.getText().toString()); if (freq < maxFreqMHz) freq = freq * 1000000; et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_" + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); cb_stopAfter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { et_stopAfter.setEnabled(isChecked); sp_stopAfter.setEnabled(isChecked); } }); // Set default frequency, sample rate and stop after values: et_frequency.setText("" + analyzerSurface.getVirtualFrequency()); int sampleRateIndex = 0; int lastSampleRate = preferences.getInt(getString(R.string.pref_recordingSampleRate), 1000000); for (; sampleRateIndex < supportedSampleRates.length; sampleRateIndex++) { if (supportedSampleRates[sampleRateIndex] >= lastSampleRate) break; } if (sampleRateIndex >= supportedSampleRates.length) sampleRateIndex = supportedSampleRates.length - 1; sp_sampleRate.setSelection(sampleRateIndex); cb_stopAfter.toggle(); // just to trigger the listener at least once! cb_stopAfter.setChecked(preferences.getBoolean(getString(R.string.pref_recordingStopAfterEnabled), false)); et_stopAfter.setText("" + preferences.getInt(getString(R.string.pref_recordingStopAfterValue), 10)); sp_stopAfter.setSelection(preferences.getInt(getString(R.string.pref_recordingStopAfterUnit), 0)); // disable sample rate selection if demodulation is running: if (demodulationMode != Demodulator.DEMODULATION_OFF) { sampleRateAdapter.add(source.getSampleRate()); // add the current sample rate in case it's not already in the list sp_sampleRate.setSelection(sampleRateAdapter.getPosition(source.getSampleRate())); // select it sp_sampleRate.setEnabled(false); // disable the spinner tv_fixedSampleRateHint.setVisibility(View.VISIBLE); } // Show dialog: new AlertDialog.Builder(this).setTitle("Start recording").setView(view) .setPositiveButton("Record", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String filename = et_filename.getText().toString(); final int stopAfterUnit = sp_stopAfter.getSelectedItemPosition(); final int stopAfterValue = Integer.valueOf(et_stopAfter.getText().toString()); //todo check filename // Set the frequency in the source: if (et_frequency.getText().length() == 0) return; double freq = Double.valueOf(et_frequency.getText().toString()); if (freq < maxFreqMHz) freq = freq * 1000000; if (freq <= source.getMaxFrequency() && freq >= source.getMinFrequency()) source.setFrequency((long) freq); else { Toast.makeText(MainActivity.this, "Frequency is invalid!", Toast.LENGTH_LONG).show(); return; } // Set the sample rate (only if demodulator is off): if (demodulationMode == Demodulator.DEMODULATION_OFF) source.setSampleRate((Integer) sp_sampleRate.getSelectedItem()); // Open file and start recording: recordingFile = new File(externalDir + "/" + RECORDING_DIR + "/" + filename); recordingFile.getParentFile().mkdir(); // Create directory if it does not yet exist try { scheduler.startRecording(new BufferedOutputStream(new FileOutputStream(recordingFile))); } catch (FileNotFoundException e) { Log.e(LOGTAG, "showRecordingDialog: File not found: " + recordingFile.getAbsolutePath()); } // safe preferences: SharedPreferences.Editor edit = preferences.edit(); edit.putInt(getString(R.string.pref_recordingSampleRate), (Integer) sp_sampleRate.getSelectedItem()); edit.putBoolean(getString(R.string.pref_recordingStopAfterEnabled), cb_stopAfter.isChecked()); edit.putInt(getString(R.string.pref_recordingStopAfterValue), stopAfterValue); edit.putInt(getString(R.string.pref_recordingStopAfterUnit), stopAfterUnit); edit.apply(); analyzerSurface.setRecordingEnabled(true); updateActionBar(); // if stopAfter was selected, start thread to supervise the recording: if (cb_stopAfter.isChecked()) { Thread supervisorThread = new Thread() { @Override public void run() { Log.i(LOGTAG, "recording_superviser: Supervisor Thread started. (Thread: " + this.getName() + ")"); try { long startTime = System.currentTimeMillis(); boolean stop = false; // We check once per half a second if the stop criteria is met: Thread.sleep(500); while (recordingFile != null && !stop) { switch (stopAfterUnit) { // see arrays.xml - recording_stopAfterUnit case 0: /* MB */ if (recordingFile.length() / 1000000 >= stopAfterValue) stop = true; break; case 1: /* GB */ if (recordingFile.length() / 1000000000 >= stopAfterValue) stop = true; break; case 2: /* sec */ if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000) stop = true; break; case 3: /* min */ if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000 * 60) stop = true; break; } } // stop recording: stopRecording(); } catch (InterruptedException e) { Log.e(LOGTAG, "recording_superviser: Interrupted!"); } catch (NullPointerException e) { Log.e(LOGTAG, "recording_superviser: Recording file is null!"); } Log.i(LOGTAG, "recording_superviser: Supervisor Thread stopped. (Thread: " + this.getName() + ")"); } }; supervisorThread.start(); } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).show().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); }
From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java
private void setFilelistCurrDir(Spinner tv, String base, String dir) { // tv.setText(dir_text); for (int i = 0; i < tv.getCount(); i++) { String list = (String) tv.getItemAtPosition(i); if (list.equals(base)) { tv.setSelection(i); break; }/*from ww w . j a v a 2 s . c o m*/ } ; }
From source file:com.digi.android.wva.fragments.EndpointOptionsDialog.java
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (mConfig == null && savedInstanceState == null) { Log.e(TAG, "mConfig is null, not showing dialog!"); return null; }// w ww . j a va 2 s .c o m LayoutInflater inf = getActivity().getLayoutInflater(); View v = inf.inflate(R.layout.dialog_endpoint_options, null); // Suppresses warnings, and ensures the layout exists. assert v != null; final TextView subIntervalTV = (TextView) v.findViewById(R.id.textView_interval); final TextView alarmInfoTV = (TextView) v.findViewById(R.id.alarm_info); final CheckBox subscribedCB = (CheckBox) v.findViewById(R.id.subscribedCheckbox); final CheckBox alarmCB = (CheckBox) v.findViewById(R.id.alarmCheckbox); final EditText subInterval = (EditText) v.findViewById(R.id.subscriptionInterval); final EditText alarmThreshold = (EditText) v.findViewById(R.id.alarmThreshold); final Spinner typeSpinner = (Spinner) v.findViewById(R.id.alarmTypeSpinner); final LinearLayout makeAlarmSection = (LinearLayout) v.findViewById(R.id.section_make_alarm); final LinearLayout showAlarmSection = (LinearLayout) v.findViewById(R.id.section_show_alarm); final CheckBox dcSendCB = (CheckBox) v.findViewById(R.id.dcPushCheckbox); String alarmInfo = "No alarm yet"; boolean isSubscribed = false; String endpointName = "UNKNOWN"; int sinterval = 10; boolean alarmCreated = false; double threshold = 0; int alarmtypeidx = 0; boolean isSendingToDC = false; if (savedInstanceState != null && savedInstanceState.containsKey("config")) { mConfig = savedInstanceState.getParcelable("config"); } if (mConfig != null) { endpointName = mConfig.getEndpoint(); alarmInfo = mConfig.getAlarmSummary(); if (mConfig.getSubscriptionConfig() != null) { isSubscribed = mConfig.getSubscriptionConfig().isSubscribed(); sinterval = mConfig.getSubscriptionConfig().getInterval(); isSendingToDC = mConfig.shouldBePushedToDeviceCloud(); } else { // Not subscribed; default interval value from preferences. String i = PreferenceManager.getDefaultSharedPreferences(getActivity()) .getString("pref_default_interval", "0"); try { sinterval = Integer.parseInt(i); } catch (NumberFormatException e) { Log.d(TAG, "Failed to parse default interval from preferences: " + i); sinterval = 0; } } if (mConfig.getAlarmConfig() != null) { alarmCreated = mConfig.getAlarmConfig().isCreated(); threshold = mConfig.getAlarmConfig().getThreshold(); String typestr = AlarmType.makeString(mConfig.getAlarmConfig().getType()); for (int i = 0; i < alarmTypes.length; i++) { if (alarmTypes[i].toLowerCase(Locale.US).equals(typestr)) alarmtypeidx = i; } } } // Set up event listeners on EditText and CheckBox items subscribedCB.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { subInterval.setEnabled(isChecked); subIntervalTV.setEnabled(isChecked); } }); alarmCB.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { typeSpinner.setEnabled(isChecked); alarmThreshold.setEnabled(false); // If type spinner is set to Change, we want threshold disabled again if (isChecked) { alarmThreshold.setEnabled(!shouldDisableAlarmThreshold(typeSpinner.getSelectedItemPosition())); } } }); typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { if (alarmCB.isChecked() && shouldDisableAlarmThreshold(position)) alarmThreshold.setEnabled(false); else if (!alarmCB.isChecked()) alarmThreshold.setEnabled(false); else alarmThreshold.setEnabled(true); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); subIntervalTV.setEnabled(false); subInterval.setEnabled(false); alarmThreshold.setEnabled(false); typeSpinner.setEnabled(false); alarmInfoTV.setText(alarmInfo); // Click checkboxes, show data depending on if subscription or alarm // has been added already if (isSubscribed) subscribedCB.performClick(); if (alarmCreated) { showAlarmSection.setVisibility(View.VISIBLE); makeAlarmSection.setVisibility(View.GONE); alarmCB.setText("Remove alarm"); } else { makeAlarmSection.setVisibility(View.VISIBLE); showAlarmSection.setVisibility(View.GONE); alarmCB.setText("Create alarm"); } dcSendCB.setChecked(isSendingToDC); subInterval.setText(Integer.toString(sinterval)); alarmThreshold.setText(Double.toString(threshold)); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.alarm_types, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); typeSpinner.setAdapter(adapter); typeSpinner.setSelection(alarmtypeidx); DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { // Fetch the EndpointsAdapter's configuration for this endpoint. // (We might have gotten mConfig from the saved instance bundle) EndpointConfiguration cfg = EndpointsAdapter.getInstance() .findEndpointConfiguration(mConfig.getEndpoint()); // Set whether this endpoint's data should be pushed to Device Cloud if (cfg != null) { cfg.setPushToDeviceCloud(dcSendCB.isChecked()); } // Handle (un)subscribing if (isUnsubscribing(subscribedCB.isChecked())) { unsubscribe(mConfig.getEndpoint()); } else if (subscribedCB.isChecked()) { if (handleMakingSubscription(subInterval)) { // Subscription was successful... most likely. Log.d(TAG, "Probably subscribed to endpoint."); } else { // Invalid interval. Toast.makeText(getActivity(), getString(R.string.configure_endpoints_toast_invalid_sub_interval), Toast.LENGTH_SHORT).show(); } } // Handle adding/removing alarm as necessary if (isRemovingAlarm(alarmCB.isChecked())) { removeAlarm(mConfig.getEndpoint(), mConfig.getAlarmConfig().getType()); } else if (alarmCB.isChecked()) { Editable thresholdText = alarmThreshold.getText(); String thresholdString; if (thresholdText == null) thresholdString = ""; else thresholdString = thresholdText.toString(); double threshold; try { threshold = Double.parseDouble(thresholdString); } catch (NumberFormatException e) { Toast.makeText(getActivity(), getString(R.string.configure_endpoints_invalid_threshold), Toast.LENGTH_SHORT).show(); return; } int alarmidx = typeSpinner.getSelectedItemPosition(); if (alarmidx == -1) { // But... how? Log.wtf(TAG, "alarm type index -1 ?"); return; } String type = alarmTypes[alarmidx]; AlarmType atype = AlarmType.fromString(type); createAlarm(mConfig.getEndpoint(), atype, threshold); } dialog.dismiss(); } }; return new AlertDialog.Builder(getActivity()).setView(v).setTitle("Endpoint: " + endpointName) .setPositiveButton("Save", clickListener) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Cancel means just dismiss the dialog. dialog.dismiss(); } }).create(); }
From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java
private void setRemoteDirBtnListener() { final CustomSpinnerAdapter spAdapter = new CustomSpinnerAdapter(this, R.layout.custom_simple_spinner_item); // spAdapter.setTextColor(Color.BLACK); spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); remoteFileListDirSpinner.setPrompt("??"); remoteFileListDirSpinner.setAdapter(spAdapter); // mIgnoreRemoteSelection=true; if (remoteBase.equals("")) spAdapter.add("--- Not selected ---"); int a_no = 0; for (int i = 0; i < profileAdapter.getCount(); i++) if (profileAdapter.getItem(i).getType().equals("R") && profileAdapter.getItem(i).getActive().equals("A")) { spAdapter.add(profileAdapter.getItem(i).getName()); String surl = buildRemoteBase(profileAdapter.getItem(i)); if (surl.equals(remoteBase)) remoteFileListDirSpinner.setSelection(a_no); a_no++;/*from ww w . ja va 2 s. c om*/ } remoteFileListDirSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (mIgnoreSpinnerSelection) { // Log.v("","ignored"); return; } // mIgnoreRemoteSelection=false; Spinner spinner = (Spinner) parent; if (((String) spinner.getSelectedItem()).startsWith("---")) { return; } String sel_item = (String) spinner.getSelectedItem(); if (spAdapter.getItem(0).startsWith("---")) { spAdapter.remove(spAdapter.getItem(0)); spinner.setSelection(position - 1); } ProfileListItem pli = null; for (int i = 0; i < profileAdapter.getCount(); i++) { if (profileAdapter.getItem(i).getName().equals(sel_item)) { pli = profileAdapter.getItem(i); } } String turl = buildRemoteBase(pli); if (turl.equals(remoteBase)) tabHost.setCurrentTabByTag(SMBEXPLORER_TAB_REMOTE); else { tabHost.getTabWidget().getChildTabViewAt(2).setEnabled(true); tabHost.setCurrentTabByTag(SMBEXPLORER_TAB_REMOTE); setJcifsProperties(pli.getUser(), pli.getPass()); remoteBase = turl; remoteDir = ""; clearDirHist(remoteDirHist); // putDirHist(remoteBase, remoteDir, remoteDirHist); if (remoteCurrFLI != null) { remoteCurrFLI.pos_fv = remoteFileListView.getFirstVisiblePosition(); if (remoteFileListView.getChildAt(0) != null) remoteCurrFLI.pos_top = remoteFileListView.getChildAt(0).getTop(); } loadRemoteFilelist(remoteBase, remoteDir); remoteFileListView.setSelection(0); for (int j = 0; j < remoteFileListView.getChildCount(); j++) remoteFileListView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); remoteFileListUpBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { processRemoteUpButton(); } }); remoteFileListPathBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (remoteFileListCache.size() > 0) showFileListCache(remoteFileListCache, remoteFileListAdapter, remoteFileListView, remoteFileListDirSpinner); } }); remoteFileListTopBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { processRemoteTopButton(); } }); remoteFileListPasteBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String to_dir = ""; if (remoteDir.equals("")) to_dir = remoteBase; else to_dir = remoteBase + "/" + remoteDir; pasteItem(remoteFileListAdapter, to_dir, remoteBase); } }); remoteFileListReloadBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { reloadFilelistView(); setEmptyFolderView(); } }); remoteFileListCreateBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (currentTabName.equals(SMBEXPLORER_TAB_LOCAL)) { if (localDir.length() == 0) createItem(localFileListAdapter, "C", localBase); else createItem(localFileListAdapter, "C", localBase + "/" + localDir); } else if (currentTabName.equals(SMBEXPLORER_TAB_REMOTE)) { if (remoteDir.length() == 0) createItem(remoteFileListAdapter, "C", remoteBase); else createItem(remoteFileListAdapter, "C", remoteBase + "/" + remoteDir); } } }); }
From source file:org.tvbrowser.tvbrowser.TvBrowser.java
private void updateTvData() { if (!TvDataUpdateService.IS_RUNNING) { Cursor test = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_CHANNELS, null, TvBrowserContentProvider.CHANNEL_KEY_SELECTION + "=1", null, null); if (test.getCount() > 0) { AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this); RelativeLayout dataDownload = (RelativeLayout) getLayoutInflater() .inflate(R.layout.dialog_data_update_selection, getParentViewGroup(), false); final Spinner days = (Spinner) dataDownload .findViewById(R.id.dialog_data_update_selection_download_days); final CheckBox pictures = (CheckBox) dataDownload .findViewById(R.id.dialog_data_update_selection_download_picture); final Spinner autoUpdate = (Spinner) dataDownload .findViewById(R.id.dialog_data_update_preferences_auto_update_selection_type); final Spinner frequency = (Spinner) dataDownload .findViewById(R.id.dialog_data_update_preferences_auto_update_selection_frequency); final CheckBox onlyWiFi = (CheckBox) dataDownload .findViewById(R.id.dialog_data_update_preferences_auto_update_selection_type_connection); final TextView timeLabel = (TextView) dataDownload .findViewById(R.id.dialog_data_update_preferences_auto_update_selection_time_label); final TextView time = (TextView) dataDownload .findViewById(R.id.dialog_data_update_preferences_auto_update_selection_time); time.setTextColor(onlyWiFi.getTextColors()); String currentDownloadDays = PrefUtils.getStringValue(R.string.DAYS_TO_DOWNLOAD, R.string.days_to_download_default); final String[] possibleDownloadDays = getResources().getStringArray(R.array.download_days); for (int i = 0; i < possibleDownloadDays.length; i++) { if (currentDownloadDays.equals(possibleDownloadDays[i])) { days.setSelection(i); break; }//w w w .j a v a2 s .c om } pictures.setChecked( PrefUtils.getBooleanValue(R.string.LOAD_PICTURE_DATA, R.bool.load_picture_data_default)); String currentAutoUpdateValue = PrefUtils.getStringValue(R.string.PREF_AUTO_UPDATE_TYPE, R.string.pref_auto_update_type_default); String currentAutoUpdateFrequency = PrefUtils.getStringValue(R.string.PREF_AUTO_UPDATE_FREQUENCY, R.string.pref_auto_update_frequency_default); if (currentAutoUpdateValue.equals("0")) { frequency.setEnabled(false); onlyWiFi.setEnabled(false); timeLabel.setEnabled(false); time.setEnabled(false); frequency.setVisibility(View.GONE); onlyWiFi.setVisibility(View.GONE); timeLabel.setVisibility(View.GONE); time.setVisibility(View.GONE); } else if (currentAutoUpdateValue.equals("1")) { autoUpdate.setSelection(1); timeLabel.setEnabled(false); time.setEnabled(false); timeLabel.setVisibility(View.GONE); time.setVisibility(View.GONE); } else if (currentAutoUpdateValue.equals("2")) { autoUpdate.setSelection(2); } final String[] autoFrequencyPossibleValues = getResources() .getStringArray(R.array.pref_auto_update_frequency_values); for (int i = 0; i < autoFrequencyPossibleValues.length; i++) { if (autoFrequencyPossibleValues[i].equals(currentAutoUpdateFrequency)) { frequency.setSelection(i); break; } } onlyWiFi.setChecked(PrefUtils.getBooleanValue(R.string.PREF_AUTO_UPDATE_ONLY_WIFI, R.bool.pref_auto_update_only_wifi_default)); final AtomicInteger currentAutoUpdateTime = new AtomicInteger(PrefUtils.getIntValue( R.string.PREF_AUTO_UPDATE_START_TIME, R.integer.pref_auto_update_start_time_default)); Calendar now = Calendar.getInstance(); now.set(Calendar.HOUR_OF_DAY, currentAutoUpdateTime.get() / 60); now.set(Calendar.MINUTE, currentAutoUpdateTime.get() % 60); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); time.setText(DateFormat.getTimeFormat(TvBrowser.this).format(now.getTime())); autoUpdate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { frequency.setEnabled(position != 0); onlyWiFi.setEnabled(position != 0); if (position != 0) { frequency.setVisibility(View.VISIBLE); onlyWiFi.setVisibility(View.VISIBLE); } else { frequency.setVisibility(View.GONE); onlyWiFi.setVisibility(View.GONE); } timeLabel.setEnabled(position == 2); time.setEnabled(position == 2); if (position == 2) { timeLabel.setVisibility(View.VISIBLE); time.setVisibility(View.VISIBLE); } else { timeLabel.setVisibility(View.GONE); time.setVisibility(View.GONE); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder b2 = new AlertDialog.Builder(TvBrowser.this); LinearLayout timeSelection = (LinearLayout) getLayoutInflater().inflate( R.layout.dialog_data_update_selection_auto_update_time, getParentViewGroup(), false); final TimePicker timePick = (TimePicker) timeSelection .findViewById(R.id.dialog_data_update_selection_auto_update_selection_time); timePick.setIs24HourView(DateFormat.is24HourFormat(TvBrowser.this)); timePick.setCurrentHour(currentAutoUpdateTime.get() / 60); timePick.setCurrentMinute(currentAutoUpdateTime.get() % 60); b2.setView(timeSelection); b2.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { currentAutoUpdateTime .set(timePick.getCurrentHour() * 60 + timePick.getCurrentMinute()); Calendar now = Calendar.getInstance(); now.set(Calendar.HOUR_OF_DAY, currentAutoUpdateTime.get() / 60); now.set(Calendar.MINUTE, currentAutoUpdateTime.get() % 60); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); time.setText(DateFormat.getTimeFormat(TvBrowser.this).format(now.getTime())); } }); b2.setNegativeButton(android.R.string.cancel, null); b2.show(); } }; time.setOnClickListener(onClickListener); timeLabel.setOnClickListener(onClickListener); builder.setTitle(R.string.download_data); builder.setView(dataDownload); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String value = possibleDownloadDays[days.getSelectedItemPosition()]; Editor settings = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit(); if (PrefUtils.getStringValueAsInt(R.string.PREF_AUTO_UPDATE_RANGE, R.string.pref_auto_update_range_default) < Integer.parseInt(value)) { settings.putString(getString(R.string.PREF_AUTO_UPDATE_RANGE), value); } settings.putString(getString(R.string.DAYS_TO_DOWNLOAD), value); settings.putBoolean(getString(R.string.LOAD_PICTURE_DATA), pictures.isChecked()); settings.putString(getString(R.string.PREF_AUTO_UPDATE_TYPE), String.valueOf(autoUpdate.getSelectedItemPosition())); if (autoUpdate.getSelectedItemPosition() == 1 || autoUpdate.getSelectedItemPosition() == 2) { settings.putString(getString(R.string.PREF_AUTO_UPDATE_FREQUENCY), autoFrequencyPossibleValues[frequency.getSelectedItemPosition()]); settings.putBoolean(getString(R.string.PREF_AUTO_UPDATE_ONLY_WIFI), onlyWiFi.isChecked()); if (autoUpdate.getSelectedItemPosition() == 2) { settings.putInt(getString(R.string.PREF_AUTO_UPDATE_START_TIME), currentAutoUpdateTime.get()); } } settings.commit(); IOUtils.handleDataUpdatePreferences(TvBrowser.this); Intent startDownload = new Intent(TvBrowser.this, TvDataUpdateService.class); startDownload.putExtra(TvDataUpdateService.TYPE, TvDataUpdateService.TV_DATA_TYPE); startDownload.putExtra(getResources().getString(R.string.DAYS_TO_DOWNLOAD), Integer.parseInt(value)); startService(startDownload); updateProgressIcon(true); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); } else { Cursor test2 = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_CHANNELS, null, null, null, null); boolean loadAgain = test2.getCount() < 1; test2.close(); selectChannels(loadAgain); } test.close(); } }
From source file:g7.bluesky.launcher3.Launcher.java
@Override protected void onCreate(Bundle savedInstanceState) { activity = this; if (DEBUG_STRICT_MODE) { StrictMode.setThreadPolicy(//from ww w . j a v a 2 s . co m new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or .detectAll() for all detectable problems .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); } if (mLauncherCallbacks != null) { mLauncherCallbacks.preOnCreate(); } super.onCreate(savedInstanceState); LauncherAppState.setApplicationContext(getApplicationContext()); LauncherAppState app = LauncherAppState.getInstance(); LauncherAppState.getLauncherProvider().setLauncherProviderChangeListener(this); // Lazy-initialize the dynamic grid DeviceProfile grid = app.initDynamicGrid(this); // the LauncherApplication should call this, but in case of Instrumentation it might not be present yet mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE); // Set defaultSharedPref defaultSharedPref = PreferenceManager.getDefaultSharedPreferences(this); mIsSafeModeEnabled = getPackageManager().isSafeMode(); mModel = app.setLauncher(this); mIconCache = app.getIconCache(); mIconCache.flushInvalidIcons(grid); mDragController = new DragController(this); mInflater = getLayoutInflater(); mStats = new Stats(this); mAppWidgetManager = AppWidgetManagerCompat.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here, // this also ensures that any synchronous binding below doesn't re-trigger another // LauncherModel load. mPaused = false; if (PROFILE_STARTUP) { android.os.Debug.startMethodTracing(Environment.getExternalStorageDirectory() + "/launcher"); } checkForLocaleChange(); setContentView(R.layout.launcher); setupViews(); grid.layout(this); registerContentObservers(); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); if (PROFILE_STARTUP) { android.os.Debug.stopMethodTracing(); } if (!mRestoring) { if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) { // If the user leaves launcher, then we should just load items asynchronously when // they return. mModel.startLoader(true, PagedView.INVALID_RESTORE_PAGE); } else { // We only load the page synchronously if the user rotates (or triggers a // configuration change) while launcher is in the foreground mModel.startLoader(true, mWorkspace.getRestorePage()); } } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(mCloseSystemDialogsReceiver, filter); // On large interfaces, we want the screen to auto-rotate based on the current orientation unlockScreenOrientation(true); if (mLauncherCallbacks != null) { mLauncherCallbacks.onCreate(savedInstanceState); if (mLauncherCallbacks.hasLauncherOverlay()) { ViewStub stub = (ViewStub) findViewById(R.id.launcher_overlay_stub); mLauncherOverlayContainer = (InsettableFrameLayout) stub.inflate(); mLauncherOverlay = mLauncherCallbacks.setLauncherOverlayView(mLauncherOverlayContainer, mLauncherOverlayCallbacks); mWorkspace.setLauncherOverlay(mLauncherOverlay); } } if (shouldShowIntroScreen()) { showIntroScreen(); } else { showFirstRunActivity(); showFirstRunClings(); } //create extramenu //llExtraMenu = (LinearLayout) findViewById(R.id.ll_extra_menu); //llExtraMenu.addView(new ExtraMenu(this, null)); flLauncher = (LauncherRootView) findViewById(R.id.launcher); mExtraMenu = new ExtraMenu(this, null); flLauncher.addView(mExtraMenu); if (!defaultSharedPref.getBoolean(SettingConstants.EXTRA_MENU_PREF_KEY, false)) { mExtraMenu.setVisibility(View.GONE); } editTextFilterApps.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { String searchString = editTextFilterApps.getText().toString(); if (listApps != null && listApps.size() > 0) { if (searchString.trim().length() > 0) { ArrayList<AppInfo> searchList = new ArrayList<>(); for (AppInfo appInfo : listApps) { String appTitle = StringUtil .convertVNString(appInfo.getTitle().toString().toLowerCase().trim()); searchString = StringUtil.convertVNString(searchString.toLowerCase().trim()); if (appTitle.contains(searchString)) { searchList.add(appInfo); } } mAppsCustomizeContent.setApps(searchList); } else { mAppsCustomizeContent.setApps((ArrayList<AppInfo>) listApps); } } } }); // Spinner element Spinner spinner = (Spinner) findViewById(R.id.spinner); // Spinner click listener spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Clear spinner text ((TextView) view).setText(null); SharedPreferences.Editor editor = defaultSharedPref.edit(); editor.putInt(SettingConstants.SORT_PREF_KEY, position); editor.apply(); // Value from preference int prefVal = defaultSharedPref.getInt(SettingConstants.SORT_PREF_KEY, SettingConstants.SORT_A_Z); LauncherUtil.sortListApps(defaultSharedPref, listApps, prefVal); mAppsCustomizeContent.invalidatePageData(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); // Creating adapter for spinner ArrayAdapter<CharSequence> dataAdapter = ArrayAdapter.createFromResource(this, R.array.sort_options, android.R.layout.simple_spinner_item); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice); // attaching data adapter to spinner spinner.setAdapter(dataAdapter); // Set default value final int prefSortOptionVal = defaultSharedPref.getInt(SettingConstants.SORT_PREF_KEY, SettingConstants.SORT_A_Z); spinner.setSelection(prefSortOptionVal); // Listen on pref change prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key.equalsIgnoreCase(SettingConstants.EXTRA_MENU_PREF_KEY)) { if (!defaultSharedPref.getBoolean(SettingConstants.EXTRA_MENU_PREF_KEY, false)) { mExtraMenu.setVisibility(View.GONE); } else { mExtraMenu.setVisibility(View.VISIBLE); } } else if (key.equalsIgnoreCase(SettingConstants.ICON_THEME_PREF_KEY)) { mModel.forceReload(); loadIconPack(); } } }; defaultSharedPref.registerOnSharedPreferenceChangeListener(prefChangeListener); }
From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceActionProfile.java
private void restoreViewContents(final SavedViewContents sv) { final EditText dlg_prof_name_et = (EditText) mDialog.findViewById(R.id.edit_profile_action_profile_et_name); final CheckBox cb_active = (CheckBox) mDialog.findViewById(R.id.edit_profile_action_enabled); final CheckBox cb_enable_env_parms = (CheckBox) mDialog .findViewById(R.id.edit_profile_action_enable_env_parms); final TextView tv_sound_filename = (TextView) mDialog .findViewById(R.id.edit_profile_action_exec_sound_file_name); final CheckBox cb_music_vol = (CheckBox) mDialog .findViewById(R.id.edit_profile_action_profile_sound_use_volume); final SeekBar sb_music_vol = (SeekBar) mDialog.findViewById(R.id.edit_profile_action_profile_sound_volume); final CheckBox cb_ringtone_vol = (CheckBox) mDialog .findViewById(R.id.edit_profile_action_profile_ringtone_use_volume); final SeekBar sb_ringtone_vol = (SeekBar) mDialog .findViewById(R.id.edit_profile_action_profile_ringtone_volume); final Spinner spinnerActionType = (Spinner) mDialog.findViewById(R.id.edit_profile_action_action_type); final Spinner spinnerActivityName = (Spinner) mDialog .findViewById(R.id.edit_profile_action_exec_activity_name); final Spinner spinnerActivityDataType = (Spinner) mDialog .findViewById(R.id.edit_profile_action_exec_activity_data_type); final Spinner spinnerRingtoneType = (Spinner) mDialog .findViewById(R.id.edit_profile_action_exec_ringtone_type); final Spinner spinnerRingtoneName = (Spinner) mDialog .findViewById(R.id.edit_profile_action_exec_ringtone_name); final Spinner spinnerCompareType = (Spinner) mDialog.findViewById(R.id.edit_profile_action_compare_type); final EditText et_comp_value1 = (EditText) mDialog.findViewById(R.id.edit_profile_action_compare_value1); final EditText et_comp_value2 = (EditText) mDialog.findViewById(R.id.edit_profile_action_compare_value2); final ListView lv_comp_data = (ListView) mDialog .findViewById(R.id.edit_profile_action_compare_value_listview); final Spinner spinnerCompareResult = (Spinner) mDialog .findViewById(R.id.edit_profile_action_compare_result); final Spinner spinnerCompareTarget = (Spinner) mDialog .findViewById(R.id.edit_profile_action_compare_target); final Spinner spinnerMessageType = (Spinner) mDialog.findViewById(R.id.edit_profile_action_message_type); final EditText et_msg_text = (EditText) mDialog.findViewById(R.id.edit_profile_action_message_message); final CheckBox cb_vib_used = (CheckBox) mDialog.findViewById(R.id.edit_profile_action_message_vibration); final CheckBox cb_led_used = (CheckBox) mDialog.findViewById(R.id.edit_profile_action_message_led); final RadioButton rb_msg_blue = (RadioButton) mDialog .findViewById(R.id.edit_profile_action_message_led_blue); final RadioButton rb_msg_red = (RadioButton) mDialog.findViewById(R.id.edit_profile_action_message_led_red); final RadioButton rb_msg_green = (RadioButton) mDialog .findViewById(R.id.edit_profile_action_message_led_green); final Spinner spinnerTimeType = (Spinner) mDialog.findViewById(R.id.edit_profile_action_time_type); final Spinner spinnerTimeTarget = (Spinner) mDialog.findViewById(R.id.edit_profile_action_time_target); final Spinner spinnerTaskType = (Spinner) mDialog.findViewById(R.id.edit_profile_action_task_type); final Spinner spinnerTaskTarget = (Spinner) mDialog.findViewById(R.id.edit_profile_action_task_target); final Spinner spinnerWaitTarget = (Spinner) mDialog.findViewById(R.id.edit_profile_action_wait_target); final Spinner spinnerWaitTimeoutType = (Spinner) mDialog .findViewById(R.id.edit_profile_action_wait_timeout); final Spinner spinnerWaitTimeoutValue = (Spinner) mDialog .findViewById(R.id.edit_profile_action_wait_timeout_value); final Spinner spinnerWaitTimeoutUnits = (Spinner) mDialog .findViewById(R.id.edit_profile_action_wait_timeout_units); final EditText et_bsh_script = (EditText) mDialog .findViewById(R.id.edit_profile_action_dlg_bsh_script_text); final Spinner spinnerBshMethod = (Spinner) mDialog .findViewById(R.id.edit_profile_action_dlg_bsh_add_method); final Spinner spinnerCatMethod = (Spinner) mDialog .findViewById(R.id.edit_profile_action_dlg_bsh_cat_method); final EditText uri_data = (EditText) mDialog.findViewById(R.id.edit_profile_action_exec_activity_uri_data); final ListView lv_aed = (ListView) mDialog .findViewById(R.id.edit_profile_action_exec_activity_extra_data_listview); dlg_prof_name_et.setText(sv.dlg_prof_name_et); dlg_prof_name_et.setSelection(sv.dlg_prof_name_et_spos, sv.dlg_prof_name_et_epos); cb_active.setChecked(sv.cb_active);/* w w w . ja va 2s . com*/ tv_sound_filename.setText(sv.tv_sound_filename); cb_music_vol.setChecked(sv.cb_music_vol); sb_music_vol.setProgress(sv.sb_music_vol); cb_ringtone_vol.setChecked(sv.cb_ringtone_vol); sb_ringtone_vol.setProgress(sv.sb_ringtone_vol); et_comp_value1.setText(sv.et_comp_value1); et_comp_value2.setText(sv.et_comp_value2); lv_comp_data.setSelectionFromTop(sv.lv_comp_data[0], sv.lv_comp_data[1]); et_msg_text.setText(sv.et_msg_text); cb_vib_used.setChecked(sv.cb_vib_used); cb_led_used.setChecked(sv.cb_led_used); if (sv.rb_msg_blue) rb_msg_blue.setChecked(sv.rb_msg_blue); if (sv.rb_msg_red) rb_msg_red.setChecked(sv.rb_msg_red); if (sv.rb_msg_green) rb_msg_green.setChecked(sv.rb_msg_green); et_bsh_script.setText(sv.et_bsh_script); uri_data.setText(sv.uri_data); lv_aed.setSelectionFromTop(sv.lv_aed[0], sv.lv_aed[1]); cb_enable_env_parms.setChecked(sv.cb_enable_env_parms); for (int i = 0; i < mGlblParms.activityExtraDataEditListAdapter.getCount(); i++) mGlblParms.activityExtraDataEditListAdapter.remove(0); for (int i = 0; i < sv.aed_adapter_list.size(); i++) mGlblParms.activityExtraDataEditListAdapter.add(sv.aed_adapter_list.get(i)); mGlblParms.activityExtraDataEditListAdapter.notifyDataSetChanged(); for (int i = 0; i < mGlblParms.actionCompareDataAdapter.getCount(); i++) mGlblParms.actionCompareDataAdapter.remove(0); for (int i = 0; i < sv.data_array_adapter_list.size(); i++) mGlblParms.actionCompareDataAdapter.add(sv.data_array_adapter_list.get(i)); mGlblParms.actionCompareDataAdapter.notifyDataSetChanged(); spinnerActionType.setSelection(sv.spinnerActionType); spinnerActivityName.setSelection(sv.spinnerActivityName); spinnerActivityDataType.setSelection(sv.spinnerActivityDataType); spinnerRingtoneType.setSelection(sv.spinnerRingtoneType); spinnerRingtoneName.setSelection(sv.spinnerRingtoneName); spinnerCompareType.setSelection(sv.spinnerCompareType); spinnerCompareResult.setSelection(sv.spinnerCompareResult); spinnerCompareTarget.setSelection(sv.spinnerCompareTarget); spinnerMessageType.setSelection(sv.spinnerMessageType); spinnerTimeType.setSelection(sv.spinnerTimeType); spinnerTimeTarget.setSelection(sv.spinnerTimeTarget); spinnerTaskType.setSelection(sv.spinnerTaskType); spinnerTaskTarget.setSelection(sv.spinnerTaskTarget); spinnerWaitTarget.setSelection(sv.spinnerWaitTarget); spinnerWaitTimeoutType.setSelection(sv.spinnerWaitTimeoutType); spinnerWaitTimeoutValue.setSelection(sv.spinnerWaitTimeoutValue); spinnerWaitTimeoutUnits.setSelection(sv.spinnerWaitTimeoutUnits); spinnerBshMethod.setSelection(sv.spinnerBshMethod); spinnerCatMethod.setSelection(sv.spinnerCatMethod); // Handler hndl1=new Handler(); // hndl1.postDelayed(new Runnable(){ // @Override // public void run() { // // Handler hndl2=new Handler(); // hndl2.postDelayed(new Runnable(){ // @Override // public void run() { // } // },50); // } // },50); }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
public void DoSettings() { // get settings.xml view LayoutInflater li = LayoutInflater.from(context); settingsView = li.inflate(R.layout.settings, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set settings.xml to alertdialog builder alertDialogBuilder.setView(settingsView); // get user input for service code final EditText userInput = (EditText) settingsView.findViewById(R.id.editTextDialogUserInput); // set dialog message alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override// www.j a va2s . co m public void onClick(DialogInterface dialog, int id) { SharedPreferences prefs = context.getSharedPreferences("Share", Context.MODE_PRIVATE); prefs.edit().clear(); SharedPreferences.Editor es = prefs.edit(); String[] mTestArray; if (userInput.getText().toString().equals("NoAccess")) { // prefs URL EditText et1 = (EditText) settingsView.findViewById(R.id.setting_url); appURL = et1.getText().toString(); es.putString("com.ezac.gliderlogs.url", appURL).apply(); } // prefs PRE EditText et2 = (EditText) settingsView.findViewById(R.id.setting_pre); appPRE = et2.getText().toString().replace(" ", ""); es.putString("com.ezac.gliderlogs.pre", appPRE).apply(); if (userInput.getText().toString().equals("NoAccess")) { // prefs SCN EditText et3 = (EditText) settingsView.findViewById(R.id.setting_scn); appSCN = et3.getText().toString(); es.putString("com.ezac.gliderlogs.scn", appSCN).apply(); // prefs KEY EditText et4 = (EditText) settingsView.findViewById(R.id.setting_key); appKEY = et4.getText().toString(); es.putString("com.ezac.gliderlogs.key", appKEY).apply(); // prefs KEY EditText et5 = (EditText) settingsView.findViewById(R.id.setting_secret); appSCT = et5.getText().toString(); es.putString("com.ezac.gliderlogs.sct", appSCT).apply(); // prefs Meteo mTestArray = getResources().getStringArray(R.array.meteo_id_arrays); Spinner et6 = (Spinner) settingsView.findViewById(R.id.setting_station); String sel6 = (String) et6.getSelectedItem(); //String sel6_id = ""; for (int i = 0; i < et6.getCount(); i++) { String s1 = (String) et6.getItemAtPosition(i); if (s1.equalsIgnoreCase(sel6)) { appMST = mTestArray[i]; } } es.putString("com.ezac.gliderlogs.mst", appMST).apply(); // prefs Metar EditText et7 = (EditText) settingsView.findViewById(R.id.setting_metar); appMTR = et7.getText().toString(); es.putString("com.ezac.gliderlogs.mst", appMST).apply(); } // prefs Flags CheckBox et9a = (CheckBox) settingsView.findViewById(R.id.setting_menu01); CheckBox et9b = (CheckBox) settingsView.findViewById(R.id.setting_menu02); CheckBox et9c = (CheckBox) settingsView.findViewById(R.id.setting_menu11); CheckBox et9d = (CheckBox) settingsView.findViewById(R.id.setting_menu12); CheckBox et9e = (CheckBox) settingsView.findViewById(R.id.setting_menu13); CheckBox et9f = (CheckBox) settingsView.findViewById(R.id.setting_menu14); CheckBox et9g = (CheckBox) settingsView.findViewById(R.id.setting_menu21); CheckBox et9h = (CheckBox) settingsView.findViewById(R.id.setting_menu22); String et9aa, et9ab; String v[]; if (userInput.getText().toString().equals("To3Myd4T")) { et9aa = et9a.isChecked() ? "true" : "false"; et9ab = et9b.isChecked() ? "true" : "false"; } else { v = appFLG.split(";"); et9aa = v[0]; et9ab = v[1]; } String et9ac = et9c.isChecked() ? "true" : "false"; String et9ad = et9d.isChecked() ? "true" : "false"; String et9ae = et9e.isChecked() ? "true" : "false"; String et9af = et9f.isChecked() ? "true" : "false"; String et9ag = et9g.isChecked() ? "true" : "false"; String et9ah = et9h.isChecked() ? "true" : "false"; appFLG = et9aa + ";" + et9ab + ";" + et9ac + ";" + et9ad + ";" + et9ae + ";" + et9af + ";" + et9ag + ";" + et9ah + ";false;false"; v = appFLG.split(";"); menu.findItem(R.id.action_ezac).setVisible(Boolean.parseBoolean(v[2])); menu.findItem(R.id.action_meteo_group).setVisible(Boolean.parseBoolean(v[3])); menu.findItem(R.id.action_ntm_nld).setVisible(Boolean.parseBoolean(v[4])); menu.findItem(R.id.action_ntm_blx).setVisible(Boolean.parseBoolean(v[4])); menu.findItem(R.id.action_ogn_flarm).setVisible(Boolean.parseBoolean(v[5])); menu.findItem(R.id.action_adsb).setVisible(Boolean.parseBoolean(v[6])); menu.findItem(R.id.action_adsb_lcl).setVisible(Boolean.parseBoolean(v[7])); es.putString("com.ezac.gliderlogs.flg", appFLG).apply(); // adjust value in menu button to value in use MenuItem MenuItem_dur = menu.findItem(R.id.action_45min); MenuItem_dur.setTitle(" " + appPRE + " Min "); if (userInput.getText().toString().equals("To3Myd4T")) { // prefs airfield heading mTestArray = getResources().getStringArray(R.array.heading_arrays); Spinner et10 = (Spinner) settingsView.findViewById(R.id.setting_heading); String sel10 = (String) et10.getSelectedItem(); //String sel10_id = ""; for (int i = 0; i < et10.getCount(); i++) { String s2 = (String) et10.getItemAtPosition(i); if (s2.equalsIgnoreCase(sel10)) { appLND = mTestArray[i]; es.putString("com.ezac.gliderlogs.lnd", appLND).apply(); } } } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog & and load it's data AlertDialog alertDialog = alertDialogBuilder.create(); EditText et1 = (EditText) settingsView.findViewById(R.id.setting_url); EditText et2 = (EditText) settingsView.findViewById(R.id.setting_pre); EditText et3 = (EditText) settingsView.findViewById(R.id.setting_scn); EditText et4 = (EditText) settingsView.findViewById(R.id.setting_key); EditText et5 = (EditText) settingsView.findViewById(R.id.setting_secret); Spinner et6 = (Spinner) settingsView.findViewById(R.id.setting_station); EditText et7 = (EditText) settingsView.findViewById(R.id.setting_metar); //EditText et8 = (EditText) settingsView.findViewById(R.id.setting_ntp); CheckBox et9a = (CheckBox) settingsView.findViewById(R.id.setting_menu01); CheckBox et9b = (CheckBox) settingsView.findViewById(R.id.setting_menu02); CheckBox et9c = (CheckBox) settingsView.findViewById(R.id.setting_menu11); CheckBox et9d = (CheckBox) settingsView.findViewById(R.id.setting_menu12); CheckBox et9e = (CheckBox) settingsView.findViewById(R.id.setting_menu13); CheckBox et9f = (CheckBox) settingsView.findViewById(R.id.setting_menu14); CheckBox et9g = (CheckBox) settingsView.findViewById(R.id.setting_menu21); CheckBox et9h = (CheckBox) settingsView.findViewById(R.id.setting_menu22); Spinner et10 = (Spinner) settingsView.findViewById(R.id.setting_heading); et1.setText(appURL); et2.setText(appPRE); et3.setText(appSCN); et4.setText(appKEY); et5.setText(appSCT); // get settings value for meteo station and set spinner String[] mTestArray; mTestArray = getResources().getStringArray(R.array.meteo_id_arrays); for (int i = 0; i < mTestArray.length; i++) { String s = mTestArray[i]; if (s.equals(appMST)) { et6.setSelection(i); } } et7.setText(appMTR); // get settings value for menu tabs and set checkboxes String v[] = appFLG.split(";"); et9a.setChecked(Boolean.parseBoolean(v[0])); et9b.setChecked(Boolean.parseBoolean(v[1])); et9c.setChecked(Boolean.parseBoolean(v[2])); et9d.setChecked(Boolean.parseBoolean(v[3])); et9e.setChecked(Boolean.parseBoolean(v[4])); et9f.setChecked(Boolean.parseBoolean(v[5])); et9g.setChecked(Boolean.parseBoolean(v[6])); et9h.setChecked(Boolean.parseBoolean(v[7])); // re-use mTestArray mTestArray = getResources().getStringArray(R.array.heading_arrays); for (int i = 0; i < mTestArray.length; i++) { String s = mTestArray[i]; if (s.equals(appLND)) { et10.setSelection(i); } } // show it alertDialog.show(); }
From source file:gr.scify.newsum.ui.ViewActivity.java
@Override public void run() { // take the String from the TopicActivity Bundle extras = getIntent().getExtras(); Category = extras.getString(CATEGORY_INTENT_VAR); // Make sure we have updated the data source NewSumUiActivity.setDataSource(this); // Get user sources String sUserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this); // get Topics from TopicActivity (avoid multiple server calls) TopicInfo[] tiTopics = TopicActivity.getTopics(sUserSources, Category, this); // Also get Topic Titles, to display to adapter final String[] saTopicTitles = new String[tiTopics.length]; // Also get Topic IDs final String[] saTopicIDs = new String[tiTopics.length]; // Also get Dates, in order to show in summary title final String[] saTopicDates = new String[tiTopics.length]; // DeHTML titles for (int iCnt = 0; iCnt < tiTopics.length; iCnt++) { // update Titles Array saTopicTitles[iCnt] = Html.fromHtml(tiTopics[iCnt].getTitle()).toString(); // update IDs Array saTopicIDs[iCnt] = tiTopics[iCnt].getID(); // update Date Array saTopicDates[iCnt] = tiTopics[iCnt].getPrintableDate(NewSumUiActivity.getDefaultLocale()); }//from w ww. ja va 2s. co m // get the value of the TopicIDs list size (to use in swipe) saTopicIDsLength = saTopicIDs.length; final TextView title = (TextView) findViewById(R.id.title); // Fill topic spinner final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, saTopicTitles); final TextView tx = (TextView) findViewById(R.id.textView1); // final float minm = tx.getTextSize(); // final float maxm = (minm + 24); // Get active topic int iTopicNum; // If we have returned from a pause if (iPrvSelectedItem >= 0) // use previous selection before pause iTopicNum = iPrvSelectedItem; // else else // use selection from topic page iTopicNum = extras.getInt(TOPIC_ID_INTENT_VAR); final int num = iTopicNum; // create an invisible spinner just to control the summaries of the // category (i will use it later on Swipe) final Spinner spinner = (Spinner) findViewById(R.id.spinner1); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); runOnUiThread(new Runnable() { @Override public void run() { spinner.setAdapter(adapter); // Scroll view init final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1); final String[] saTopicTitlesArg = saTopicTitles; final String[] saTopicIDsArg = saTopicIDs; final String[] SaTopicDatesArg = saTopicDates; // Add selection event spinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // Changing summary loading = true; showWaitingDialog(); // Update visibility of rating bar final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar); rb.setRating(0.0f); rb.setVisibility(View.VISIBLE); final TextView rateLbl = (TextView) findViewById(R.id.rateLbl); rateLbl.setVisibility(View.VISIBLE); scroll.scrollTo(0, 0); String UserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this); String[] saTopicIDs = saTopicIDsArg; // track summary views per category and topic title if (getAnalyticsPref()) { EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, Category, saTopicTitlesArg[arg2], 0l); } if (sCustomCategory.trim().length() > 0) { if (Category.equals(sCustomCategory)) { Context ctxCur = NewSumUiActivity.getAppContext(ViewActivity.this); String sCustomCategoryURL = ctxCur.getResources() .getString(R.string.custom_category_url); // Check if specific element needs to be read String sElementID = ctxCur.getResources() .getString(R.string.custom_category_elementId); // If an element needs to be selected if (sElementID.trim().length() > 0) { try { // Check if specific element needs to be read String sViewOriginalPage = ctxCur.getResources() .getString(R.string.custom_category_visit_source); // Init text by a link to the original page sText = "<p><a href='" + sCustomCategoryURL + "'>" + sViewOriginalPage + "</a></p>"; // Get document Document doc = Jsoup.connect(sCustomCategoryURL).get(); // If a table Element eCur = doc.getElementById(sElementID); if (eCur.tagName().equalsIgnoreCase("table")) { // Get table rows Elements eRows = eCur.select("tr"); // For each row StringBuffer sTextBuf = new StringBuffer(); for (Element eCurRow : eRows) { // Append content // TODO: Use HTML if possible. Now problematic (crashes when we click on link) sTextBuf.append("<p>" + eCurRow.text() + "</p>"); } // Return as string sText = sText + sTextBuf.toString(); } else // else get text sText = eCur.text(); } catch (IOException e) { // Show unavailable text sText = ctxCur.getResources() .getString(R.string.custom_category_unavailable); e.printStackTrace(); } } else sText = Utils.getFromHttp(sCustomCategoryURL, false); } } else { // call getSummary with (sTopicID, sUserSources). Use "All" for // all Sources String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources); // check if Summary exists, otherwise display message if (Summary.length == 0) { // DONE APPLICATION HANGS, DOES NOT // WORK. Updated: Probably OK nothingFound = true; AlertDialog.Builder al = new AlertDialog.Builder(ViewActivity.this); al.setMessage(R.string.shouldReloadSummaries); al.setNeutralButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { // Reset cache CacheController.clearCache(); // Restart main activity startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); } }); al.setCancelable(false); al.show(); // Return to home activity loading = false; return; } // Generate Summary text for normal categories sText = generateSummaryText(Summary, ViewActivity.this); pText = generatesummarypost(Summary, ViewActivity.this); } // Update HTML tx.setText(Html.fromHtml(sText)); // Allow links to be followed into browser tx.setMovementMethod(LinkMovementMethod.getInstance()); // Also Add Date to Topic Title inside Summary title.setText(saTopicTitlesArg[arg2] + " : " + SaTopicDatesArg[arg2]); // Update size updateTextSize(); // Update visited topics TopicActivity.addVisitedTopicID(saTopicIDs[arg2]); // Done loading = false; closeWaitingDialog(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); runOnUiThread(new Runnable() { @Override public void run() { // Get active topic spinner.setSelection(num); } }); } }); runOnUiThread(new Runnable() { @Override public void run() { showHelpDialog(); } }); closeWaitingDialog(); }
From source file:knayi.delevadriver.JobDetailActivity.java
@Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); final long timestamp = System.currentTimeMillis(); final String token = sPref.getString(Config.TOKEN, null); switch (v.getId()) { case R.id.job_reject: if (job_reject.getText().toString().equals("Reject")) { MaterialDialog dialog = new MaterialDialog.Builder(this).titleColor(R.color.white) .customView(R.layout.reject_layout, true).positiveText("REJECT") .positiveColor(R.color.white).positiveColorRes(R.color.white).negativeText("CANCEL") .negativeColorRes(R.color.white).backgroundColorRes(R.color.primary) .typeface("ciclefina.ttf", "ciclegordita.ttf") .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(final MaterialDialog dialog) { super.onPositive(dialog); EditText et_message = (EditText) dialog.findViewById(R.id.reject_message); if (!et_message.getText().toString().equals("")) { AvaliableJobsAPI.getInstance().getService().rejectJob(jobitem.get_id(), token, et_message.getText().toString(), "true", new Callback<String>() { @Override public void success(String s, Response response) { Toast.makeText(JobDetailActivity.this, "Job is successfully rejected", Toast.LENGTH_SHORT) .show(); dialog.dismiss(); //remove job id that is saved to use in locatin update sPref.edit().putString(Config.TOKEN_JOBID, null).commit(); sPref.edit().putString(Config.TOKEN_DELAY, null).commit(); //check report service is alive //if alive stop service if (sPref.getBoolean(Config.TOKEN_SERVICE_ALIVE, false)) { Intent intentservice = new Intent(JobDetailActivity.this, BackgroundLocationService.class); stopService(intentservice); } Intent intent = new Intent(JobDetailActivity.this, DrawerMainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); } @Override public void failure(RetrofitError error) { if (error.getBody() == null) { Toast.makeText(JobDetailActivity.this, "Cannot connect to server!", Toast.LENGTH_SHORT) .show(); } else { String errmsg = error.getBody().toString(); String errcode = ""; try { JSONObject errobj = new JSONObject(errmsg); errcode = errobj.getJSONObject("err") .getString("message"); Toast.makeText(JobDetailActivity.this, errcode, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } dialog.dismiss(); } }); } else { Toast.makeText(JobDetailActivity.this, "Please enter your message", Toast.LENGTH_SHORT).show(); }/*w ww.j a va 2 s. co m*/ progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } } ).build(); dialog.show(); EditText et_message = (EditText) dialog.findViewById(R.id.reject_message); et_message.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); } /*else{ final Dialog msgDialog = new Dialog(JobDetailActivity.this); msgDialog.setTitle("Why do u reject?"); msgDialog.setCancelable(true); msgDialog.setContentView(R.layout.custom_dialog_reason); final EditText message = (EditText) msgDialog.findViewById(R.id.messagebox); Button submit = (Button) msgDialog.findViewById(R.id.submitbutton); msgDialog.show(); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progress.setVisibility(View.VISIBLE); progress_background.setVisibility(View.VISIBLE); if(message.getText().toString().equals("") && message.getText().toString().equals(null)){ Toast.makeText(getApplicationContext(), "Please input message to submit", Toast.LENGTH_SHORT).show(); }else{ msgDialog.dismiss(); progress.setVisibility(View.VISIBLE); progress_background.setVisibility(View.VISIBLE); if(token == null){ new SweetAlertDialog(JobDetailActivity.this, SweetAlertDialog.WARNING_TYPE) .setTitleText("") .setContentText("Please Login again!") .show(); finish(); startActivity(new Intent(JobDetailActivity.this, LoginActivity.class)); } else{ AvaliableJobsAPI.getInstance().getService().rejectJob(jobitem.get_id(), token, location, String.valueOf(timestamp), message.getText().toString(), new Callback<String>() { @Override public void success(String s, Response response) { progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); startActivity(new Intent(JobDetailActivity.this, TabMainActivity.class)); finish(); } @Override public void failure(RetrofitError error) { progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show(); } }); } } } }); }*/ break; case R.id.job_bid: progress.setVisibility(View.VISIBLE); progress_background.setVisibility(View.VISIBLE); if (token == null) { MaterialDialog dialog = new MaterialDialog.Builder(this) .customView(R.layout.custom_message_dialog, false).positiveText("OK") .positiveColor(R.color.white).positiveColorRes(R.color.white) .backgroundColorRes(R.color.primary).typeface("ciclefina.ttf", "ciclegordita.ttf").build(); dialog.show(); TextView txt_title = (TextView) dialog.findViewById(R.id.dialog_title); TextView txt_message = (TextView) dialog.findViewById(R.id.dialog_message); txt_title.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); txt_message.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); txt_title.setText("Please Login again!"); txt_message.setText("Server doesn't know this account!"); Intent intent = new Intent(JobDetailActivity.this, LoginActivity.class); startActivity(intent); finish(); } if (job_bid.getText().toString().equals("Bid")) { final long ts1 = System.currentTimeMillis(); Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { location = mLastLocation.getLongitude() + "," + mLastLocation.getLatitude(); } acceptJob(token, String.valueOf(ts1), ""); /*MaterialDialog dialog = new MaterialDialog.Builder(this) .title("Estimate time of arrival to pick up point") .customView(R.layout.estimatetime_layout, true) .positiveText("BID") .positiveColor(R.color.primary) .positiveColorRes(R.color.primary) .negativeText("CANCEL") .negativeColorRes(R.color.primary) .cancelable(false) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); EditText et_estimatetime = (EditText) dialog.findViewById(R.id.estimatetime_et); if(!et_estimatetime.getText().toString().equals("")) { acceptJob(token, String.valueOf(ts1), et_estimatetime.getText().toString()); }else{ Toast.makeText(JobDetailActivity.this, "Please Input Fields!", Toast.LENGTH_SHORT).show(); progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } } ) .build(); dialog.show(); final EditText et_estimatetime = (EditText) dialog.findViewById(R.id.estimatetime_et); et_estimatetime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar mcurrentTime = Calendar.getInstance(); int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); int minute = mcurrentTime.get(Calendar.MINUTE); TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(JobDetailActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { et_estimatetime.setText( selectedHour + ":" + selectedMinute); } }, hour, minute, true);//Yes 24 hour time mTimePicker.setTitle("Select Time"); mTimePicker.show(); } });*/ } else if (job_bid.getText().toString().equals("Agree")) { AvaliableJobsAPI.getInstance().getService().agreeJob(jobitem.get_id(), token, "true", new Callback<String>() { @Override public void success(String s, Response response) { Toast.makeText(JobDetailActivity.this, "Success", Toast.LENGTH_SHORT).show(); getDataFromServer(job_id); } @Override public void failure(RetrofitError error) { if (error.getBody() == null) { Toast.makeText(JobDetailActivity.this, "Cannot connect to server!", Toast.LENGTH_SHORT).show(); } else { String errmsg = error.getBody().toString(); String errcode = ""; try { JSONObject errobj = new JSONObject(errmsg); errcode = errobj.getJSONObject("err").getString("message"); Toast.makeText(JobDetailActivity.this, errcode, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } } }); } else if (job_bid.getText().toString().equals("Finished")) { MaterialDialog dialog = new MaterialDialog.Builder(this).titleColor(R.color.white) .customView(R.layout.custom_request_message_dialog, true).positiveText("SEND") .positiveColor(R.color.white).positiveColorRes(R.color.white).negativeText("CANCEL") .negativeColorRes(R.color.white).backgroundColorRes(R.color.primary) .typeface("ciclefina.ttf", "ciclegordita.ttf") .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); EditText request_secret_code = (EditText) dialog .findViewById(R.id.request_secret_code); /*EditText request_msg = (EditText) dialog.findViewById(R.id.request_msg);*/ if (request_secret_code != null) { if (request_secret_code.getText().toString() != null && request_secret_code.getText().toString() != "") { Location mLastLocation = LocationServices.FusedLocationApi .getLastLocation(mGoogleApiClient); Long tsLong = System.currentTimeMillis(); String ts = tsLong.toString(); String location = "96,16"; if (mLastLocation != null) { location = mLastLocation.getLongitude() + "," + mLastLocation.getLatitude(); } final long timestamp = System.currentTimeMillis(); JSONObject obj = new JSONObject(); try { obj.put("location", location); obj.put("timestamp", String.valueOf(timestamp)); obj.put("secret_code", request_secret_code.getText().toString()); obj.put("message", "");//request_msg.getText().toString()); } catch (JSONException e) { e.printStackTrace(); } String json = obj.toString(); try { TypedInput in = new TypedByteArray("application/json", json.getBytes("UTF-8")); progress.setVisibility(View.VISIBLE); progress_background.setVisibility(View.VISIBLE); AvaliableJobsAPI.getInstance().getService().jobDone(jobitem.get_id(), token, in, new Callback<String>() { @Override public void success(String s, Response response) { Toast.makeText(JobDetailActivity.this, "Message is sent successfully", Toast.LENGTH_SHORT).show(); sPref.edit().putString(Config.TOKEN_DELAY, null) .commit(); if (sPref.getBoolean(Config.TOKEN_SERVICE_ALIVE, false)) { Intent intentservice = new Intent( JobDetailActivity.this, BackgroundLocationService.class); stopService(intentservice); } progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); bitLayout.setVisibility(View.GONE); } @Override public void failure(RetrofitError error) { //Toast.makeText(JobDetailActivity.this, "Failed, Please Try Again!", Toast.LENGTH_SHORT).show(); if (error.getBody() == null) { Toast.makeText(JobDetailActivity.this, "Cannot connect to server!", Toast.LENGTH_SHORT).show(); } else { String errmsg = error.getBody().toString(); String errcode = ""; try { JSONObject errobj = new JSONObject(errmsg); errcode = errobj.getJSONObject("err") .getString("message"); Toast.makeText(JobDetailActivity.this, errcode, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } }); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } } ).build(); dialog.show(); EditText request_secret_code = (EditText) dialog.findViewById(R.id.request_secret_code); /*EditText request_msg = (EditText) dialog.findViewById(R.id.request_msg);*/ request_secret_code.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); /*request_msg.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL));*/ } break; case R.id.job_report: isFirstDialog = true; totalprice = Double.parseDouble(jobitem.get_price()); final MaterialDialog dialog = new MaterialDialog.Builder(this).customView(R.layout.report_layout, true) .positiveText("REPORT").positiveColor(R.color.white).positiveColorRes(R.color.white) .negativeText("CANCEL").negativeColorRes(R.color.white).backgroundColorRes(R.color.primary) .typeface("ciclefina.ttf", "ciclegordita.ttf").callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(final MaterialDialog dialog) { super.onPositive(dialog); CheckBox cb_weight = (CheckBox) dialog.findViewById(R.id.report_cb_overweight); CheckBox cb_express = (CheckBox) dialog.findViewById(R.id.report_cb_express); CheckBox cb_refrig = (CheckBox) dialog.findViewById(R.id.report_cb_refrigerated); //CheckBox cb_type = (CheckBox) dialog.findViewById(R.id.report_cb_type); final Spinner sp_weight = (Spinner) dialog.findViewById(R.id.report_spinner_overweight); //final Spinner sp_type = (Spinner) dialog.findViewById(R.id.report_spinner_type); EditText et_message = (EditText) dialog.findViewById(R.id.report_et_message); //Refrage if (!et_message.getText().toString().equals("") && et_message.getText().toString() != null) { if (cb_weight.isChecked() || cb_express.isChecked() || cb_refrig.isChecked()) { String message = "";//et_message.getText().toString(); if (cb_express.isChecked()) { message += "true,"; } else { message += "false,"; } if (cb_refrig.isChecked()) { message += "true,"; } else { message += "false,"; } if (cb_weight.isChecked()) { message += weightlist.get(sp_weight.getSelectedItemPosition()) + ","; } else { message += ","; } AvaliableJobsAPI.getInstance().getService().reportJob(jobitem.get_id(), token, message, "0", new Callback<String>() { @Override public void success(String s, Response response) { Toast.makeText(JobDetailActivity.this, "Your report has successfully sent", Toast.LENGTH_SHORT) .show(); dialog.dismiss(); } @Override public void failure(RetrofitError error) { //Toast.makeText(JobDetailActivity.this, "Report is Failed", Toast.LENGTH_SHORT).show(); if (error.getBody() == null) { Toast.makeText(JobDetailActivity.this, "Cannot connect to server!", Toast.LENGTH_SHORT) .show(); } else { String errmsg = error.getBody().toString(); String errcode = ""; try { JSONObject errobj = new JSONObject(errmsg); errcode = errobj.getJSONObject("err") .getString("message"); Toast.makeText(JobDetailActivity.this, errcode, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } dialog.dismiss(); } }); } else { Toast.makeText(JobDetailActivity.this, "Please select report reason", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(JobDetailActivity.this, "Please enter your message", Toast.LENGTH_SHORT).show(); } progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); progress.setVisibility(View.INVISIBLE); progress_background.setVisibility(View.INVISIBLE); } } ).build(); dialog.show(); final CheckBox cb_weight = (CheckBox) dialog.findViewById(R.id.report_cb_overweight); //final CheckBox cb_type = (CheckBox) dialog.findViewById(R.id.report_cb_type); CheckBox cb_express = (CheckBox) dialog.findViewById(R.id.report_cb_express); CheckBox cb_refrig = (CheckBox) dialog.findViewById(R.id.report_cb_refrigerated); EditText et_message = (EditText) dialog.findViewById(R.id.report_et_message); et_message.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); cb_weight.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); cb_express.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); cb_refrig.setTypeface(MyTypeFace.get(JobDetailActivity.this, MyTypeFace.NORMAL)); if (jobitem.getIsExpress().equals("true")) { cb_express.setChecked(true); } if (jobitem.getIsRefrigerated().equals("true")) { cb_refrig.setChecked(true); } //final TextView tv_price = (TextView) dialog.findViewById(R.id.report_price_tag); final Spinner sp_weight = (Spinner) dialog.findViewById(R.id.report_spinner_overweight); //final Spinner sp_type = (Spinner) dialog.findViewById(R.id.report_spinner_type); sp_weight.setEnabled(false); //sp_type.setEnabled(false); //tv_price.setText("price " + jobitem.get_price()); sp_weight.setAdapter(new ArrayAdapter<String>(JobDetailActivity.this, android.R.layout.simple_spinner_dropdown_item, weightshowlist)); //sp_type.setAdapter(new ArrayAdapter<String>(JobDetailActivity.this, android.R.layout.simple_spinner_dropdown_item, new String[]{"Other", "Express", "Refrigerated"})); sp_weight.setSelection(weightpos); //sp_type.setSelection(typepos); sp_weight.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (!isFirstDialog) { totalprice += weightPricelist.get(sp_weight.getSelectedItemPosition()); } else { isFirstDialog = false; } /*if(cb_type.isChecked()){ totalprice += typepricelist.get(position); }*/ // tv_price.setText("price " + String.valueOf(totalprice)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); /*sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { totalprice = Double.parseDouble(jobitem.get_price()); if (!isFirstDialog) { totalprice += typepricelist.get(position); } else { isFirstDialog = false; } if (cb_weight.isChecked()) { totalprice += weightPricelist.get(sp_weight.getSelectedItemPosition()); } tv_price.setText("price " + String.valueOf(totalprice)); } @Override public void onNothingSelected(AdapterView<?> parent) { } });*/ cb_weight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { sp_weight.setEnabled(true); totalprice += weightPricelist.get(sp_weight.getSelectedItemPosition()); } else { sp_weight.setEnabled(false); totalprice -= weightPricelist.get(sp_weight.getSelectedItemPosition()); } //tv_price.setText("price " + String.valueOf(totalprice)); } }); /*cb_type.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ sp_type.setEnabled(true); totalprice += typepricelist.get(sp_type.getSelectedItemPosition()); }else{ sp_type.setEnabled(false); totalprice -= typepricelist.get(sp_type.getSelectedItemPosition()); } tv_price.setText("price " + String.valueOf(totalprice)); } });*/ break; default: Intent intent = new Intent(JobDetailActivity.this, DrawerMainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); break; } }