Example usage for android.widget ArrayAdapter add

List of usage examples for android.widget ArrayAdapter add

Introduction

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

Prototype

public void add(@Nullable T object) 

Source Link

Document

Adds the specified object at the end of the array.

Usage

From source file:com.cssweb.android.base.DialogActivity.java

private void setAdapter(Spinner timeSpinner, String[] params) {
    ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
    timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Log.i("=================", ">>>>>>>>>>>>>>>>>>>>>>>>"+params);
    for (String param : params) {
        timeAdapter.add(param);
    }/*from   www.ja va 2  s.  com*/
    timeSpinner.setAdapter(timeAdapter);
}

From source file:mx.klozz.xperience.tweaker.fragments.CPUSettings.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.cpu_settings, root, false);

    mIsTegra3 = new File(TEGRA_MAX_FREQ_PATH).exists();
    mIsDynFreq = new File(DYN_MAX_FREQ_PATH).exists() && new File(DYN_MIN_FREQ_PATH).exists();

    lCurrentCPU = (LinearLayout) view.findViewById(R.id.lCurCPU);

    mCurFreq = (TextView) view.findViewById(R.id.current_speed);
    mCurFreq.setOnClickListener(new View.OnClickListener() {
        @Override//from  www.j av a  2s .  c  o m
        public void onClick(View view) {
            if (nCpus == 1)
                return;
            if (++MainActivity.CurrentCPU > (nCpus - 1))
                MainActivity.CurrentCPU = 0;
            setCPUval(MainActivity.CurrentCPU);
        }
    });

    mCurFreq.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            if (new File(CPU_ON_PATH.replace("cpu0", "cpu" + MainActivity.CurrentCPU)).exists()
                    && MainActivity.CurrentCPU > 0) {
                final StringBuilder sb = new StringBuilder();
                if (MainActivity.mCPUOn.get(MainActivity.CurrentCPU).equals("1")) {
                    sb.append("set_val \"").append(CPU_ON_PATH.replace("cpu0", "cpu" + MainActivity.CurrentCPU))
                            .append("\" \"0\";\n");
                    MainActivity.mCPUOn.set(MainActivity.CurrentCPU, "0");
                } else {
                    sb.append("set_val \"").append(CPU_ON_PATH.replace("cpu0", "cpu" + MainActivity.CurrentCPU))
                            .append("\" \"1\";\n");
                    MainActivity.mCPUOn.set(MainActivity.CurrentCPU, "1");
                }
                Helpers.shExec(sb, context, true);

                setCPUval(MainActivity.CurrentCPU);
            }

            return true;
        }
    });

    final int mFrequenciesNum = MainActivity.mAvailableFrequencies.length - 1;

    mMaxSlider = (SeekBar) view.findViewById(R.id.max_slider);
    mMaxSlider.setMax(mFrequenciesNum);
    mMaxSlider.setOnSeekBarChangeListener(this);
    mMaxSpeedText = (TextView) view.findViewById(R.id.max_speed_text);

    mMinSlider = (SeekBar) view.findViewById(R.id.min_slider);
    mMinSlider.setMax(mFrequenciesNum);
    mMinSlider.setOnSeekBarChangeListener(this);
    mMinSpeedText = (TextView) view.findViewById(R.id.min_speed_text);

    mGovernor = (Spinner) view.findViewById(R.id.pref_governor);
    String[] mAvailableGovernors = Helpers.LeerUnaLinea(GOVERNORS_LIST_PATH).split(" ");
    ArrayAdapter<CharSequence> governorAdapter = new ArrayAdapter<CharSequence>(context,
            android.R.layout.simple_spinner_item);
    governorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    for (String mAvailableGovernor : mAvailableGovernors) {
        governorAdapter.add(mAvailableGovernor.trim());
    }
    mGovernor.setAdapter(governorAdapter);
    mGovernor.setSelection(Arrays.asList(mAvailableGovernors)
            .indexOf(MainActivity.mCurrentGovernor.get(MainActivity.CurrentCPU)));
    mGovernor.post(new Runnable() {
        public void run() {
            mGovernor.setOnItemSelectedListener(new GovListener());
        }
    });

    mIo = (Spinner) view.findViewById(R.id.pref_io);
    String[] mAvailableIo = Helpers.getAvailableIOSchedulers(IO_SCHEDULER_PATH);

    ArrayAdapter<CharSequence> ioAdapter = new ArrayAdapter<CharSequence>(context,
            android.R.layout.simple_spinner_item);
    ioAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    for (String aMAvailableIo : mAvailableIo) {
        ioAdapter.add(aMAvailableIo);
    }
    mIo.setAdapter(ioAdapter);
    mIo.setSelection(
            Arrays.asList(mAvailableIo).indexOf(MainActivity.mCurrentIOSched.get(MainActivity.CurrentCPU)));
    mIo.post(new Runnable() {
        public void run() {
            mIo.setOnItemSelectedListener(new IOListener());
        }
    });

    Switch mSetOnBoot = (Switch) view.findViewById(R.id.cpu_sob);
    mSetOnBoot.setChecked(mPreferences.getBoolean(CPU_SOB, false));
    mSetOnBoot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton v, boolean checked) {
            final SharedPreferences.Editor editor = mPreferences.edit();
            editor.putBoolean(CPU_SOB, checked);
            if (checked) {
                for (int i = 0; i < nCpus; i++) {
                    editor.putString(PREF_MIN_CPU + i, MainActivity.mMinimunFreqSetting.get(i));
                    editor.putString(PREF_MAX_CPU + i, MainActivity.mMaximunFreqSetting.get(i));
                    editor.putString(PREF_GOV, MainActivity.mCurrentGovernor.get(i));
                    editor.putString(PREF_IO, MainActivity.mCurrentIOSched.get(i));
                    editor.putString("cpuon" + i, MainActivity.mCPUOn.get(i));
                }
            }
            editor.apply();
        }
    });

    //if(nCpus>1){
    LinearLayout vcpus[] = new LinearLayout[nCpus];
    for (int i = 0; i < nCpus; i++) {
        vcpus[i] = (LinearLayout) inflater.inflate(R.layout.cpu_view, root, false);
        vcpus[i].setId(i);
        TextView nc = (TextView) vcpus[i].findViewById(R.id.ncpu);
        nc.setText(Integer.toString(i + 1));
        if (i != MainActivity.CurrentCPU)
            nc.setText(" ");
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
                LinearLayout.LayoutParams.WRAP_CONTENT, (float) 0.1);
        lCurrentCPU.addView(vcpus[i], params);
    }
    //}

    setCPUval(MainActivity.CurrentCPU);

    return view;
}

