Example usage for android.widget ArrayAdapter getPosition

List of usage examples for android.widget ArrayAdapter getPosition

Introduction

In this page you can find the example usage for android.widget ArrayAdapter getPosition.

Prototype

public int getPosition(@Nullable T item) 

Source Link

Document

Returns the position of the specified item in the array.

Usage

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  w  w w  . j av a2  s  . c om*/
        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);
}