List of usage examples for android.widget ArrayAdapter add
public void add(@Nullable T object)
From source file:org.cvasilak.jboss.mobile.app.fragments.DeploymentsViewFragment.java
public void showRepositoryDeploymentsOptionsMenu() { ProgressDialogFragment.showDialog(getActivity(), R.string.queryingServer); application.getOperationsManager().fetchDeployments(null, new Callback() { @Override/*from www . ja v a2 s.co m*/ public void onSuccess(JsonElement reply) { ProgressDialogFragment.dismissDialog(getActivity()); String name, runtimeName, BYTES_VALUE; boolean enabled = false; JsonObject jsonObj = reply.getAsJsonObject(); final ArrayAdapter<Deployment> repoAdapter = new ArrayAdapter<Deployment>(getActivity(), android.R.layout.select_dialog_singlechoice); for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) { name = e.getKey(); JsonObject detailsJsonObj = e.getValue().getAsJsonObject(); if (detailsJsonObj.get("enabled") != null) enabled = detailsJsonObj.get("enabled").getAsBoolean(); runtimeName = detailsJsonObj.get("runtime-name").getAsString(); // "content" : [{"hash" : { "BYTES_VALUE" : "Pb4xyzgJmsxruKEf5eGOLu6lBjw="}}], BYTES_VALUE = detailsJsonObj.get("content").getAsJsonArray().get(0).getAsJsonObject() .get("hash").getAsJsonObject().get("BYTES_VALUE").getAsString(); repoAdapter.add(new Deployment(name, runtimeName, enabled, BYTES_VALUE)); } selectedAlertDialogItemPos = -1; // reset any previous selected value // time to display content repository AlertDialog.Builder filesDialog = new AlertDialog.Builder(getActivity()); filesDialog.setTitle(R.string.add_deployment_from_repository); filesDialog.setSingleChoiceItems(repoAdapter, selectedAlertDialogItemPos, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { selectedAlertDialogItemPos = ((AlertDialog) dialogInterface).getListView() .getCheckedItemPosition(); // enable buttons if a deployment is clicked ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL) .setEnabled(true); ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE) .setEnabled(true); } }); // Cancel Button filesDialog.setNegativeButton(R.string.cancel, null); // Add to Group Button filesDialog.setNeutralButton(R.string.add_to_group, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addDeployment(repoAdapter.getItem(selectedAlertDialogItemPos), false, Arrays.asList(group)); } }); // Add to Group and Enable Button filesDialog.setPositiveButton(R.string.add_to_group_enable, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addDeployment(repoAdapter.getItem(selectedAlertDialogItemPos), true, Arrays.asList(group)); } }); filesDialog.setCancelable(true); ParameterizedDialogFragment dialog = new ParameterizedDialogFragment(filesDialog, new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialogInterface) { ((AlertDialog) dialogInterface).getListView() .setItemChecked(selectedAlertDialogItemPos, true); ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL) .setEnabled(selectedAlertDialogItemPos != -1); ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE) .setEnabled(selectedAlertDialogItemPos != -1); } }); dialog.show(getActivity().getSupportFragmentManager(), null); } @Override public void onFailure(Exception e) { ProgressDialogFragment.dismissDialog(getActivity()); ErrorDialogFragment.showDialog(getActivity(), e.getMessage()); } }); }
From source file:com.nttec.everychan.ui.ShareActivity.java
private void handleIntent(Intent intent) { ArrayAdapter<Pair<TabModel, SerializablePage>> adapter = new ArrayAdapter<Pair<TabModel, SerializablePage>>( this, 0) { private final int drawablePadding = (int) (getResources().getDisplayMetrics().density * 5 + 0.5f); @Override//from w ww. ja v a 2s.co m public View getView(int position, View convertView, ViewGroup parent) { View view = convertView == null ? getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false) : convertView; TextView tv = (TextView) view.findViewById(android.R.id.text1); tv.setEllipsize(TextUtils.TruncateAt.END); tv.setSingleLine(); tv.setText(getItem(position).getLeft().title); tv.setCompoundDrawablesWithIntrinsicBounds(MainApplication.getInstance() .getChanModule(getItem(position).getLeft().pageModel.chanName).getChanFavicon(), null, null, null); tv.setCompoundDrawablePadding(drawablePadding); return view; } }; for (TabModel tab : MainApplication.getInstance().tabsState.tabsArray) { if (tab.type == TabModel.TYPE_NORMAL && tab.pageModel.type != UrlPageModel.TYPE_SEARCHPAGE) { SerializablePage page = MainApplication.getInstance().pagesCache.getSerializablePage(tab.hash); if (page != null) { adapter.add(Pair.of(tab, page)); } } } if (adapter.getCount() == 0) { for (Database.HistoryEntry entity : MainApplication.getInstance().database.getHistory()) { try { TabModel tab = new TabModel(); tab.title = entity.title; tab.type = TabModel.TYPE_NORMAL; tab.webUrl = entity.url; tab.pageModel = UrlHandler.getPageModel(entity.url); tab.hash = ChanModels.hashUrlPageModel(tab.pageModel); SerializablePage page = MainApplication.getInstance().pagesCache.getSerializablePage(tab.hash); if (page != null) { adapter.add(Pair.of(tab, page)); } } catch (Exception e) { Logger.e(TAG, e); } } if (adapter.getCount() == 0) { Toast.makeText(this, R.string.share_no_tabs, Toast.LENGTH_LONG).show(); finish(); return; } } if (PostingService.isNowPosting()) { Toast.makeText(this, R.string.posting_now_posting, Toast.LENGTH_LONG).show(); finish(); return; } selectedFile = null; if (intent != null) { Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (uri != null) { File file = UriFileUtils.getFile(this, uri); if (file != null) { selectedFile = file; } } } if (selectedFile == null) { Toast.makeText(this, R.string.postform_cannot_attach, Toast.LENGTH_LONG).show(); finish(); return; } setListAdapter(adapter); }
From source file:org.cvasilak.jboss.mobile.admin.fragments.DeploymentsViewFragment.java
public void showRepositoryDeploymentsOptionsMenu() { progress = ProgressDialog.show(getSherlockActivity(), "", getString(R.string.queryingServer)); application.getOperationsManager().fetchDeployments(null, new Callback() { @Override//from w w w . j a v a 2 s. co m public void onSuccess(JsonElement reply) { progress.dismiss(); String name, runtimeName, BYTES_VALUE; boolean enabled = false; JsonObject jsonObj = reply.getAsJsonObject(); final ArrayAdapter<Deployment> repoAdapter = new ArrayAdapter<Deployment>(getActivity(), android.R.layout.simple_list_item_single_choice); for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) { name = e.getKey(); JsonObject detailsJsonObj = e.getValue().getAsJsonObject(); if (detailsJsonObj.get("enabled") != null) enabled = detailsJsonObj.get("enabled").getAsBoolean(); runtimeName = detailsJsonObj.get("runtime-name").getAsString(); // "content" : [{"hash" : { "BYTES_VALUE" : "Pb4xyzgJmsxruKEf5eGOLu6lBjw="}}], BYTES_VALUE = detailsJsonObj.get("content").getAsJsonArray().get(0).getAsJsonObject() .get("hash").getAsJsonObject().get("BYTES_VALUE").getAsString(); repoAdapter.add(new Deployment(name, runtimeName, enabled, BYTES_VALUE)); } // time to display content repository AlertDialog.Builder filesDialog = new AlertDialog.Builder(getActivity()); filesDialog.setTitle(R.string.add_deployment_from_repository); filesDialog.setSingleChoiceItems(repoAdapter, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // enable buttons if a deployment is clicked ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(true); ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true); } }); // Cancel Button filesDialog.setNegativeButton(R.string.cancel, null); // Add to Group Button filesDialog.setNeutralButton(R.string.add_to_group, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { int selectedPosition = ((AlertDialog) dialogInterface).getListView() .getCheckedItemPosition(); addDeployment(repoAdapter.getItem(selectedPosition), false, Arrays.asList(group)); } }); // Add to Group and Enable Button filesDialog.setPositiveButton(R.string.add_to_group_enable, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { int selectedPosition = ((AlertDialog) dialogInterface).getListView() .getCheckedItemPosition(); addDeployment(repoAdapter.getItem(selectedPosition), true, Arrays.asList(group)); } }); filesDialog.setCancelable(true); AlertDialog dialog = filesDialog.create(); // initially show add* buttons disabled // wait until a deployment is enabled dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialogInterface) { ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(false); ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); } }); dialog.show(); } @Override public void onFailure(Exception e) { progress.dismiss(); AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()); alertDialog.setTitle(R.string.dialog_error_title).setMessage(e.getMessage()) .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false) .setIcon(android.R.drawable.ic_dialog_alert).show(); } }); }
From source file:com.nextgis.mobile.forms.DescriptionFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.setRetainInstance(true); View view = inflater.inflate(R.layout.descriptfragment, container, false); final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_spinner_item); final Map<String, ArrayList<String>> mlCategories = new HashMap<String, ArrayList<String>>(); //fill spinners from xml data XmlPullParser parser = Xml.newPullParser(); try {/*from ww w .ja v a 2 s. co m*/ File file = new File(getActivity().getExternalFilesDir(null), "categories.xml"); if (file != null) { if (!file.exists()) { createExternalStoragePrivateFile(); file = new File(getActivity().getExternalFilesDir(null), "categories.xml"); } InputStream in = new BufferedInputStream(new FileInputStream(file)); InputStreamReader isr = new InputStreamReader(in); // auto-detect the encoding from the stream parser.setInput(isr); int eventType = parser.getEventType(); String sCatVal = null; while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: String name = parser.getName(); if (name.equalsIgnoreCase("category")) { sCatVal = parser.getAttributeValue(null, "name"); adapter.add(sCatVal); mlCategories.put(sCatVal, new ArrayList<String>()); } else if (name.equalsIgnoreCase("subcategory")) { if (sCatVal != null) { String sSubCatVal = parser.getAttributeValue(null, "name"); mlCategories.get(sCatVal).add(sSubCatVal); } } break; } eventType = parser.next(); } if (in != null) { in.close(); } } } catch (IOException e) { // TODO } catch (Exception e) { // TODO } Spinner spinner = (Spinner) view.findViewById(R.id.spinner_cat); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { final Spinner subspinner = (Spinner) getView().findViewById(R.id.spinner_subcat); //subspinner String sCat = adapter.getItem(arg2).toString(); TextView textview = (TextView) getView().findViewById(R.id.spinner_subcat_custom); if (sCat.equalsIgnoreCase("custom")) { //enable text item textview.setEnabled(true); } else { textview.setEnabled(false); } ArrayAdapter<String> subadapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, mlCategories.get(sCat)); subadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); subspinner.setAdapter(subadapter); } public void onNothingSelected(AdapterView<?> arg0) { } }); onStoreValues(); return view; }
From source file:com.example.yudiandrean.socioblood.FeedActivity.java
@SuppressLint("NewApi") @Override// ww w. j av a 2 s.c o m protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Dialog d = new Dialog(context); setContentView(R.layout.feed_activity); postrequest = (TextView) findViewById(R.id.editText); WindowManager manager = (WindowManager) getSystemService(Activity.WINDOW_SERVICE); final int width, height; ActionBar.LayoutParams params; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) { width = manager.getDefaultDisplay().getWidth(); height = manager.getDefaultDisplay().getHeight(); } else { Point point = new Point(); manager.getDefaultDisplay().getSize(point); width = point.x; height = point.y; } session = new SessionManager(getApplicationContext()); // Check if user is already logged in or not if (!session.isLoggedIn()) { // User is already logged in. Take him to main activity Intent intent = new Intent(FeedActivity.this, LoginActivity.class); startActivity(intent); finish(); } listView = (ListView) findViewById(R.id.list); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); feedItems = new ArrayList<FeedItem>(); listAdapter = new FeedListAdapter(this, feedItems); listView.setAdapter(listAdapter); swipeRefreshLayout.setOnRefreshListener(this); // add button listener postrequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { try { d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.post_request); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(d.getWindow().getAttributes()); lp.width = width; lp.height = height; d.getWindow().setAttributes(lp); } catch (AndroidRuntimeException e) { } catch (Exception e) { } final Spinner rhesusspinner = (Spinner) d.findViewById(R.id.rhesus_spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(FeedActivity.this, android.R.layout.simple_spinner_dropdown_item) { @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if (position == getCount()) { ((TextView) v.findViewById(android.R.id.text1)).setText(""); ((TextView) v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed" } return v; } @Override public int getCount() { return super.getCount() - 1; // you dont display last item. It is used as hint. } }; adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapter.add("+"); adapter.add("-"); adapter.add("Rhesus"); rhesusspinner.setAdapter(adapter); rhesusspinner.setSelection(adapter.getCount()); //display hint final Spinner bloodspinner = (Spinner) d.findViewById(R.id.bloodtype_spinner); ArrayAdapter<String> bloodadapter = new ArrayAdapter<String>(FeedActivity.this, android.R.layout.simple_spinner_dropdown_item) { @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if (position == getCount()) { ((TextView) v.findViewById(android.R.id.text1)).setText(""); ((TextView) v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed" } return v; } @Override public int getCount() { return super.getCount() - 1; // you dont display last item. It is used as hint. } }; bloodadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); bloodadapter.add("O"); bloodadapter.add("A"); bloodadapter.add("B"); bloodadapter.add("AB"); bloodadapter.add("Desired Type"); bloodspinner.setAdapter(bloodadapter); bloodspinner.setSelection(bloodadapter.getCount()); //display hint //Buttons-Editexts Button btnpost = (Button) d.findViewById(R.id.post); final EditText userInput = (EditText) d.findViewById(R.id.editTextDialogUserInput); d.show(); btnpost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (bloodspinner.getSelectedItem().toString().equals("Desired Type")) { Toast.makeText(getApplicationContext(), "Input Blood Type!", Toast.LENGTH_SHORT).show(); } else if (rhesusspinner.getSelectedItem().toString().equals("Rhesus")) { Toast.makeText(getApplicationContext(), "Input Rhesus!", Toast.LENGTH_SHORT).show(); } else if (userInput.getText().toString().equals("")) { Toast.makeText(getApplicationContext(), "Input your request message!", Toast.LENGTH_SHORT).show(); } else { int uid = session.currentUID(); String message = userInput.getText().toString(); String post_bloodtype = bloodspinner.getSelectedItem().toString(); String post_rhesus = rhesusspinner.getSelectedItem().toString(); NetAsync(d, view, uid, message, post_bloodtype, post_rhesus); } } }); } }); // // We first check for cached request // Cache cache = FeedController.getInstance().getRequestQueue().getCache(); // Entry entry = cache.get(URL_FEED); // if (entry != null) { // // fetch the data from cache // try { // String data = new String(entry.data, "UTF-8"); // try { // parseJsonFeed(new JSONObject(data)); // } catch (JSONException e) { // e.printStackTrace(); // } // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // } else { // making fresh volley request and getting json /** * Showing Swipe Refresh animation on activity create * As animation won't start on onCreate, post runnable is used */ swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); getTimelineAsync(); } }); }
From source file:com.mantz_it.rfanalyzer.ui.activity.MainActivity.java
public void showRecordingDialog() { if (!running || scheduler == null || demodulator == null || source == null) { toaster.showLong("Analyzer must be running to start recording"); return;/*from w ww. j av a 2 s .c om*/ } // 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 = rxSampleRate.getSupportedSampleRates(); final double maxFreqMHz = rxFrequency.getMax() / 1000000f; // max frequency of the source in MHz final int sourceType = Integer.parseInt(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<>(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.parseDouble(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.parseDouble(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((buttonView, isChecked) -> { et_stopAfter.setEnabled(isChecked); sp_stopAfter.setEnabled(isChecked); }); // Set default frequency, sample rate and stop after values: et_frequency.setText(Long.toString(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( Integer.toString(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(rxSampleRate.get()); // add the current sample rate in case it's not already in the list sp_sampleRate.setSelection(sampleRateAdapter.getPosition(rxSampleRate.get())); // 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", (dialog, whichButton) -> { String filename = et_filename.getText().toString(); final int stopAfterUnit = sp_stopAfter.getSelectedItemPosition(); final int stopAfterValue = Integer.parseInt(et_stopAfter.getText().toString()); //todo check filename // Set the frequency in the source: if (et_frequency.getText().length() == 0) return; double freq = Double.parseDouble(et_frequency.getText().toString()); if (freq < maxFreqMHz) freq = freq * 1000000; if (freq <= rxFrequency.getMax() && freq >= rxFrequency.getMin()) rxFrequency.set((long) freq); else { toaster.showLong("Frequency is invalid!"); return; } // Set the sample rate (only if demodulator is off): if (demodulationMode == Demodulator.DEMODULATION_OFF) rxSampleRate.set((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()) { final String recorderSuperviserName = "Supervisor Thread"; Thread supervisorThread = new Thread(() -> { Log.i(LOGTAG, "recording_superviser: Supervisor Thread started. (Thread: " + recorderSuperviserName + ")"); 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) { // todo: shouldn't we call stopRecording() here? how about finally{}? 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: " + recorderSuperviserName + ")"); }, recorderSuperviserName); supervisorThread.start(); } }).setNegativeButton("Cancel", (dialog, whichButton) -> { // do nothing }).show().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); }
From source file:de.mkrtchyan.recoverytools.FlashFragment.java
public void FlashSupportedKernel(Card card) { final File path; ArrayList<String> Versions; ArrayAdapter<String> VersionsAdapter = new ArrayAdapter<>(mContext, R.layout.custom_list_item); if (!mDevice.downloadUtils(mContext)) { /**//from w w w. ja v a 2 s .co m * If there files be needed to flash download it and listing device specified recovery * file for example stock-boot-grouper-4.4.img (read out from kernel_sums) */ String SYSTEM = card.getData().toString(); if (SYSTEM.equals("stock")) { Versions = mDevice.getStockKernelVersions(); path = Constants.PathToStockKernel; for (String i : Versions) { try { String version = i.split("-")[3].replace(mDevice.getRecoveryExt(), ""); String deviceName = i.split("-")[2]; VersionsAdapter.add("Stock Kernel " + version + " (" + deviceName + ")"); } catch (ArrayIndexOutOfBoundsException e) { VersionsAdapter.add(i); } } } else { return; } final AppCompatDialog KernelDialog = new AppCompatDialog(mContext); KernelDialog.setTitle(SYSTEM); ListView VersionList = new ListView(mContext); KernelDialog.setContentView(VersionList); VersionList.setAdapter(VersionsAdapter); KernelDialog.show(); VersionList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { KernelDialog.dismiss(); final String fileName; if ((fileName = ((AppCompatTextView) view).getText().toString()) != null) { final File kernel = new File(path, fileName); if (!kernel.exists()) { try { URL url = new URL(Constants.KERNEL_URL + "/" + fileName); Downloader KernelDownloader = new Downloader(mContext, url, kernel); KernelDownloader.setOnDownloadListener(new Downloader.OnDownloadListener() { @Override public void success(File file) { flashKernel(file); } @Override public void failed(Exception e) { } }); KernelDownloader.setRetry(true); KernelDownloader.setAskBeforeDownload(true); KernelDownloader.setChecksumFile(KernelCollectionFile); KernelDownloader.ask(); } catch (MalformedURLException ignored) { } } else { flashKernel(kernel); } } } }); } }
From source file:com.example.android.bluetoothchat.DeviceListActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ??//from www . j a v a 2 s . c om requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_device_list); // ????????????CANCELED setResult(Activity.RESULT_CANCELED); // ???????? Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doDiscovery(); v.setVisibility(View.GONE); } }); //??????? Button startchatButton = (Button) findViewById(R.id.button_start_chat); startchatButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { connect(); } }); // array adapters??. // ?????????????? ArrayAdapter<String> pairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); // ????ListView? pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(pairedDevicesArrayAdapter); pairedListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // ????????ListView? ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // ???? IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // ??? filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // local Bluetooth adapter?? mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // ???? Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); // ????????ArrayAdapter?? if (pairedDevices.size() > 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) { pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { String noDevices = getResources().getText(R.string.none_paired).toString(); pairedDevicesArrayAdapter.add(noDevices); } }
From source file:org.strongswan.android.ui.VpnProfileDetailActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* the title is set when we load the profile, if any */ getSupportActionBar().setDisplayHomeAsUpEnabled(true); mDataSource = new VpnProfileDataSource(this); mDataSource.open();//from ww w . j ava2s. c om setContentView(R.layout.profile_detail_view); mName = (MultiAutoCompleteTextView) findViewById(R.id.name); mNameWrap = (TextInputLayoutHelper) findViewById(R.id.name_wrap); mGateway = (EditText) findViewById(R.id.gateway); mGatewayWrap = (TextInputLayoutHelper) findViewById(R.id.gateway_wrap); mSelectVpnType = (Spinner) findViewById(R.id.vpn_type); mTncNotice = (RelativeLayout) findViewById(R.id.tnc_notice); mUsernamePassword = (ViewGroup) findViewById(R.id.username_password_group); mUsername = (EditText) findViewById(R.id.username); mUsernameWrap = (TextInputLayoutHelper) findViewById(R.id.username_wrap); mPassword = (EditText) findViewById(R.id.password); mUserCertificate = (ViewGroup) findViewById(R.id.user_certificate_group); mSelectUserCert = (RelativeLayout) findViewById(R.id.select_user_certificate); mSelectUserId = (Spinner) findViewById(R.id.select_user_id); mCheckAuto = (CheckBox) findViewById(R.id.ca_auto); mSelectCert = (RelativeLayout) findViewById(R.id.select_certificate); mShowAdvanced = (CheckBox) findViewById(R.id.show_advanced); mAdvancedSettings = (ViewGroup) findViewById(R.id.advanced_settings); mRemoteId = (MultiAutoCompleteTextView) findViewById(R.id.remote_id); mRemoteIdWrap = (TextInputLayoutHelper) findViewById(R.id.remote_id_wrap); mMTU = (EditText) findViewById(R.id.mtu); mMTUWrap = (TextInputLayoutHelper) findViewById(R.id.mtu_wrap); mPort = (EditText) findViewById(R.id.port); mPortWrap = (TextInputLayoutHelper) findViewById(R.id.port_wrap); mNATKeepalive = (EditText) findViewById(R.id.nat_keepalive); mNATKeepaliveWrap = (TextInputLayoutHelper) findViewById(R.id.nat_keepalive_wrap); mCertReq = (Switch) findViewById(R.id.cert_req); mIncludedSubnets = (EditText) findViewById(R.id.included_subnets); mIncludedSubnetsWrap = (TextInputLayoutHelper) findViewById(R.id.included_subnets_wrap); mExcludedSubnets = (EditText) findViewById(R.id.excluded_subnets); mExcludedSubnetsWrap = (TextInputLayoutHelper) findViewById(R.id.excluded_subnets_wrap); mBlockIPv4 = (CheckBox) findViewById(R.id.split_tunneling_v4); mBlockIPv6 = (CheckBox) findViewById(R.id.split_tunneling_v6); mSelectSelectedAppsHandling = (Spinner) findViewById(R.id.apps_handling); mSelectApps = (RelativeLayout) findViewById(R.id.select_applications); mIkeProposal = (EditText) findViewById(R.id.ike_proposal); mIkeProposalWrap = (TextInputLayoutHelper) findViewById(R.id.ike_proposal_wrap); mEspProposal = (EditText) findViewById(R.id.esp_proposal); mEspProposalWrap = (TextInputLayoutHelper) findViewById(R.id.esp_proposal_wrap); /* make the link clickable */ ((TextView) findViewById(R.id.proposal_intro)).setMovementMethod(LinkMovementMethod.getInstance()); final SpaceTokenizer spaceTokenizer = new SpaceTokenizer(); mName.setTokenizer(spaceTokenizer); mRemoteId.setTokenizer(spaceTokenizer); final ArrayAdapter<String> completeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line); mName.setAdapter(completeAdapter); mRemoteId.setAdapter(completeAdapter); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { findViewById(R.id.apps).setVisibility(View.GONE); mSelectSelectedAppsHandling.setVisibility(View.GONE); mSelectApps.setVisibility(View.GONE); } mGateway.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) { completeAdapter.clear(); completeAdapter.add(mGateway.getText().toString()); if (TextUtils.isEmpty(mGateway.getText())) { mNameWrap.setHelperText(getString(R.string.profile_name_hint)); mRemoteIdWrap.setHelperText(getString(R.string.profile_remote_id_hint)); } else { mNameWrap.setHelperText( String.format(getString(R.string.profile_name_hint_gateway), mGateway.getText())); mRemoteIdWrap.setHelperText( String.format(getString(R.string.profile_remote_id_hint_gateway), mGateway.getText())); } } }); mSelectVpnType.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mVpnType = VpnType.values()[position]; updateCredentialView(); } @Override public void onNothingSelected(AdapterView<?> parent) { /* should not happen */ mVpnType = VpnType.IKEV2_EAP; updateCredentialView(); } }); ((TextView) mTncNotice.findViewById(android.R.id.text1)).setText(R.string.tnc_notice_title); ((TextView) mTncNotice.findViewById(android.R.id.text2)).setText(R.string.tnc_notice_subtitle); mTncNotice.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new TncNoticeDialog().show(VpnProfileDetailActivity.this.getSupportFragmentManager(), "TncNotice"); } }); mSelectUserCert.setOnClickListener(new SelectUserCertOnClickListener()); mSelectUserIdAdapter = new CertificateIdentitiesAdapter(this); mSelectUserId.setAdapter(mSelectUserIdAdapter); mSelectUserId.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (mUserCertEntry != null) { /* we don't store the subject DN as it is in the reverse order and the default anyway */ mSelectedUserId = position == 0 ? null : mSelectUserIdAdapter.getItem(position); } } @Override public void onNothingSelected(AdapterView<?> parent) { mSelectedUserId = null; } }); mCheckAuto.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateCertificateSelector(); } }); mSelectCert.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VpnProfileDetailActivity.this, TrustedCertificatesActivity.class); intent.setAction(TrustedCertificatesActivity.SELECT_CERTIFICATE); startActivityForResult(intent, SELECT_TRUSTED_CERTIFICATE); } }); mShowAdvanced.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateAdvancedSettings(); } }); mSelectSelectedAppsHandling.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mSelectedAppsHandling = SelectedAppsHandling.values()[position]; updateAppsSelector(); } @Override public void onNothingSelected(AdapterView<?> parent) { /* should not happen */ mSelectedAppsHandling = SelectedAppsHandling.SELECTED_APPS_DISABLE; updateAppsSelector(); } }); mSelectApps.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VpnProfileDetailActivity.this, SelectedApplicationsActivity.class); intent.putExtra(VpnProfileDataSource.KEY_SELECTED_APPS_LIST, new ArrayList<>(mSelectedApps)); startActivityForResult(intent, SELECT_APPLICATIONS); } }); mId = savedInstanceState == null ? null : savedInstanceState.getLong(VpnProfileDataSource.KEY_ID); if (mId == null) { Bundle extras = getIntent().getExtras(); mId = extras == null ? null : extras.getLong(VpnProfileDataSource.KEY_ID); } loadProfileData(savedInstanceState); updateCredentialView(); updateCertificateSelector(); updateAdvancedSettings(); updateAppsSelector(); }