From source file:org.mythdroid.fragments.RecEditFragment.java

private void setViews() {

    ((TextView) view.findViewById(R.id.title)).setText(prog.Title);
    ((TextView) view.findViewById(R.id.subtitle)).setText(prog.SubTitle);
    ((TextView) view.findViewById(R.id.channel)).setText(prog.Channel);
    ((TextView) view.findViewById(R.id.start)).setText(prog.startString());

    final Spinner typeSpinner = ((Spinner) view.findViewById(R.id.type));
    final ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(activity,
            android.R.layout.simple_spinner_item);
    typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    for (RecType type : RecType.values()) {
        if (type == RecType.DONT || type == RecType.OVERRIDE)
            continue;
        typeAdapter.add(type.msg());
    }//  ww w  . j  a v a 2s .  c o m

    typeSpinner.setAdapter(typeAdapter);
    typeSpinner.setSelection(type.ordinal());
    typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            type = RecType.values()[pos];
            if (type != prog.Type || prio != prog.RecPrio)
                modified = true;
            else
                modified = false;
            updateSaveEnabled();

            if (type == RecType.NOT) {
                prioSpinner.setEnabled(false);
                if (!inlineOpts) {
                    schedOptions.setEnabled(false);
                    groupOptions.setEnabled(false);
                } else {
                    resf.setEnabled(false);
                    regf.setEnabled(false);
                }
            } else {
                prioSpinner.setEnabled(true);
                if (!inlineOpts) {
                    schedOptions.setEnabled(true);
                    groupOptions.setEnabled(true);
                } else {
                    resf.setEnabled(true);
                    regf.setEnabled(true);
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }

    });

    prioSpinner = ((Spinner) view.findViewById(R.id.prio));

    final String[] prios = new String[21];
    for (int i = -10, j = 0; i < 11; i++)
        prios[j++] = String.valueOf(i);

    final ArrayAdapter<String> prioAdapter = new ArrayAdapter<String>(activity,
            android.R.layout.simple_spinner_item, prios);
    prioAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    prioSpinner.setAdapter(prioAdapter);
    prioSpinner.setSelection(prio + 10);
    prioSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            prio = pos - 10;
            if (type != prog.Type || prio != prog.RecPrio)
                modified = true;
            else
                modified = false;
            updateSaveEnabled();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }

    });
    prioSpinner.setEnabled(type == RecType.NOT ? false : true);

    if (!inlineOpts) {
        schedOptions = (Button) view.findViewById(R.id.schedOptions);
        schedOptions.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().beginTransaction()
                        .replace(containerId, new RecEditSchedFragment(), "RecEditSchedFragment" //$NON-NLS-1$
                ).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).addToBackStack(null)
                        .commitAllowingStateLoss();
            }
        });
        schedOptions.setEnabled(type == RecType.NOT ? false : true);

        groupOptions = (Button) view.findViewById(R.id.groupOptions);
        groupOptions.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().beginTransaction()
                        .replace(containerId, new RecEditGroupsFragment(), "RecEditGroupsFragment" //$NON-NLS-1$
                ).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).addToBackStack(null)
                        .commitAllowingStateLoss();
            }
        });
        groupOptions.setEnabled(type == RecType.NOT ? false : true);
    }

    save = (Button) view.findViewById(R.id.save);
    save.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            doSave();
        }
    });
    save.setEnabled(false);

}

