Example usage for android.widget ArrayAdapter getItem

List of usage examples for android.widget ArrayAdapter getItem

Introduction

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

Prototype

@Override
    public @Nullable T getItem(int position) 

Source Link

Usage

From source file:com.andrew.apollo.utils.MusicUtils.java

private static long[] getSongListForAdapter(final ArrayAdapter<Song> adapter) {
    if (adapter == null) {
        return sEmptyList;
    }//from w  w  w.  j av  a  2s.  co m

    int count = adapter.getCount() - (adapter.getViewTypeCount() > 1 ? 1 : 0);
    List<Long> songList = new LinkedList<>();
    for (int i = 0; i < count; i++) {
        try {
            long songId = adapter.getItem(i).mSongId;
            songList.add(songId);
        } catch (Throwable ignored) {
            // possible array out of bounds on adapter.getItem(i)
        }
    }

    if (songList.size() == 0) {
        return sEmptyList;
    }

    // until Java supports primitive types as generics, we'll live with this double copy. O(2n)
    Long[] list = new Long[songList.size()];
    long[] result = ArrayUtils.toPrimitive(songList.toArray(list));
    songList.clear();
    return result;
}

From source file:com.manning.androidhacks.hack017.CreateAccountAdapter.java

private void populateSecondForm(LinearLayout formLayout) {
    formLayout.addView(createTitle(mContext.getString(R.string.account_create_password_title)));
    EditText passwordEditText = createEditText(mContext.getString(R.string.account_create_password_hint),
            InputType.TYPE_CLASS_TEXT, EditorInfo.IME_ACTION_DONE, false, PASSWORD_KEY);
    passwordEditText.setTransformationMethod(new PasswordTransformationMethod());

    formLayout.addView(passwordEditText);
    formLayout.addView(createErrorView(PASSWORD_KEY));

    formLayout.addView(createTitle(mContext.getString(R.string.account_create_gender_title)));
    Spinner spinner = new Spinner(mContext);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);//from  ww  w . j av  a 2 s  . co m
    params.bottomMargin = 17;
    spinner.setLayoutParams(params);

    final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(mContext, R.array.sexes_array,
            android.R.layout.simple_spinner_item);
    spinner.setAdapter(adapter);
    spinner.setPrompt(mContext.getString(R.string.account_create_sex_spinner_prompt));
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

            mFormData.put(GENDER_KEY, adapter.getItem(pos).toString());
        }

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

    if (mFormData.get(GENDER_KEY) != null) {
        spinner.setSelection(adapter.getPosition(mFormData.get(GENDER_KEY)));
    }

    formLayout.addView(spinner);

}