From source file:br.com.bioscada.apps.biotracks.fragments.ExportDialogFragment.java

private void setupExportTypeOptions(FragmentActivity fragmentActivity) {
    boolean hideDrive = getArguments().getBoolean(KEY_HIDE_DRIVE);
    ExportType exportType = ExportType.valueOf(PreferencesUtils.getString(fragmentActivity,
            R.string.export_type_key, PreferencesUtils.EXPORT_TYPE_DEFAULT));

    if (hideDrive && exportType == ExportType.GOOGLE_DRIVE) {
        exportType = ExportType.GOOGLE_MAPS;
    }/*from   www  .j  ava 2  s  .  c o  m*/

    exportTypeOptionsList = new ArrayList<ExportDialogFragment.ExportType>();
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(),
            android.R.layout.simple_spinner_item);
    if (accounts.length > 0) {
        if (!hideDrive) {
            exportTypeOptionsList.add(ExportType.GOOGLE_DRIVE);
        }
        exportTypeOptionsList.add(ExportType.GOOGLE_MAPS);
        exportTypeOptionsList.add(ExportType.GOOGLE_FUSION_TABLES);
        exportTypeOptionsList.add(ExportType.GOOGLE_SPREADSHEET);
    }
    exportTypeOptionsList.add(ExportType.EXTERNAL_STORAGE);

    int selection = 0;
    for (int i = 0; i < exportTypeOptionsList.size(); i++) {
        ExportType type = exportTypeOptionsList.get(i);
        adapter.add(getString(type.resId));
        if (type == exportType) {
            selection = i;
        }
    }
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    exportTypeOptions.setAdapter(adapter);
    exportTypeOptions.setSelection(selection);
    exportTypeOptions.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ExportType type = exportTypeOptionsList.get(position);
            exportGoogleMapsOptions.setVisibility(type == ExportType.GOOGLE_MAPS ? View.VISIBLE : View.GONE);
            exportGoogleFusionTablesOptions
                    .setVisibility(type == ExportType.GOOGLE_FUSION_TABLES ? View.VISIBLE : View.GONE);
            exportExternalStorageOptions
                    .setVisibility(type == ExportType.EXTERNAL_STORAGE ? View.VISIBLE : View.GONE);
            accountSpinner.setVisibility(
                    accounts.length > 1 && type != ExportType.EXTERNAL_STORAGE ? View.VISIBLE : View.GONE);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Safely ignore
        }
    });
}

From source file:org.openremote.android.console.AppSettingsActivity.java

/**
 * Received custom server from AddServerActivity, add prefix "http://" before it.
 * Add the result in custom server list and set it as current server.
 * /*from  w ww  . java  2s .c om*/
 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
 */
@SuppressWarnings("unchecked")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        String result = data.getDataString();
        if (Constants.REQUEST_CODE == requestCode && !TextUtils.isEmpty(result)) {
            if (Constants.RESULT_CONTROLLER_URL == resultCode) {
                currentServer = "http://" + result;
                ArrayAdapter<String> customeListAdapter = (ArrayAdapter<String>) customListView.getAdapter();
                customeListAdapter.add(currentServer);
                customListView.setItemChecked(customeListAdapter.getCount() - 1, true);
                AppSettingsModel.setCurrentServer(AppSettingsActivity.this, currentServer);
                writeCustomServerToFile();
                requestPanelList();
                checkAuthentication();
                requestAccess();
            }
        }
    }
}

From source file:com.xperia64.timidityae.PlaylistFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (!gotPlaylists) {
        gotPlaylists = true;//from  w  ww . j  a  v a  2s.  c o  m
        getPlaylists(null);
    }
    getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int pos, long id) {
            if (!mode) {
                AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
                builderSingle.setIcon(R.drawable.ic_launcher);
                builderSingle.setTitle(getActivity().getResources()
                        .getString((pos == 0) ? R.string.plist_save2 : R.string.plist_mod));
                builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
                if (pos != 0) {
                    builderSingle.setNeutralButton(getResources().getString(R.string.plist_del),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AlertDialog.Builder builderDouble = new AlertDialog.Builder(getActivity())
                                            .setIcon(R.drawable.ic_launcher)
                                            .setTitle(String.format(
                                                    getActivity().getResources().getString(R.string.plist_del2),
                                                    fname.get(pos)));
                                    builderDouble.setPositiveButton(android.R.string.yes,
                                            new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    File f = new File(path.get(pos));
                                                    if (f.exists()) {
                                                        String[] x = null;
                                                        try {
                                                            new FileOutputStream(path.get(pos), true).close();
                                                        } catch (FileNotFoundException e) {
                                                            x = Globals.getDocFilePaths(getActivity(),
                                                                    f.getAbsolutePath());
                                                        } catch (IOException e) {
                                                            e.printStackTrace();
                                                        }

                                                        if (x != null) {
                                                            Globals.tryToDeleteFile(getActivity(),
                                                                    path.get(pos));
                                                        } else {
                                                            f.delete();
                                                        }
                                                    }
                                                    getPlaylists(null);
                                                    dialog.dismiss();
                                                }
                                            });
                                    builderDouble.setNegativeButton(android.R.string.no,
                                            new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            });
                                    builderDouble.show();
                                }
                            });
                    builderSingle.setPositiveButton(getResources().getString(R.string.plist_ren),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());

                                    alert.setTitle(String.format(getResources().getString(R.string.plist_ren2),
                                            fname.get(pos)));

                                    final EditText input = new EditText(getActivity());
                                    alert.setView(input);

                                    alert.setPositiveButton(android.R.string.ok,
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int whichButton) {
                                                    String value = input.getText().toString();
                                                    File f = new File(path.get(pos));
                                                    File f2 = new File(path.get(pos).substring(0,
                                                            path.get(pos).lastIndexOf('/') + 1) + value
                                                            + ".tpl");
                                                    if (f.exists()) {
                                                        if (f2.exists()) {
                                                            Toast.makeText(getActivity(),
                                                                    getResources().getString(R.string.plist_ex),
                                                                    Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            String[] x = null;
                                                            try {
                                                                new FileOutputStream(f.getAbsolutePath(), true)
                                                                        .close();
                                                            } catch (FileNotFoundException e) {
                                                                x = Globals.getDocFilePaths(getActivity(),
                                                                        f.getAbsolutePath());
                                                            } catch (IOException e) {
                                                                e.printStackTrace();
                                                            }

                                                            if (x != null) {
                                                                Globals.renameDocumentFile(getActivity(),
                                                                        f.getAbsolutePath(),
                                                                        f2.getAbsolutePath()
                                                                                .substring(f2.getAbsolutePath()
                                                                                        .indexOf(x[1])
                                                                                        + x[1].length()));
                                                            } else {
                                                                f.renameTo(f2);
                                                            }

                                                        }
                                                    } else
                                                        Toast.makeText(getActivity(),
                                                                getResources().getString(R.string.plist_pnf),
                                                                Toast.LENGTH_SHORT).show();
                                                    getPlaylists(null);
                                                    dialog.dismiss();
                                                }

                                            });

                                    alert.setNegativeButton(android.R.string.cancel,
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int whichButton) {
                                                    dialog.dismiss();
                                                }
                                            });

                                    alert.show();
                                }
                            });
                } else {

                    final EditText input2 = new EditText(getActivity());
                    builderSingle.setView(input2);
                    builderSingle.setPositiveButton(getResources().getString(R.string.plist_save),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (input2.getText() != null) {
                                        if (!TextUtils.isEmpty(input2.getText().toString())) {
                                            tmpName = playlistDir + "/" + input2.getText().toString() + ".tpl";
                                            vola = currPlist;
                                            write();
                                        }
                                    }
                                }
                            });
                }
                builderSingle.show();
                return true;
            } else if (!plistName.equals("CURRENT")) {
                AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());

                builderSingle.setIcon(R.drawable.ic_launcher);
                builderSingle.setTitle(getResources().getString(R.string.plist_modit));
                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                        android.R.layout.select_dialog_item);
                arrayAdapter.add(getResources().getString(R.string.plist_ds));
                arrayAdapter.add(getResources().getString(R.string.plist_addcsh));
                arrayAdapter.add(getResources().getString(R.string.plist_addsh));
                arrayAdapter.add(getResources().getString(R.string.plist_addfh));
                arrayAdapter.add(getResources().getString(R.string.plist_addfth));
                builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        vola = parsePlist(tmpName = plistName);
                        loki = pos;
                        switch (which) {
                        case 0:
                            setItem(null, -1);
                            write();
                            break;
                        case 1:
                            if (((TimidityActivity) getActivity()).currSongName != null) {
                                setItem(((TimidityActivity) getActivity()).currSongName, 0);
                                write();
                            }
                            break;
                        case 2:
                            new FileBrowserDialog().create(0,
                                    (Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles),
                                    PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(),
                                    false, Globals.defaultFolder,
                                    getActivity().getResources().getString(R.string.fb_add));
                            break;
                        case 3:
                            new FileBrowserDialog().create(1, null, PlaylistFragment.this, getActivity(),
                                    getActivity().getLayoutInflater(), false, Globals.defaultFolder,
                                    getActivity().getResources().getString(R.string.fb_add));
                            break;
                        case 4:
                            new FileBrowserDialog().create(2, null, PlaylistFragment.this, getActivity(),
                                    getActivity().getLayoutInflater(), false, Globals.defaultFolder,
                                    getActivity().getResources().getString(R.string.fb_add));
                            break;
                        }
                    }
                });
                builderSingle.show();
                return true;
            }
            return true;
        }
    });
}