From source file:de.domjos.schooltools.activities.LearningCardOverviewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.learning_card_overview_activity);
    this.initControls();

    this.cmdLearningCardQueryStart.setOnClickListener(new View.OnClickListener() {
        @Override/*w  w  w  .  jav  a 2s. com*/
        public void onClick(View v) {
            final LearningCardQueryTraining learningCardQueryTraining = new LearningCardQueryTraining();
            if (cmdLearningCardQueryStart.getText().equals(getString(R.string.learningCard_query))) {
                final Dialog dialog = new Dialog(LearningCardOverviewActivity.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.learning_card_dialog);
                dialog.setCancelable(true);

                final Spinner spLearningCardQuery = dialog.findViewById(R.id.spLearningCardQueries);
                final ArrayAdapter<LearningCardQuery> learningCardQueries = new ArrayAdapter<>(
                        getApplicationContext(), android.R.layout.simple_spinner_item,
                        MainActivity.globals.getSqLite().getLearningCardQueries(""));
                spLearningCardQuery.setAdapter(learningCardQueries);
                learningCardQueries.notifyDataSetChanged();

                final Button btnStartSop = dialog.findViewById(R.id.cmdStart);
                btnStartSop.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        learningCardQueryTraining.setLearningCardQuery(
                                learningCardQueries.getItem(spLearningCardQuery.getSelectedItemPosition()));
                        learningCardQueryTraining.setID(MainActivity.globals.getSqLite()
                                .insertOrUpdateLearningCardQueryTraining(learningCardQueryTraining));
                        cmdLearningCardQueryStart.setText(getString(R.string.learningCard_query_end));
                        fragmentAdapter.setQuery(learningCardQueryTraining);
                        viewPager.setAdapter(fragmentAdapter);
                        dialog.dismiss();
                    }
                });
                dialog.show();
            } else {
                int wrongCards = 0, rightCards = 0, firstTry = 0, secondTry = 0, thirdTry = 0;
                LearningCardQueryTraining reloadedTraining = MainActivity.globals.getSqLite()
                        .getLearningCardQueryTraining("ID=" + learningCardQueryTraining.getID()).get(0);
                for (LearningCardQueryResult result : reloadedTraining.getResults()) {
                    if (result.isResult1() || result.isResult2() || result.isResult3()) {
                        rightCards++;
                        if (result.isResult1()) {
                            firstTry++;
                        } else if (result.isResult2()) {
                            secondTry++;
                        } else {
                            thirdTry++;
                        }
                    } else {
                        wrongCards++;
                    }
                }
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        LearningCardOverviewActivity.this);
                alertDialogBuilder.setTitle(R.string.learningCard_result);
                String content = String.format("%s %s%n%s %s%n%s %s%n%s %s%n%s %s%n",
                        getString(R.string.learningCard_result_right), rightCards,
                        getString(R.string.learningCard_result_wrong), wrongCards,
                        getString(R.string.learningCard_result_firstTry), firstTry,
                        getString(R.string.learningCard_result_secondTry), secondTry,
                        getString(R.string.learningCard_result_thirdTry), thirdTry);
                alertDialogBuilder.setMessage(content);
                alertDialogBuilder.create().show();

                cmdLearningCardQueryStart.setText(getString(R.string.learningCard_query));
                fragmentAdapter.setQuery(null);
                viewPager.setAdapter(fragmentAdapter);
            }
        }
    });
}

From source file:tw.com.geminihsu.app01.fragment.Fragment_Account.java

private void selectIdentity() {
    getDriverIdentity();//from   w  w  w  .j  a va 2  s .  c  o m

    if (!driver_identity.isEmpty()) {
        AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());

        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.select_dialog_item);

        for (String type : driver_identity.keySet()) {
            arrayAdapter.add(type);
        }

        builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);

                progressDialog_loading = ProgressDialog.show(getActivity(), "", "Loading. Please wait...",
                        true);
                change_driver = driver_mapping_value.get(strName);
                changeDriverType = driver_identity.get(strName);
                attributes.put("select driver", strName);
                sendDataRequest.driverWorkIdentity(change_driver);

            }
        });
        builderSingle.show();
    }
}

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