From source file:org.akvo.caddisfly.sensor.colorimetry.liquid.CalibrateListActivity.java

/**
 * Load the calibrated swatches from the calibration text file
 *
 * @param callback callback to be initiated once the loading is complete
 *///from www.  jav a  2 s.c  o m
private void loadCalibration(@NonNull final Context context, @NonNull final Handler.Callback callback) {
    try {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.loadCalibration);

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(context, R.layout.row_text);

        final File path = FileHelper.getFilesDir(FileHelper.FileType.CALIBRATION,
                CaddisflyApp.getApp().getCurrentTestInfo().getId());

        File[] listFilesTemp = null;
        if (path.exists() && path.isDirectory()) {
            listFilesTemp = path.listFiles();
        }

        final File[] listFiles = listFilesTemp;
        if (listFiles != null && listFiles.length > 0) {
            Arrays.sort(listFiles);

            for (File listFile : listFiles) {
                arrayAdapter.add(listFile.getName());
            }

            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(@NonNull DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String fileName = listFiles[which].getName();
                    try {
                        final List<Swatch> swatchList = SwatchHelper.loadCalibrationFromFile(getBaseContext(),
                                fileName);

                        (new AsyncTask<Void, Void, Void>() {
                            @Nullable
                            @Override
                            protected Void doInBackground(Void... params) {
                                SwatchHelper.saveCalibratedSwatches(context, swatchList);
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void result) {
                                super.onPostExecute(result);
                                callback.handleMessage(null);
                            }
                        }).execute();

                    } catch (Exception ex) {
                        AlertUtil.showError(context, R.string.error, getString(R.string.errorLoadingFile), null,
                                R.string.ok, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(@NonNull DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }, null, null);
                    }
                }

            });

            final AlertDialog alertDialog = builder.create();
            alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialogInterface) {
                    final ListView listView = alertDialog.getListView();
                    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                        @Override
                        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                            final int position = i;

                            AlertUtil.askQuestion(context, R.string.delete, R.string.deleteConfirm,
                                    R.string.delete, R.string.cancel, true,
                                    new DialogInterface.OnClickListener() {
                                        @SuppressWarnings("unchecked")
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            String fileName = listFiles[position].getName();
                                            FileUtil.deleteFile(path, fileName);
                                            ArrayAdapter listAdapter = (ArrayAdapter) listView.getAdapter();
                                            listAdapter.remove(listAdapter.getItem(position));
                                            alertDialog.dismiss();
                                            Toast.makeText(context, R.string.deleted, Toast.LENGTH_SHORT)
                                                    .show();
                                        }
                                    }, null);
                            return true;
                        }
                    });

                }
            });
            alertDialog.show();
        } else {
            AlertUtil.showMessage(context, R.string.notFound, R.string.loadFilesNotAvailable);
        }
    } catch (ActivityNotFoundException ignored) {
    }

    callback.handleMessage(null);
}

From source file:com.nextgis.maplibui.formcontrol.DoubleCombobox.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {
    mSubCombobox = new Spinner(getContext());
    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_LEVEL1_KEY);
    mSubFieldName = attributes.getString(JSON_FIELD_LEVEL2_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));

    String lastValue = null;/*from   w  ww  . ja  v  a 2 s.  c  o m*/
    String subLastValue = null;
    if (ControlHelper.hasKey(savedState, mFieldName) && ControlHelper.hasKey(savedState, mSubFieldName)) {
        lastValue = savedState.getString(ControlHelper.getSavedStateKey(mFieldName));
        subLastValue = savedState.getString(ControlHelper.getSavedStateKey(mSubFieldName));
    } else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);
        int subColumn = featureCursor.getColumnIndex(mSubFieldName);
        if (column >= 0)
            lastValue = featureCursor.getString(column);
        if (subColumn >= 0)
            subLastValue = featureCursor.getString(subColumn);
    } else if (mIsShowLast) {
        lastValue = preferences.getString(mFieldName, null);
        subLastValue = preferences.getString(mSubFieldName, null);
    }

    JSONArray values = attributes.optJSONArray(JSON_VALUES_KEY);
    int defaultPosition = 0;
    int lastValuePosition = -1;
    int subLastValuePosition = -1;
    mAliasValueMap = new HashMap<>();
    mSubAliasValueMaps = new HashMap<>();
    mAliasSubListMap = new HashMap<>();

    final ArrayAdapter<String> comboboxAdapter = new ArrayAdapter<>(getContext(),
            R.layout.formtemplate_double_spinner);
    setAdapter(comboboxAdapter);

    if (values != null) {
        for (int j = 0; j < values.length(); j++) {
            JSONObject keyValue = values.getJSONObject(j);
            String value = keyValue.getString(JSON_VALUE_NAME_KEY);
            String valueAlias = keyValue.getString(JSON_VALUE_ALIAS_KEY);

            Map<String, String> subAliasValueMap = new HashMap<>();
            AliasList subAliasList = new AliasList();

            mAliasValueMap.put(valueAlias, value);
            mSubAliasValueMaps.put(valueAlias, subAliasValueMap);
            mAliasSubListMap.put(valueAlias, subAliasList);
            comboboxAdapter.add(valueAlias);

            if (keyValue.has(JSON_DEFAULT_KEY) && keyValue.getBoolean(JSON_DEFAULT_KEY))
                defaultPosition = j;

            if (null != lastValue && lastValue.equals(value)) // if modify data
                lastValuePosition = j;

            JSONArray subValues = keyValue.getJSONArray(JSON_VALUES_KEY);
            for (int k = 0; k < subValues.length(); k++) {
                JSONObject subKeyValue = subValues.getJSONObject(k);
                String subValue = subKeyValue.getString(JSON_VALUE_NAME_KEY);
                String subValueAlias = subKeyValue.getString(JSON_VALUE_ALIAS_KEY);

                subAliasValueMap.put(subValueAlias, subValue);
                subAliasList.aliasList.add(subValueAlias);

                if (subKeyValue.has(JSON_DEFAULT_KEY) && subKeyValue.getBoolean(JSON_DEFAULT_KEY))
                    subAliasList.defaultPosition = k;

                if (null != subLastValue && subLastValue.equals(subValue)) { // if modify data
                    lastValuePosition = j;
                    subLastValuePosition = k;
                }
            }
        }
    }

    setSelection(lastValuePosition >= 0 ? lastValuePosition : defaultPosition);
    final int subLastValuePositionFinal = subLastValuePosition;

    // The drop down view
    comboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    float minHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14,
            getResources().getDisplayMetrics());
    setPadding(0, (int) minHeight, 0, (int) minHeight);
    mSubCombobox.setPadding(0, (int) minHeight, 0, (int) minHeight);

    setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedValueAlias = comboboxAdapter.getItem(position);
            AliasList subAliasList = mAliasSubListMap.get(selectedValueAlias);

            ArrayAdapter<String> subComboboxAdapter = new ArrayAdapter<>(view.getContext(),
                    R.layout.formtemplate_double_spinner, subAliasList.aliasList);
            subComboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            mSubCombobox.setAdapter(subComboboxAdapter);
            mSubCombobox.setSelection(mFirstShow && subLastValuePositionFinal >= 0 ? subLastValuePositionFinal
                    : subAliasList.defaultPosition);

            if (mFirstShow) {
                mFirstShow = false;
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
}