/** Called when the activity is first created. */
@Override/*from   ww w  . j  a v  a 2s .c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    tmpFiles = new ArrayList<File>();

    db = new Database(this);

    /* Get the incoming data from the calling activity */
    final String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey");
    Item item = Item.load(itemKey, db);
    this.item = item;

    if (item == null) {
        Log.e(TAG, "AttachmentActivity started without itemKey; finishing.");
        finish();
        return;
    }

    this.setTitle(getResources().getString(R.string.attachments_for_item, item.getTitle()));

    ArrayList<Attachment> rows = Attachment.forItem(item, db);

    /* 
     * We use the standard ArrayAdapter, passing in our data as a Attachment.
     * Since it's no longer a simple TextView, we need to override getView, but
     * we can do that anonymously.
     */
    setListAdapter(new ArrayAdapter<Attachment>(this, R.layout.list_attach, rows) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row;

            // We are reusing views, but we need to initialize it if null
            if (null == convertView) {
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.list_attach, null);
            } else {
                row = convertView;
            }

            ImageView tvType = (ImageView) row.findViewById(R.id.attachment_type);
            TextView tvSummary = (TextView) row.findViewById(R.id.attachment_summary);

            Attachment att = getItem(position);
            Log.d(TAG, "Have an attachment: " + att.title + " fn:" + att.filename + " status:" + att.status);

            tvType.setImageResource(Item.resourceForType(att.getType()));

            try {
                Log.d(TAG, att.content.toString(4));
            } catch (JSONException e) {
                Log.e(TAG, "JSON parse exception when reading attachment content", e);
            }

            if (att.getType().equals("note")) {
                String note = att.content.optString("note", "");
                if (note.length() > 40) {
                    note = note.substring(0, 40);
                }
                tvSummary.setText(note);
            } else {
                StringBuffer status = new StringBuffer(getResources().getString(R.string.status));
                if (att.status == Attachment.AVAILABLE)
                    status.append(getResources().getString(R.string.attachment_zfs_available));
                else if (att.status == Attachment.LOCAL)
                    status.append(getResources().getString(R.string.attachment_zfs_local));
                else
                    status.append(getResources().getString(R.string.attachment_unknown));
                tvSummary.setText(att.title + " " + status.toString());
            }
            return row;
        }
    });

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setOnItemLongClickListener(new OnItemLongClickListener() {
        // Warning here because Eclipse can't tell whether my ArrayAdapter is
        // being used with the correct parametrization.
        @SuppressWarnings("unchecked")
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            // If we have a click on an entry, show its note
            ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
            Attachment row = adapter.getItem(position);

            if (row.content.has("note")) {
                Log.d(TAG, "Trying to start note view activity for: " + row.key);
                Intent i = new Intent(getBaseContext(), NoteActivity.class);
                i.putExtra("com.gimranov.zandy.app.attKey", row.key);//row.content.optString("note", ""));
                startActivity(i);
            }
            return true;
        }
    });
    lv.setOnItemClickListener(new OnItemClickListener() {
        // Warning here because Eclipse can't tell whether my ArrayAdapter is
        // being used with the correct parametrization.
        @SuppressWarnings("unchecked")
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // If we have a long click on an entry, do something...
            ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
            Attachment row = adapter.getItem(position);
            String url = (row.url != null && !row.url.equals("")) ? row.url : row.content.optString("url");

            if (!row.getType().equals("note")) {
                Bundle b = new Bundle();
                b.putString("title", row.title);
                b.putString("attachmentKey", row.key);
                b.putString("content", url);
                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                int linkMode = row.content.optInt("linkMode", Attachment.MODE_IMPORTED_URL);

                if (settings.getBoolean("webdav_enabled", false))
                    b.putString("mode", "webdav");
                else
                    b.putString("mode", "zfs");

                if (linkMode == Attachment.MODE_IMPORTED_FILE || linkMode == Attachment.MODE_IMPORTED_URL) {
                    loadFileAttachment(b);
                } else {
                    AttachmentActivity.this.b = b;
                    showDialog(DIALOG_CONFIRM_NAVIGATE);
                }
            }

            if (row.getType().equals("note")) {
                Bundle b = new Bundle();
                b.putString("attachmentKey", row.key);
                b.putString("itemKey", itemKey);
                b.putString("content", row.content.optString("note", ""));
                removeDialog(DIALOG_NOTE);
                AttachmentActivity.this.b = b;
                showDialog(DIALOG_NOTE);
            }
            return;
        }
    });
}

From source file:de.uni_koblenz_landau.apow.EncounterDetailFragment.java

/**
 * Called by EncounterDetailTask, when loading is finished.
 *///from   w  ww  . j  av a 2 s .  co  m
@Override
public void onEncounterFetched(Encounter encounter, List<ListViewItem> types) {
    mEncounterDetailTask = null;

    // If result is not empty, update UI, else show error message.
    if (types != null) {
        mTypes = types;
        ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_spinner_item, types);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mTypesView.setAdapter(adapter);

        if (encounter != null) {
            mEncounter = encounter;
            mDateView.setText(Helper.dateToLocaleString(mEncounter.getEncounterDatetime(), getActivity()));
            mTimeView.setText(Helper.dateToLocaleTimeString(mEncounter.getEncounterDatetime(), getActivity()));

            int position = -1;
            for (int i = 0; i < adapter.getCount(); i++) {
                if (adapter.getItem(i).getId() == mEncounter.getEncounterType().getEncounterTypeId()) {
                    position = i;
                    break;
                }
            }
            mTypesView.setSelection(position);
        } else {
            mEncounter = new Encounter();
            mDateView.setText(Helper.dateToLocaleString(new Date(), getActivity()));
            mTimeView.setText(Helper.dateToLocaleTimeString(new Date(), getActivity()));
        }
    } else {
        Toast.makeText(getActivity(), R.string.error_database, Toast.LENGTH_SHORT).show();
    }
}