From source file:com.gimranov.zandy.app.AttachmentActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    final String attachmentKey = b.getString("attachmentKey");
    final String itemKey = b.getString("itemKey");
    final String content = b.getString("content");
    final String mode = b.getString("mode");
    AlertDialog dialog;/*  www.  j a  v  a 2  s.  c om*/
    switch (id) {
    case DIALOG_CONFIRM_NAVIGATE:
        dialog = new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.view_online_warning))
                .setPositiveButton(getResources().getString(R.string.view),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // The behavior for invalid URIs might be nasty, but
                                // we'll cross that bridge if we come to it.
                                try {
                                    Uri uri = Uri.parse(content);
                                    startActivity(new Intent(Intent.ACTION_VIEW).setData(uri));
                                } catch (ActivityNotFoundException e) {
                                    // There can be exceptions here; not sure what would prompt us to have
                                    // URIs that the browser can't load, but it apparently happens.
                                    Toast.makeText(getApplicationContext(), getResources()
                                            .getString(R.string.attachment_intent_failed_for_uri, content),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                .setNeutralButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        })
                .create();
        return dialog;
    case DIALOG_CONFIRM_DELETE:
        dialog = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.attachment_delete_confirm))
                .setPositiveButton(getResources().getString(R.string.menu_delete),
                        new DialogInterface.OnClickListener() {
                            @SuppressWarnings("unchecked")
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Attachment a = Attachment.load(attachmentKey, db);
                                a.delete(db);
                                ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
                                la.clear();
                                for (Attachment at : Attachment.forItem(Item.load(itemKey, db), db)) {
                                    la.add(at);
                                }
                            }
                        })
                .setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        })
                .create();
        return dialog;
    case DIALOG_NOTE:
        final EditText input = new EditText(this);
        input.setText(content, BufferType.EDITABLE);

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.note)).setView(input).setPositiveButton(
                        getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @SuppressWarnings("unchecked")
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Editable value = input.getText();
                                String fixed = value.toString().replaceAll("\n\n", "\n<br>");
                                if (mode != null && mode.equals("new")) {
                                    Log.d(TAG, "Attachment created with parent key: " + itemKey);
                                    Attachment att = new Attachment(getBaseContext(), "note", itemKey);
                                    att.setNoteText(fixed);
                                    att.dirty = APIRequest.API_NEW;
                                    att.save(db);
                                } else {
                                    Attachment att = Attachment.load(attachmentKey, db);
                                    att.setNoteText(fixed);
                                    att.dirty = APIRequest.API_DIRTY;
                                    att.save(db);
                                }
                                ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
                                la.clear();
                                for (Attachment a : Attachment.forItem(Item.load(itemKey, db), db)) {
                                    la.add(a);
                                }
                                la.notifyDataSetChanged();
                            }
                        })
                .setNeutralButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                // do nothing
                            }
                        });
        // We only want the delete option when this isn't a new note
        if (mode == null || !"new".equals(mode)) {
            builder = builder.setNegativeButton(getResources().getString(R.string.menu_delete),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            Bundle b = new Bundle();
                            b.putString("attachmentKey", attachmentKey);
                            b.putString("itemKey", itemKey);
                            removeDialog(DIALOG_CONFIRM_DELETE);
                            AttachmentActivity.this.b = b;
                            showDialog(DIALOG_CONFIRM_DELETE);
                        }
                    });
        }
        dialog = builder.create();
        return dialog;
    case DIALOG_FILE_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog
                .setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
        mProgressDialog.setIndeterminate(true);
        return mProgressDialog;
    default:
        Log.e(TAG, "Invalid dialog requested");
        return null;
    }
}

From source file:com.silentcircle.contacts.interactions.ImportExportDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Wrap our context to inflate list items using the correct theme
    final Resources res = getActivity().getResources();
    final LayoutInflater dialogInflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final boolean contactsAreAvailable = getArguments().getBoolean(ARG_CONTACTS_ARE_AVAILABLE);

    // Adapter that shows a list of string resources
    final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getActivity(),
            R.layout.select_dialog_item) {
        @Override//  w  w w .  jav  a2 s .  com
        public View getView(int position, View convertView, ViewGroup parent) {
            final TextView result = (TextView) (convertView != null ? convertView
                    : dialogInflater.inflate(R.layout.select_dialog_item, parent, false));

            final int resId = getItem(position);
            result.setText(resId);
            return result;
        }
    };

    //        if (TelephonyManager.getDefault().hasIccCard()
    //                && res.getBoolean(R.bool.config_allow_sim_import)) {
    //            adapter.add(R.string.import_from_sim);
    //        }
    if (res.getBoolean(R.bool.config_allow_import_from_sdcard)) {
        adapter.add(R.string.import_from_sdcard);
    }
    if (res.getBoolean(R.bool.config_allow_export_to_sdcard)) {
        if (contactsAreAvailable) {
            adapter.add(R.string.export_to_sdcard);
        }
    }
    if (res.getBoolean(R.bool.config_allow_share_visible_contacts)) {
        if (contactsAreAvailable) {
            adapter.add(R.string.share_visible_contacts);
        }
    }

    final DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            boolean dismissDialog;
            final int resId = adapter.getItem(which);
            switch (resId) {
            //                    case R.string.import_from_sim:
            case R.string.import_from_sdcard: {
                dismissDialog = handleImportRequest(resId);
                break;
            }
            case R.string.export_to_sdcard: {
                dismissDialog = true;
                Intent exportIntent = new Intent(getActivity(), ExportVCardActivity.class);
                getActivity().startActivity(exportIntent);
                break;
            }
            //                    case R.string.share_visible_contacts: {
            //                        dismissDialog = true;
            //                        Log.e(TAG, "Share contects not yet available");
            //                        doShareVisibleContacts();
            //                        break;
            //                    }
            default: {
                dismissDialog = true;
                Log.e(TAG, "Unexpected resource: " + getActivity().getResources().getResourceEntryName(resId));
            }
            }
            if (dismissDialog) {
                dialog.dismiss();
            }
        }
    };
    return new AlertDialog.Builder(getActivity())
            .setTitle(contactsAreAvailable ? R.string.dialog_import_export : R.string.dialog_import)
            .setSingleChoiceItems(adapter, -1, clickListener).create();
}