From source file:com.example.linhdq.test.documents.creation.visualisation.LayoutQuestionDialog.java

@NonNull
@Override/*from w ww. j  av a2  s .  c o  m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Context context = getContext();
    mLayout = null;
    Pair<String, String> language = PreferencesUtils.getOCRLanguage(context);

    final InstallStatus installStatus = OcrLanguageDataStore.isLanguageInstalled(language.first, context);

    if (!installStatus.isInstalled()) {
        final String defaultLanguage = context.getString(R.string.default_ocr_language);
        final String defaultLanguageDisplay = context.getString(R.string.default_ocr_display_language);
        language = Pair.create(defaultLanguage, defaultLanguageDisplay);
    }
    mLanguage = language.first;

    AlertDialog.Builder builder;

    builder = new AlertDialog.Builder(context);
    builder.setCancelable(false);
    View layout = View.inflate(context, R.layout.dialog_layout_question, null);
    builder.setView(layout);

    final ViewFlipper titleViewFlipper = (ViewFlipper) layout.findViewById(R.id.layout_title);
    final ImageView columnLayout = (ImageView) layout.findViewById(R.id.column_layout);
    final ImageView pageLayout = (ImageView) layout.findViewById(R.id.page_layout);
    final ImageSwitcher fairy = (ImageSwitcher) layout.findViewById(R.id.fairy_layout);
    fairy.setFactory(new ViewSwitcher.ViewFactory() {
        public View makeView() {
            return new ImageView(context);
        }
    });
    fairy.setImageResource(R.drawable.fairy_looks_center);
    fairy.setInAnimation(context, android.R.anim.fade_in);
    fairy.setOutAnimation(context, android.R.anim.fade_out);

    final int color = context.getResources().getColor(R.color.progress_color);

    final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.LIGHTEN);

    columnLayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mLayout != LayoutKind.COMPLEX) {
                fairy.setImageResource(R.drawable.fairy_looks_left);
                titleViewFlipper.setDisplayedChild(2);
                columnLayout.setColorFilter(colorFilter);
                pageLayout.clearColorFilter();
                mLayout = LayoutKind.COMPLEX;
            }

        }
    });
    pageLayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mLayout != LayoutKind.SIMPLE) {
                mLayout = LayoutKind.SIMPLE;
                titleViewFlipper.setDisplayedChild(1);
                fairy.setImageResource(R.drawable.fairy_looks_right);
                pageLayout.setColorFilter(colorFilter);
                columnLayout.clearColorFilter();
            }
        }
    });

    final Spinner langButton = (Spinner) layout.findViewById(R.id.button_language);
    List<OcrLanguage> installedLanguages = OcrLanguageDataStore.getInstalledOCRLanguages(context);

    // actual values uses by tesseract
    final ArrayAdapter<OcrLanguage> adapter = new ArrayAdapter<>(context, R.layout.item_spinner_language,
            installedLanguages);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    langButton.setAdapter(adapter);
    for (int i = 0; i < installedLanguages.size(); i++) {
        OcrLanguage lang = installedLanguages.get(i);
        if (lang.getValue().equals(language.first)) {
            langButton.setSelection(i, false);
            break;
        }
    }
    langButton.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            final OcrLanguage item = adapter.getItem(position);
            mLanguage = item.getValue();
            PreferencesUtils.saveOCRLanguage(context, item);
        }

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

        }
    });

    builder.setPositiveButton(R.string.start_scan, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int id) {
            if (mLayout == null) {
                mLayout = LayoutKind.SIMPLE;
            }
            LayoutChoseListener listener = (LayoutChoseListener) getActivity();
            listener.onLayoutChosen(mLayout, mLanguage);
            dialog.dismiss();
        }
    });

    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int id) {
            getActivity().finish();
            dialog.dismiss();
        }
    });

    return builder.create();

}

From source file:com.renard.ocr.documents.creation.visualisation.LayoutQuestionDialog.java

@NonNull
@Override//w  ww .  ja  va2  s  .c om
public Dialog onCreateDialog(Bundle savedInstanceState) {
    getAnalytics().sendScreenView(SCREEN_NAME);
    final Context context = getContext();
    mLayout = null;
    Pair<String, String> language = PreferencesUtils.getOCRLanguage(context);

    final OcrLanguage.InstallStatus installStatus = OcrLanguageDataStore.isLanguageInstalled(language.first,
            context);

    if (!installStatus.isInstalled()) {
        final String defaultLanguage = context.getString(R.string.default_ocr_language);
        final String defaultLanguageDisplay = context.getString(R.string.default_ocr_display_language);
        language = Pair.create(defaultLanguage, defaultLanguageDisplay);
    }
    mLanguage = language.first;

    AlertDialog.Builder builder;

    builder = new AlertDialog.Builder(context);
    builder.setCancelable(false);
    View layout = View.inflate(context, R.layout.dialog_layout_question, null);
    builder.setView(layout);

    final ViewFlipper titleViewFlipper = (ViewFlipper) layout.findViewById(R.id.layout_title);
    final ImageView columnLayout = (ImageView) layout.findViewById(R.id.column_layout);
    final ImageView pageLayout = (ImageView) layout.findViewById(R.id.page_layout);
    final ImageSwitcher fairy = (ImageSwitcher) layout.findViewById(R.id.fairy_layout);
    fairy.setFactory(new ViewSwitcher.ViewFactory() {
        public View makeView() {
            return new ImageView(context);
        }
    });
    fairy.setImageResource(R.drawable.fairy_looks_center);
    fairy.setInAnimation(context, android.R.anim.fade_in);
    fairy.setOutAnimation(context, android.R.anim.fade_out);

    final int color = context.getResources().getColor(R.color.progress_color);

    final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.LIGHTEN);

    columnLayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mLayout != LayoutKind.COMPLEX) {
                fairy.setImageResource(R.drawable.fairy_looks_left);
                titleViewFlipper.setDisplayedChild(2);
                columnLayout.setColorFilter(colorFilter);
                pageLayout.clearColorFilter();
                mLayout = LayoutKind.COMPLEX;
            }

        }
    });
    pageLayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mLayout != LayoutKind.SIMPLE) {
                mLayout = LayoutKind.SIMPLE;
                titleViewFlipper.setDisplayedChild(1);
                fairy.setImageResource(R.drawable.fairy_looks_right);
                pageLayout.setColorFilter(colorFilter);
                columnLayout.clearColorFilter();
            }
        }
    });

    final Spinner langButton = (Spinner) layout.findViewById(R.id.button_language);
    List<OcrLanguage> installedLanguages = OcrLanguageDataStore.getInstalledOCRLanguages(context);

    // actual values uses by tesseract
    final ArrayAdapter<OcrLanguage> adapter = new ArrayAdapter<>(context, R.layout.language_spinner_item,
            installedLanguages);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    langButton.setAdapter(adapter);
    for (int i = 0; i < installedLanguages.size(); i++) {
        OcrLanguage lang = installedLanguages.get(i);
        if (lang.getValue().equals(language.first)) {
            langButton.setSelection(i, false);
            break;
        }
    }
    langButton.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            final OcrLanguage item = adapter.getItem(position);
            mLanguage = item.getValue();
            PreferencesUtils.saveOCRLanguage(context, item);
            getAnalytics().sendOcrLanguageChanged(item);
        }

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

        }
    });

    builder.setPositiveButton(R.string.start_scan, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int id) {
            if (mLayout == null) {
                mLayout = LayoutKind.SIMPLE;
            }
            LayoutChoseListener listener = (LayoutChoseListener) getActivity();
            listener.onLayoutChosen(mLayout, mLanguage);
            getAnalytics().sendOcrStarted(mLanguage, mLayout);
            dialog.dismiss();
        }
    });

    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int id) {
            getActivity().finish();
            dialog.dismiss();
            getAnalytics().sendLayoutDialogCancelled();
        }
    });

    return builder.create();

}

From source file:org.akvo.caddisfly.ui.activity.MainActivity.java

@Override
public void onLoadCalibration(final Handler.Callback callback) {
    final Context context = this;
    final MainApp mainApp = (MainApp) this.getApplicationContext();

    try {/* ww w  . j ava  2 s  . c  o  m*/
        AlertDialog.Builder builderSingle = new AlertDialog.Builder(context);
        builderSingle.setIcon(R.drawable.ic_launcher);
        builderSingle.setTitle(R.string.loadCalibration);

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

        File external = Environment.getExternalStorageDirectory();
        final String folderName = Config.CALIBRATE_FOLDER_NAME;
        String path = external.getPath() + folderName;
        File folder = new File(path);
        if (folder.exists()) {
            final File[] listFiles = folder.listFiles();
            for (File listFile : listFiles) {
                arrayAdapter.add(listFile.getName());
            }

            builderSingle.setNegativeButton(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) {
                    String fileName = listFiles[which].getName();
                    final ArrayList<Integer> swatchList = new ArrayList<Integer>();

                    final ArrayList<String> rgbList = FileUtils.loadFromFile(fileName);
                    if (rgbList != null) {

                        for (String rgb : rgbList) {
                            swatchList.add(ColorUtils.getColorFromRgb(rgb));
                        }
                        (new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                mainApp.saveCalibratedSwatches(mainApp.currentTestInfo.getCode(), swatchList);

                                mainApp.setSwatches(mainApp.currentTestInfo.getCode());

                                SharedPreferences sharedPreferences = PreferenceManager
                                        .getDefaultSharedPreferences(context);
                                SharedPreferences.Editor editor = sharedPreferences.edit();

                                for (int i = 0; i < mainApp.rangeIntervals.size(); i++) {
                                    int index = i * mainApp.rangeIncrementStep;

                                    ColorUtils.autoGenerateColors(index, mainApp.currentTestInfo.getCode(),
                                            mainApp.colorList, mainApp.rangeIncrementStep, editor, 0);
                                }
                                editor.apply();
                                return null;
                            }

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

                    }
                }
            });

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

                            AlertUtils.askQuestion(context, R.string.delete, R.string.selectedWillBeDeleted,
                                    new DialogInterface.OnClickListener() {
                                        @SuppressWarnings("unchecked")
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            String fileName = listFiles[position].getName();
                                            FileUtils.deleteFile(folderName, fileName);
                                            ArrayAdapter listAdapter = (ArrayAdapter) listView.getAdapter();
                                            listAdapter.remove(listAdapter.getItem(position));
                                        }
                                    });
                            return true;
                        }
                    });

                }
            });
            alert.show();
        } else {
            AlertUtils.showMessage(context, R.string.notFound, R.string.noSavedCalibrations);
        }
    } catch (ActivityNotFoundException e) {
        AlertUtils.showMessage(context, R.string.error, R.string.updateRequired);
    }

    callback.handleMessage(null);
}

From source file:com.openerp.addons.idea.product.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case R.id.Dash_Board:

        Dash_Board detail = new Dash_Board();
        FragmentListener frag = (FragmentListener) getActivity();
        frag.startDetailFragment(detail);

        return true;

    case R.id.Search_product:

        final Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.product_search_custom_dialog);
        //   dialog.setTitle("Product Search");
        dialog.setOnCancelListener(new OnCancelListener() {

            @Override//from   ww w  .j a v a2s  .c  o  m
            public void onCancel(DialogInterface dialog) {

                dialog.dismiss();
            }
        });

        AutoCompleteTextView autotext = (AutoCompleteTextView) dialog
                .findViewById(R.id.autoCompleteTextView_product_search);
        final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1,
                OEHelper.datatemplate);
        TextView txv = (TextView) dialog.findViewById(R.id.textView1);
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Georgia.ttf");
        autotext.setTypeface(font, Typeface.BOLD);
        autotext.setAdapter(adapter);
        txv.setTypeface(font, Typeface.BOLD);
        autotext.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                String name = adapter.getItem(arg2).toString();
                callmethod_for_position_productdetail(OEHelper.datatemplate.indexOf(name));
                dialog.dismiss();
            }
        });

        dialog.show();
        return true;
    }
    return true;
}