Example usage for android.widget Spinner setAdapter

List of usage examples for android.widget Spinner setAdapter

Introduction

In this page you can find the example usage for android.widget Spinner setAdapter.

Prototype

@Override
public void setAdapter(SpinnerAdapter adapter) 

Source Link

Document

Sets the SpinnerAdapter used to provide the data which backs this Spinner.

Usage

From source file:org.rapidandroid.activity.FormCreator.java

/**
 * //from   w  w w .  ja  va  2s  .c o  m
 */
// private void updateFieldList() {
// ListView lsv = (ListView) findViewById(R.id.lsv_createfields);
// if (mCurrentFields == null) {
// mCurrentFields = new Vector<Field>();
// }
//
// Field[] fieldArray = this.mCurrentFields
// .toArray(new Field[mCurrentFields.size()]);
// lsv.setAdapter(new FieldViewAdapter(this, fieldArray));
// }

// This is a call to the DB to get all the forms that this form can support.
private void initParserSpinner() {
    // The steps:
    // get the spinner control from the layouts
    Spinner spin_forms = (Spinner) findViewById(R.id.spinner_formparser);
    // Get an array of forms from the DB
    // in the current iteration, it's mForms
    // this.mAllParsers = ModelTranslator.getAllForms();

    String[] monitors = new String[mAllParsers.length];

    for (int i = 0; i < mAllParsers.length; i++) {
        monitors[i] = "Parse Mode: " + mAllParsers[i].getName();
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            monitors);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // apply it to the spinner
    spin_forms.setAdapter(adapter);
}

From source file:com.kncwallet.wallet.ui.WalletActivity.java

private void prepareImportKeysDialog(final Dialog dialog) {
    final AlertDialog alertDialog = (AlertDialog) dialog;

    final List<File> files = new LinkedList<File>();

    // external storage
    if (Constants.EXTERNAL_WALLET_BACKUP_DIR.exists() && Constants.EXTERNAL_WALLET_BACKUP_DIR.isDirectory())
        for (final File file : Constants.EXTERNAL_WALLET_BACKUP_DIR.listFiles())
            if (WalletUtils.KEYS_FILE_FILTER.accept(file) || Crypto.OPENSSL_FILE_FILTER.accept(file))
                files.add(file);//from  w w  w .  j av a  2 s  .c o m

    // internal storage
    for (final String filename : fileList())
        if (filename.startsWith(Constants.WALLET_KEY_BACKUP_BASE58 + '.'))
            files.add(new File(getFilesDir(), filename));

    // sort
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(final File lhs, final File rhs) {
            return lhs.getName().compareToIgnoreCase(rhs.getName());
        }
    });

    final FileAdapter adapter = new FileAdapter(this, files) {
        @Override
        public View getDropDownView(final int position, View row, final ViewGroup parent) {
            final File file = getItem(position);
            final boolean isExternal = Constants.EXTERNAL_WALLET_BACKUP_DIR.equals(file.getParentFile());
            final boolean isEncrypted = Crypto.OPENSSL_FILE_FILTER.accept(file);

            if (row == null)
                row = inflater.inflate(R.layout.wallet_import_keys_file_row, null);

            final TextView filenameView = (TextView) row
                    .findViewById(R.id.wallet_import_keys_file_row_filename);
            filenameView.setText(file.getName());

            final TextView securityView = (TextView) row
                    .findViewById(R.id.wallet_import_keys_file_row_security);
            final String encryptedStr = context
                    .getString(isEncrypted ? R.string.import_keys_dialog_file_security_encrypted
                            : R.string.import_keys_dialog_file_security_unencrypted);
            final String storageStr = context
                    .getString(isExternal ? R.string.import_keys_dialog_file_security_external
                            : R.string.import_keys_dialog_file_security_internal);
            securityView.setText(encryptedStr + ", " + storageStr);

            final TextView createdView = (TextView) row.findViewById(R.id.wallet_import_keys_file_row_created);
            createdView.setText(context.getString(
                    isExternal ? R.string.import_keys_dialog_file_created_manual
                            : R.string.import_keys_dialog_file_created_automatic,
                    DateUtils.getRelativeTimeSpanString(context, file.lastModified(), true)));

            return row;
        }
    };

    final Spinner fileView = (Spinner) alertDialog.findViewById(R.id.import_keys_from_storage_file);
    fileView.setAdapter(adapter);
    fileView.setEnabled(!adapter.isEmpty());

    final EditText passwordView = (EditText) alertDialog.findViewById(R.id.import_keys_from_storage_password);
    passwordView.setText(null);

    final ImportDialogButtonEnablerListener dialogButtonEnabler = new ImportDialogButtonEnablerListener(
            passwordView, alertDialog) {
        @Override
        protected boolean hasFile() {
            return fileView.getSelectedItem() != null;
        }

        @Override
        protected boolean needsPassword() {
            final File selectedFile = (File) fileView.getSelectedItem();
            return selectedFile != null ? Crypto.OPENSSL_FILE_FILTER.accept(selectedFile) : false;
        }
    };
    passwordView.addTextChangedListener(dialogButtonEnabler);
    fileView.setOnItemSelectedListener(dialogButtonEnabler);

    final CheckBox showView = (CheckBox) alertDialog.findViewById(R.id.import_keys_from_storage_show);
    showView.setOnCheckedChangeListener(new ShowPasswordCheckListener(passwordView));

    KnCDialog.fixDialogDivider(alertDialog);
}

From source file:com.here.android.example.venue.Venue3dActivity.java

private void configureSpinner(Spinner spinner, String[] listItems) {
    int spinner_item = android.R.layout.simple_spinner_item;
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, spinner_item, listItems) {
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            ((TextView) v).setTextColor(Color.BLACK);
            return v;
        }/*www . j  a  v a2 s.c o m*/

        public View getDropDownView(int pos, View convertView, ViewGroup parent) {
            View v = super.getDropDownView(pos, convertView, parent);
            ((TextView) v).setTextSize(22);
            return v;
        }
    };
    spinner.setAdapter(adapter);
}

From source file:info.tellmetime.TellmetimeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_tellmetime);

    mDensity = getResources().getDisplayMetrics().density;
    mScreenWidth = getResources().getDisplayMetrics().widthPixels;
    mScreenHeight = getResources().getDisplayMetrics().heightPixels;
    mShorterEdge = Math.min(mScreenWidth, mScreenHeight);
    mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
    mBacklightLight = getResources().getColor(R.color.backlight_light);
    mBacklightDark = getResources().getColor(R.color.backlight_dark);

    // Restore background and highlight colors from saved values or set defaults.
    mSettings = getSharedPreferences("PREFS", Context.MODE_PRIVATE);
    mHighlightColor = mSettings.getInt(HIGHLIGHT, Color.WHITE);
    mBacklightColor = mSettings.getInt(BACKLIGHT, mBacklightLight);
    mBackgroundColor = mSettings.getInt(BACKGROUND, getResources().getColor(R.color.background));
    mBackgroundMode = mSettings.getInt(BACKGROUND_MODE, MODE_BACKGROUND_SOLID);
    mHighlightPosition = mSettings.getFloat(POSITION, 0.0f);
    mMinutesSize = mSettings.getInt(MINUTES_SIZE, 36);
    isNightMode = mSettings.getBoolean(NIGHTMODE, false);

    // Dim the navigation bar.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        getWindow().getDecorView().setSystemUiVisibility(isNightMode ? View.SYSTEM_UI_FLAG_LOW_PROFILE : 0);

    mSurface = (RelativeLayout) findViewById(R.id.surface);
    mSurface.setBackgroundColor(mBackgroundColor);

    resizeClock();/*from w w w .j a  v  a  2  s  .c  om*/

    Typeface mTypefaceBold = Typeface.createFromAsset(getAssets(), "Roboto-BoldCondensed.ttf");

    // Set typeface of all items in the clock to Roboto and dim each one and drop shadow on them.
    final LinearLayout mClock = (LinearLayout) findViewById(R.id.clock);
    for (int i = 0; i < mClock.getChildCount(); i++) {
        LinearLayout row = (LinearLayout) mClock.getChildAt(i);

        for (int j = 0; j < row.getChildCount(); j++) {
            TextView tv = (TextView) row.getChildAt(j);

            tv.setTypeface(mTypefaceBold);
            tv.setTextColor(mBacklightColor);
            tv.setShadowLayer(mShorterEdge / 200 * mDensity, 0, 0, mBacklightColor);
        }
    }

    ViewGroup minutesDots = (ViewGroup) findViewById(R.id.minutes_dots);
    for (int i = 0; i < minutesDots.getChildCount(); i++) {
        TextView m = (TextView) minutesDots.getChildAt(i);

        m.setTypeface(mTypefaceBold);
        m.setTextColor(mBacklightColor);
        m.setShadowLayer(mShorterEdge / 200 * mDensity, 0, 0, mBacklightColor);
    }

    // Set Roboto font on TextView where it isn't default.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        Typeface mTypefaceItalic = Typeface.createFromAsset(getAssets(), "Roboto-CondensedItalic.ttf");

        ((TextView) findViewById(R.id.labelBackground)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.info_background)).setTypeface(mTypefaceItalic);
        ((TextView) findViewById(R.id.info_image)).setTypeface(mTypefaceItalic);
        ((TextView) findViewById(R.id.labelHighlight)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.labelBackground)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.radio_backlight_light)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.radio_backlight_dark)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.radio_backlight_highlight)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.labelMinutes)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m1)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m2)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m3)).setTypeface(mTypefaceBold);
        ((TextView) findViewById(R.id.m4)).setTypeface(mTypefaceBold);
    }

    FrameLayout mTouchZone = (FrameLayout) findViewById(R.id.touchZone);
    mTouchZone.setOnTouchListener(this);
    mTouchZone.setBackgroundColor(
            getResources().getColor(isNightMode ? R.color.night_mode_overlay : android.R.color.transparent));

    mBackgroundImage = (ImageView) findViewById(R.id.background_image);
    switchBackgroundMode(mBackgroundMode);

    RelativeLayout mPanel = (RelativeLayout) findViewById(R.id.panel);
    mPanel.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mHider.delayedHide(4000);
            return true;
        }
    });

    mHider = new PanelHider(mPanel, this);

    Spinner spinnerBackgroundMode = (Spinner) findViewById(R.id.spinnerBackgroundMode);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.backgrounds_modes,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerBackgroundMode.setAdapter(adapter);
    spinnerBackgroundMode.setOnItemSelectedListener(this);
    spinnerBackgroundMode.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mHider.showNoAutoHide();
            return false;
        }
    });
    spinnerBackgroundMode.setSelection(mBackgroundMode);

    mSeekBarHighlight = (SeekBar) findViewById(R.id.highlightValue);
    mSeekBarHighlight.setOnSeekBarChangeListener(this);

    // Draw rainbow gradient on #mSeekBarHighlight and set position.
    drawRainbow();

    if (mBacklightColor == mBacklightLight)
        ((RadioButton) findViewById(R.id.radio_backlight_light)).setChecked(true);
    else if (mBacklightColor == mBacklightDark)
        ((RadioButton) findViewById(R.id.radio_backlight_dark)).setChecked(true);
    else
        ((RadioButton) findViewById(R.id.radio_backlight_highlight)).setChecked(true);

    SeekBar mSeekBarMinutes = (SeekBar) findViewById(R.id.minutesSize);
    mSeekBarMinutes.setOnSeekBarChangeListener(this);
    mSeekBarMinutes.setProgress(mMinutesSize);

    mHider.hideNow();

    Color.colorToHSV(mBackgroundColor, mHSV);
    mHSV[1] = 1.0f;

    //Trigger initial tick.
    mClockAlgorithm.tickTock();

    // Schedule the clock algorithm to tick every round minute.
    Calendar time = Calendar.getInstance();
    time.set(Calendar.MILLISECOND, 0);
    time.set(Calendar.SECOND, 0);
    time.add(Calendar.MINUTE, 1);

    Timer timer = new Timer();
    timer.schedule(mClockTask, time.getTime(), 60 * 1000);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mSurface.setAlpha(0.0f);
        mSurface.animate().alpha(1.0f).setDuration(1500);
    }

    // If it is first run, hint to user that panel is available.
    if (!mSettings.contains(HIGHLIGHT))
        showToast(R.string.info_first_run);
}

From source file:org.openmrs.mobile.activities.formdisplay.FormDisplayPageFragment.java

@Override
public void createAndAttachSelectQuestionDropdown(Question question, LinearLayout sectionLinearLayout) {
    TextView textView = new TextView(getActivity());
    textView.setPadding(20, 0, 0, 0);//  w  ww. ja  v a  2 s.  co m
    textView.setText(question.getLabel());
    Spinner spinner = (Spinner) getActivity().getLayoutInflater().inflate(R.layout.form_dropdown, null);

    LinearLayout questionLinearLayout = new LinearLayout(getActivity());
    LinearLayout.LayoutParams questionLinearLayoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    questionLinearLayout.setOrientation(LinearLayout.VERTICAL);
    questionLinearLayoutParams.gravity = Gravity.START;
    questionLinearLayout.setLayoutParams(questionLinearLayoutParams);

    List<String> answerLabels = new ArrayList<>();
    for (Answer answer : question.getQuestionOptions().getAnswers()) {
        answerLabels.add(answer.getLabel());
    }

    SelectOneField spinnerField = new SelectOneField(question.getQuestionOptions().getAnswers(),
            question.getQuestionOptions().getConcept());

    ArrayAdapter arrayAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item,
            answerLabels);
    spinner.setAdapter(arrayAdapter);

    LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    questionLinearLayout.addView(textView);
    questionLinearLayout.addView(spinner);

    sectionLinearLayout.setLayoutParams(linearLayoutParams);
    sectionLinearLayout.addView(questionLinearLayout);

    SelectOneField selectOneField = getSelectOneField(spinnerField.getConcept());
    if (selectOneField != null) {
        spinner.setSelection(selectOneField.getChosenAnswerPosition());
        setOnItemSelectedListener(spinner, selectOneField);
    } else {
        setOnItemSelectedListener(spinner, spinnerField);
        selectOneFields.add(spinnerField);
    }
}

From source file:it.ielettronica.TVS.MyListAdapterExt.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    //If there's no recycled view, inflate one and tag each of the views
    //you'll want to modify later
    //Log.d("Inside", "GetView");

    plv = null;//  w ww . j a v a2 s.  com
    if (convertView == null) {

        convertView = mInflater.inflate(R.layout.row_site_remote, parent, false);
        plv = new PlaylistValues();

        plv.nameTxt = (TextView) convertView.findViewById(R.id.nameTxt);
        plv.aboutTxt = (TextView) convertView.findViewById(R.id.aboutTxt);
        plv.iconImg = (ImageView) convertView.findViewById(R.id.iconImg);
        plv.btnPlayLocal = (Button) convertView.findViewById(R.id.btnPlayLocal);
        plv.indicator = (ProgressBar) convertView.findViewById(R.id.progress);
        plv.btnAddLocal = (Button) convertView.findViewById(R.id.btnAddLocal);
        plv.imageState = (ImageView) convertView.findViewById(R.id.imgState);
        plv.btnEditDel = (Button) convertView.findViewById(R.id.btnEditDel);
        //This assumes layout/row_left.xml includes a TextView with an id of "textview"
        convertView.setTag(plv);
    } else {
        plv = (PlaylistValues) convertView.getTag();
    }

    //Initially we want the progress indicator visible, and the image invisible
    plv.indicator.setVisibility(View.VISIBLE);
    plv.iconImg.setVisibility(View.INVISIBLE);

    if (MainActivity.isAmministrator()) {
        plv.btnEditDel.setVisibility(View.VISIBLE);
    } else {
        plv.btnEditDel.setVisibility(View.INVISIBLE);
    }

    //Retrieve the tagged view, get the item for that position, and
    //update the text

    ImageLoadingListener listener = new ImageLoadingListener() {

        @Override
        public void onLoadingStarted(String arg0, View arg1) {
            // TODO Auto-generated method stub
            plv.indicator.setVisibility(View.INVISIBLE);
            plv.iconImg.setVisibility(View.VISIBLE);

        }

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
            //plv.indicator.setVisibility(View.INVISIBLE);
            //plv.iconImg.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
            // TODO Auto-generated method stub

        }

    };

    stk = mItems.get(position);
    plv.nameTxt.setText(stk.getName());
    plv.aboutTxt.setText(stk.getAbout());

    String uri = "@drawable/myresource"; // where myresource.png is the file
    // extension removed from the String

    if (MainActivity.isAmministrator() == Boolean.TRUE) {
        Drawable res;
        if (stk.getAccepted() == 1) {
            res = ContextCompat.getDrawable(MainActivity.getAppContext(), R.drawable.good);
        } else {
            res = ContextCompat.getDrawable(MainActivity.getAppContext(), R.drawable.warning);
        }
        plv.imageState.setImageDrawable(res);
    }

    imageLoader.displayImage(stk.getImgUrl(), plv.iconImg, options, listener);

    plv.btnEditDel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            final StackSite stkloc = mItems.get(position);
            MainActivity.posRemoteListBeforeExecuted = sitesMusic.getFirstVisiblePosition();
            Intent intent = new Intent(MainActivity.getAppContext(), ModChannel.class);

            intent.putExtra("TitleChannel", stkloc.getName());
            intent.putExtra("DescrChannel", stkloc.getAbout());
            intent.putExtra("IconChannel", stkloc.getImgUrl());
            intent.putExtra("isAccepted", stkloc.getAccepted());
            intent.putExtra("NameGroup", GroupVSeletced.getGroupName());
            intent.putExtra("LevelGroup", GroupVSeletced.getGroupLevel());
            intent.putExtra("TypeGroup", GroupVSeletced.getGroupType());

            intent.putExtra("GroupLevel", GroupVSeletced.getGroupLevel());
            tabFromDB.fa.startActivity(intent);

        }
    });

    plv.btnPlayLocal.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            //                final Intent intent = new Intent(v.getContext(), MediaPlayerDemo_Video.class);
            final StackSite stkloc = mItems.get(position);
            MainActivity.posRemoteListBeforeExecuted = sitesMusic.getFirstVisiblePosition();

            GroupType = GroupVSeletced.getGroupType();

            RemoteCommunications rm = new RemoteCommunications();
            List<StackLink> Links = new ArrayList<StackLink>();
            rm.getLinks(Links, stkloc.getName(), new GetLinkCallback() {
                @Override
                public void done(List<StackLink> returnedLinks) {
                    List<StackLink> Links = returnedLinks;
                    if (Links.size() == 1) {
                        MainActivity.posLocalListBeforeExecuted = tabFromDB.sitesMusic
                                .getFirstVisiblePosition();
                        if (MainActivity.isAmministrator()) {

                            Intent intent = new Intent(MainActivity.getAppContext(), LinksLists.class);
                            intent.putExtra("VideoStreamName", stkloc.getName());
                            intent.putExtra("GroupType", GroupType);

                            tabFromDB.fa.startActivity(intent);

                        } else {
                            String linkVal = Links.get(0).getLinkValue();
                            //Uri myUri = Uri.parse(linkVal);

                            if (GroupType == 0) {

                                Intent mpdIntent = new Intent(tabLocal.Fa.getContext(), PlayerActivity.class)
                                        .setData(Uri.parse(linkVal))
                                        .putExtra(PlayerActivity.CONTENT_ID_EXTRA, "")
                                        .putExtra(PlayerActivity.CONTENT_TYPE_EXTRA, PlayerActivity.TYPE_HLS)
                                        .putExtra(PlayerActivity.PROVIDER_EXTRA, "");
                                tabFromDB.fa.getContext().startActivity(mpdIntent);

                            } else if (GroupType == 1) {

                                //                                    Intent intent2 = new Intent(tabLocal.Fa.getContext(), MediaPlayerDemo_VideoView.class);
                                //                                    intent2.putExtra("pathValue", linkVal);
                                //                                    tabFromDB.fa.getContext().startActivity(intent2);

                            } else {

                                //                                    intent.putExtra("media", 5);
                                //                                    intent.putExtra("pathValue", linkVal);
                                //
                                //                                    try {
                                //                                        tabFromDB.fa.startActivity(intent);
                                //                                    } catch (Exception ex) {
                                //                                        Toast.makeText(cloc, ex.toString(),
                                //                                                Toast.LENGTH_SHORT).show();
                                //                                    }

                            }

                            Toast.makeText(cloc, "Play: " + stkloc.getName(), Toast.LENGTH_SHORT).show();

                        }

                    } else if (Links.size() == 0) {
                        Toast.makeText(cloc,
                                "the channel:  '" + stkloc.getName() + "' doesn't have any link associated",
                                Toast.LENGTH_SHORT).show();
                    } else {

                        Intent intent = new Intent(MainActivity.getAppContext(), LinksLists.class);
                        intent.putExtra("VideoStreamName", stkloc.getName());
                        tabFromDB.fa.startActivity(intent);

                    }
                }
            });

        }
    });

    plv.btnAddLocal.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            stkloc = mItems.get(position);

            RemoteCommunications rm = new RemoteCommunications();
            List<StackLink> Links = new ArrayList<StackLink>();
            rm.getLinks(Links, stkloc.getName(), new GetLinkCallback() {
                @Override
                public void done(List<StackLink> returnedLinks) {

                    AlertDialog.Builder alertDialog;
                    try {
                        alertDialog = new AlertDialog.Builder(tabFromDB.fa.getContext());
                    } catch (Exception ex) {
                        alertDialog = new AlertDialog.Builder(MainActivity.getAppContext());
                    }

                    retLinks = returnedLinks;
                    LinearLayout layout = new LinearLayout(MainActivity.getAppContext());
                    layout.setOrientation(LinearLayout.VERTICAL);

                    if (returnedLinks.size() > 1) {

                        LinearLayout rlayoutLink = new LinearLayout(MainActivity.getAppContext());
                        rlayoutLink.setOrientation(LinearLayout.HORIZONTAL);
                        final TextView textView = new TextView(MainActivity.getAppContext());
                        textView.setText("Links:  ");
                        textView.setGravity(Gravity.RIGHT);
                        textView.setLayoutParams(
                                new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));
                        rlayoutLink.addView(textView);
                        listLinks = new Spinner(MainActivity.getAppContext());

                        List<String> retLinksString = new ArrayList<String>();
                        for (int i = 0; i < returnedLinks.size(); i++) {
                            retLinksString.add(returnedLinks.get(i).getLinkTxt());
                        }

                        listLinks.setAdapter(new MyCustomAdapter(MainActivity.getAppContext(),
                                R.layout.rowspinnertake, retLinksString, returnedLinks));

                        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.getAppContext(), android.R.layout.simple_spinner_item, retLinksString);
                        //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //listLinks.setAdapter(adapter);

                        listLinks.setLayoutParams(
                                new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        rlayoutLink.addView(listLinks);
                        layout.addView(rlayoutLink);
                    }

                    final Button btnAddToTheEnd = new Button(MainActivity.getAppContext());
                    btnAddToTheEnd.setText("Add");

                    btnAddToTheEnd.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {

                            StackSite stkloc = mItems.get(position);

                            if (listLinks != null) {
                                posSpinnerLink = listLinks.getSelectedItemPosition();
                            } else {
                                posSpinnerLink = 0;
                            }

                            if (retLinks.size() == 0) {
                                Toast.makeText(cloc,
                                        "the channel:  '" + stkloc.getName()
                                                + "' doesn't have any link associated",
                                        Toast.LENGTH_SHORT).show();
                            } else {

                                String url;

                                if (retLinks.size() == 1) {

                                    url = retLinks.get(0).getLinkValue();

                                } else {
                                    url = retLinks.get(posSpinnerLink).getLinkValue();
                                }

                                stkloc.setLink(url);
                                stkloc.setTypeStream(GroupVSeletced.getGroupType());
                                stkloc.setStaticName(stkloc.getName());
                                String nameStation = stkloc.getName();
                                stkloc.setOrigin(0);
                                boolean isAdded = dbHandler.addSite(stkloc);
                                if (isAdded) {
                                    Toast.makeText(MainActivity.getAppContext(),
                                            nameStation + " is added in Local Playlist", Toast.LENGTH_SHORT)
                                            .show();
                                }
                                List<StackSite> itemsLocal;
                                itemsLocal = dbHandler.getStackSites();
                                if (itemsLocal.size() == 0) {
                                    tabLocal.editEmptyLocalList.setVisibility(View.VISIBLE);
                                } else {
                                    tabLocal.editEmptyLocalList.setVisibility(View.INVISIBLE);
                                }

                                tabLocal.sitesLocal.setCheeseList(itemsLocal);
                                tabLocal.sitesLocal.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                                StableArrayAdapter adapterLocal = new StableArrayAdapter(
                                        tabLocal.Fa.getContext(), R.layout.row_site_local, itemsLocal);
                                tabLocal.sitesLocal.setAdapter(adapterLocal);

                                OptionDialog.dismiss();

                            }

                        }
                    });
                    btnAddToTheEnd.setLayoutParams(
                            new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));
                    layout.addView(btnAddToTheEnd);

                    final Button btnAddAfter = new Button(MainActivity.getAppContext());
                    final Spinner listChannelAlreadyAdded = new Spinner(MainActivity.getAppContext());
                    List<String> ListNameChannel;
                    ListNameChannel = dbHandler.getNamesFromStackSites();
                    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.getAppContext(),
                            android.R.layout.simple_spinner_item, ListNameChannel);
                    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    listChannelAlreadyAdded.setAdapter(adapter2);
                    posSpinner = listChannelAlreadyAdded.getSelectedItemPosition();

                    if (posSpinner != -1) {
                        LinearLayout rlayout = new LinearLayout(MainActivity.getAppContext());
                        rlayout.setOrientation(LinearLayout.HORIZONTAL);

                        btnAddAfter.setText("Add Before");
                        btnAddAfter.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {

                                if (listLinks != null) {
                                    posSpinnerLink = listLinks.getSelectedItemPosition();
                                } else {
                                    posSpinnerLink = 0;
                                }

                                StackSite stkloc = mItems.get(position);

                                if (retLinks.size() == 0) {
                                    Toast.makeText(cloc,
                                            "the channel:  '" + stkloc.getName()
                                                    + "' doesn't have any link associated",
                                            Toast.LENGTH_SHORT).show();
                                } else {

                                    String url;

                                    if (retLinks.size() == 1) {

                                        url = retLinks.get(0).getLinkValue();

                                    } else {
                                        url = retLinks.get(posSpinnerLink).getLinkValue();
                                    }

                                    stkloc.setLink(url);
                                    stkloc.setOrigin(0);
                                    stkloc.setTypeStream(GroupVSeletced.getGroupType());
                                    String nameStation = stkloc.getName();
                                    posSpinner = listChannelAlreadyAdded.getSelectedItemPosition();

                                    boolean isAdded = dbHandler.addSiteBefore(stkloc, posSpinner);
                                    if (isAdded) {
                                        Toast.makeText(MainActivity.getAppContext(),
                                                nameStation + " is added in Local Playlist", Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                    List<StackSite> itemsLocal;
                                    itemsLocal = dbHandler.getStackSites();
                                    tabLocal.sitesLocal.setCheeseList(itemsLocal);
                                    tabLocal.sitesLocal.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                                    StableArrayAdapter adapterLocal = new StableArrayAdapter(
                                            tabLocal.Fa.getContext(), R.layout.row_site_local, itemsLocal);
                                    tabLocal.sitesLocal.setAdapter(adapterLocal);

                                    OptionDialog.dismiss();

                                }

                            }
                        });

                        btnAddAfter.setLayoutParams(
                                new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));
                        rlayout.addView(btnAddAfter);
                        listChannelAlreadyAdded.setLayoutParams(
                                new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        rlayout.addView(listChannelAlreadyAdded);
                        layout.addView(rlayout);
                    }

                    final Button btnCancel = new Button(MainActivity.getAppContext());
                    btnCancel.setText("Cancel");
                    btnCancel.setLayoutParams(
                            new FrameLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT));

                    btnCancel.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            OptionDialog.dismiss();
                        }
                    });

                    layout.addView(btnCancel);
                    alertDialog.setView(layout); // uncomment this line
                    alertDialog.setTitle("Take the Channel");
                    OptionDialog = alertDialog.create();
                    OptionDialog.show();
                }

            });

        }

    });

    return convertView;
}

From source file:com.androguide.honamicontrol.kernel.cpucontrol.CPUActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //noinspection ConstantConditions
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.ic_tools_cpu_control));
    setContentView(R.layout.card_cpu_control);
    bootPrefs = getSharedPreferences("BOOT_PREFS", 0);

    graph = (LineGraph) findViewById(R.id.graph);
    line = new Line();
    LinePoint point = new LinePoint();
    point.setX(currX);/*from  w  w w  .j  a  v  a 2s  .  co m*/
    point.setY(1);
    line.addPoint(point);
    line.setColor(Color.parseColor("#FFBB33"));
    graph.addLine(line);
    graph.setLineToFill(0);

    availableFrequencies = new String[0];
    String availableFrequenciesLine;

    mCoresOnline = (TextView) findViewById(R.id.cores_online);
    mGeneralGovernor = (Spinner) findViewById(R.id.general_governor);
    mGovernor = (Spinner) findViewById(R.id.governor);
    mGovernor2 = (Spinner) findViewById(R.id.governor2);
    mGovernor3 = (Spinner) findViewById(R.id.governor3);
    mGovernor4 = (Spinner) findViewById(R.id.governor4);

    Button customizeGov = (Button) findViewById(R.id.governor_customize_btn);
    customizeGov.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            GovernorDialog editNameDialog = new GovernorDialog();
            editNameDialog.show(fm, "governor_fragment");
        }
    });

    if (Helpers.doesFileExist(STEPS)) {
        availableFrequenciesLine = CPUHelper.readOneLineNotRoot(STEPS);

        if (availableFrequenciesLine != null) {
            availableFrequencies = availableFrequenciesLine.split(" ");
            Arrays.sort(availableFrequencies, new Comparator<String>() {
                @Override
                public int compare(String object1, String object2) {
                    return Integer.valueOf(object1).compareTo(Integer.valueOf(object2));
                }
            });
        }
    }

    Switch snakeCharmer = (Switch) findViewById(R.id.snake_charmer_switch);
    if (!Helpers.doesFileExist(SNAKE_CHARMER_MAX_FREQ)) {
        LinearLayout cardSnakeCharmer = (LinearLayout) findViewById(R.id.card_snake_charmer);
        cardSnakeCharmer.setVisibility(View.GONE);
    } else {
        if (Helpers.doesFileExist(SNAKE_CHARMER_VERSION)) {
            TextView snakeTitle = (TextView) findViewById(R.id.snake_charmer);
            String snakeVersion = CPUHelper.readOneLineNotRoot(SNAKE_CHARMER_VERSION);
            snakeVersion = snakeVersion.replaceAll("version: ", "v");
            snakeTitle.setText(snakeTitle.getText() + " " + snakeVersion);
            if (snakeVersion.equals("v1.2")) {
                TextView snakeDesc = (TextView) findViewById(R.id.snake_charmer_text);
                snakeDesc.setText(snakeDesc.getText() + "\n" + getString(R.string.snake_charmer_built_in));
                snakeCharmer.setEnabled(false);
            }
        }

        if (bootPrefs.getBoolean("SNAKE_CHARMER", true)) {
            snakeCharmer.setChecked(true);
            snakeCharmerEnabled = true;
        }

        snakeCharmer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isOn) {
                snakeCharmerEnabled = isOn;
            }
        });
    }

    int frequenciesNum = availableFrequencies.length - 1;

    Switch thermalControl = (Switch) findViewById(R.id.msm_thermal_switch);
    if (Helpers.doesFileExist(MSM_THERMAL)) {
        String thermal = CPUHelper.readOneLineNotRoot(MSM_THERMAL);
        if (thermal.equals("Y"))
            thermalControl.setChecked(true);
        else
            thermalControl.setChecked(false);

        thermalControl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked)
                    Helpers.CMDProcessorWrapper.runSuCommand("echo Y > " + MSM_THERMAL);
                else
                    Helpers.CMDProcessorWrapper.runSuCommand("echo N > " + MSM_THERMAL);

                bootPrefs.edit().putBoolean("MSM_THERMAL", isChecked).commit();
            }
        });
    }
    thermalControl.setChecked(bootPrefs.getBoolean("MSM_THERMAL", true));

    perCoreGovernor = (Switch) findViewById(R.id.per_core_governors_switch);
    perCoreGovernor.setChecked(bootPrefs.getBoolean("PER_CORE_GOV", true));

    if (perCoreGovernor.isChecked()) {
        findViewById(R.id.card_general_governor).setVisibility(View.GONE);
        findViewById(R.id.card_per_core_governors).setVisibility(View.VISIBLE);
    } else {
        findViewById(R.id.card_per_core_governors).setVisibility(View.GONE);
        findViewById(R.id.card_general_governor).setVisibility(View.VISIBLE);
    }

    perCoreGovernor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if (isChecked) {
                findViewById(R.id.card_general_governor).setVisibility(View.GONE);
                findViewById(R.id.card_per_core_governors).setVisibility(View.VISIBLE);
                handleGovernors();
            } else {
                findViewById(R.id.card_per_core_governors).setVisibility(View.GONE);
                findViewById(R.id.card_general_governor).setVisibility(View.VISIBLE);
                handleGovernors();
            }

            bootPrefs.edit().putBoolean("PER_CORE_GOV", isChecked).commit();
        }
    });

    String currentIo = "";
    if (Helpers.doesFileExist(IO_SCHEDULER))
        currentIo = CPUHelper.getIOScheduler();

    String currentTcp = "";
    if (Helpers.doesFileExist(CURR_TCP_ALGORITHM))
        currentTcp = Helpers.getCurrentTcpAlgorithm();

    String curMaxSpeed = "NaN";
    if (Helpers.doesFileExist(MAX_FREQ_ALL_CORES))
        curMaxSpeed = CPUHelper.readOneLineNotRoot(MAX_FREQ_ALL_CORES);
    else if (Helpers.doesFileExist(MAX_FREQ))
        curMaxSpeed = CPUHelper.readOneLineNotRoot(MAX_FREQ);

    String curMinSpeed = "NaN";
    if (Helpers.doesFileExist(MIN_FREQ_ALL_CORES))
        curMinSpeed = CPUHelper.readOneLineNotRoot(MIN_FREQ_ALL_CORES);
    else if (Helpers.doesFileExist(MIN_FREQ))
        curMinSpeed = CPUHelper.readOneLineNotRoot(MIN_FREQ);

    if (mIsTegra3) {
        String curTegraMaxSpeed = "NaN";
        if (Helpers.doesFileExist(TEGRA_MAX_FREQ)) {
            curTegraMaxSpeed = CPUHelper.readOneLineNotRoot(TEGRA_MAX_FREQ);
            int curTegraMax = 0;
            try {
                curTegraMax = Integer.parseInt(curTegraMaxSpeed);
                if (curTegraMax > 0) {
                    curMaxSpeed = Integer.toString(curTegraMax);
                }
            } catch (NumberFormatException ex) {
                curTegraMax = 0;
            }
        }
    }

    if (Helpers.doesFileExist(NUM_OF_CPUS))
        mNumOfCpus = Helpers.getNumOfCpus();

    mCurFreq = (TextView) findViewById(R.id.currspeed);

    mMaxSlider = (SeekBar) findViewById(R.id.max_slider);
    mMaxSlider.setMax(frequenciesNum);
    mMaxSpeedText = (TextView) findViewById(R.id.max_speed_text);
    mMaxSpeedText.setText(toMHz(curMaxSpeed));
    mMaxSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMaxSpeed));
    mMaxSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser)
                setMaxSpeed(seekBar, progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            startSupportActionMode(new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                    MenuInflater inflater = actionMode.getMenuInflater();
                    inflater.inflate(R.menu.contextual_menu, menu);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.apply:
                        if (mMaxFreqSetting != null && !mMaxFreqSetting.isEmpty()) {
                            bootPrefs.edit().putString("CPU_MAX_FREQ", mMaxFreqSetting).commit();
                            for (int i = 0; i < mNumOfCpus; i++)
                                Helpers.CMDProcessorWrapper.runSuCommand("busybox echo " + mMaxFreqSetting
                                        + " > " + MAX_FREQ.replace("cpu0", "cpu" + i));

                            if (snakeCharmerEnabled)
                                Helpers.CMDProcessorWrapper.runSuCommand(
                                        "busybox echo " + mMaxFreqSetting + " > " + SNAKE_CHARMER_MAX_FREQ);
                        }

                        if (mIsTegra3) {
                            if (mMaxFreqSetting != null && !mMaxFreqSetting.isEmpty())
                                Helpers.CMDProcessorWrapper.runSuCommand(
                                        "busybox echo " + mMaxFreqSetting + " > " + TEGRA_MAX_FREQ);

                            if (snakeCharmerEnabled)
                                Helpers.CMDProcessorWrapper.runSuCommand(
                                        "busybox echo " + mMaxFreqSetting + " > " + SNAKE_CHARMER_MAX_FREQ);
                        }
                        actionMode.finish();
                        return true;
                    default:
                        return false;
                    }
                }

                @Override
                public void onDestroyActionMode(ActionMode actionMode) {

                }
            });
        }
    });

    mMinSlider = (SeekBar) findViewById(R.id.min_slider);
    mMinSlider.setMax(frequenciesNum);
    mMinSpeedText = (TextView) findViewById(R.id.min_speed_text);
    mMinSpeedText.setText(toMHz(curMinSpeed));
    mMinSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMinSpeed));
    mMinSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser)
                setMinSpeed(seekBar, progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            startSupportActionMode(new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                    MenuInflater inflater = actionMode.getMenuInflater();
                    inflater.inflate(R.menu.contextual_menu, menu);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.apply:
                        if (mMinFreqSetting != null && !mMinFreqSetting.isEmpty()) {
                            bootPrefs.edit().putString("CPU_MIN_FREQ", mMinFreqSetting).commit();
                            for (int i = 0; i < mNumOfCpus; i++)
                                Helpers.CMDProcessorWrapper.runSuCommand("busybox echo " + mMinFreqSetting
                                        + " > " + MIN_FREQ.replace("cpu0", "cpu" + i));
                        }
                        actionMode.finish();
                        return true;
                    default:
                        return false;
                    }
                }

                @Override
                public void onDestroyActionMode(ActionMode actionMode) {

                }
            });
        }
    });

    handleGovernors();

    /** TCP Congestion Spinner */
    Spinner mTcp = (Spinner) findViewById(R.id.tcp);
    ArrayAdapter<CharSequence> tcpAdapter = new ArrayAdapter<CharSequence>(this, R.layout.spinner_row);
    tcpAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ArrayList<String> algorithms = Helpers.getTcpAlgorithms();
    for (String algorithm : algorithms)
        tcpAdapter.add(algorithm);
    mTcp.setAdapter(tcpAdapter);
    mTcp.setSelection(algorithms.indexOf(currentTcp));
    mTcp.setOnItemSelectedListener(new TCPListener());

    onlineCoresPolling();
}

From source file:org.egov.android.view.activity.RegisterActivity.java

/**
 * load spinner from jsonarray/*from ww w . ja va2  s .  co m*/
 * @throws JSONException 
 */

public void loadCitiesFromJsonArray(Spinner dropdown) throws JSONException {

    List<String> spinnerArray = new ArrayList<String>();

    //default option
    spinnerArray.add("Select City");

    //sort cities a to z
    jsoncitiesarry = JSONUtil.sort(jsoncitiesarry, new Comparator() {
        public int compare(Object a, Object b) {
            JSONObject ja = (JSONObject) a;
            JSONObject jb = (JSONObject) b;
            return ja.optString("city_name", "").toLowerCase()
                    .compareTo(jb.optString("city_name", "").toLowerCase());
        }
    });

    for (int i = 0; i < jsoncitiesarry.length(); i++) {
        JSONObject city = jsoncitiesarry.getJSONObject(i);
        spinnerArray.add(city.getString("city_name"));
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            spinnerArray);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    dropdown.setAdapter(adapter);

}

From source file:in.andres.kandroid.ui.TaskDetailActivity.java

private void showSubtaskDialog(@Nullable final KanboardSubtask subtask) {
    View dlgView = getLayoutInflater().inflate(R.layout.dialog_new_subtask, null);
    final EditText editTitle = (EditText) dlgView.findViewById(R.id.subtask_title);
    editTitle.setText(subtask == null ? "" : subtask.getTitle());
    final Spinner userSpinner = (Spinner) dlgView.findViewById(R.id.user_spinner);
    ArrayList<String> possibleOwners = Collections.list(users.elements());
    possibleOwners.add(0, "");
    ArrayAdapter<String> adapter = new ArrayAdapter<>(self, android.R.layout.simple_spinner_item,
            possibleOwners);//  w w  w  .  j a v a  2  s.  c o m
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    userSpinner.setAdapter(adapter);
    if (subtask != null)
        userSpinner.setSelection(possibleOwners.indexOf(users.get(subtask.getUserId())));

    AlertDialog.Builder builder = new AlertDialog.Builder(self);
    builder.setTitle(getString(
            subtask == null ? R.string.taskview_fab_new_subtask : R.string.taskview_dlg_update_subtask));
    builder.setView(dlgView);
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Integer userid = null;
            if (userSpinner.getSelectedItem() != null) {
                for (Enumeration<Integer> iter = users.keys(); iter.hasMoreElements();) {
                    Integer key = iter.nextElement();
                    if (users.get(key).contentEquals((String) userSpinner.getSelectedItem())) {
                        userid = key;
                        break;
                    }
                }
            }
            if (!editTitle.getText().toString().equalsIgnoreCase("")) {
                if (subtask == null) {
                    Log.i(Constants.TAG, "Creating new subtask.");
                    kanboardAPI.createSubtask(task.getId(), editTitle.getText().toString(), userid, null, null,
                            null);
                } else {
                    Log.i(Constants.TAG, "Updating subtask.");
                    kanboardAPI.updateSubtask(subtask.getId(), subtask.getTaskId(),
                            editTitle.getText().toString(), userid, null, null, null);
                }
                dialog.dismiss();
            }
        }
    });
    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
}

From source file:gr.scify.newsum.ui.ViewActivity.java

@Override
public void run() {
    // take the String from the TopicActivity
    Bundle extras = getIntent().getExtras();
    Category = extras.getString(CATEGORY_INTENT_VAR);

    // Make sure we have updated the data source
    NewSumUiActivity.setDataSource(this);

    // Get user sources
    String sUserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

    // get Topics from TopicActivity (avoid multiple server calls)
    TopicInfo[] tiTopics = TopicActivity.getTopics(sUserSources, Category, this);

    // Also get Topic Titles, to display to adapter
    final String[] saTopicTitles = new String[tiTopics.length];
    // Also get Topic IDs
    final String[] saTopicIDs = new String[tiTopics.length];
    // Also get Dates, in order to show in summary title
    final String[] saTopicDates = new String[tiTopics.length];
    // DeHTML titles
    for (int iCnt = 0; iCnt < tiTopics.length; iCnt++) {
        // update Titles Array
        saTopicTitles[iCnt] = Html.fromHtml(tiTopics[iCnt].getTitle()).toString();
        // update IDs Array
        saTopicIDs[iCnt] = tiTopics[iCnt].getID();
        // update Date Array
        saTopicDates[iCnt] = tiTopics[iCnt].getPrintableDate(NewSumUiActivity.getDefaultLocale());
    }/*from w w w.  ja  v a 2 s. c o m*/
    // get the value of the TopicIDs list size (to use in swipe)
    saTopicIDsLength = saTopicIDs.length;
    final TextView title = (TextView) findViewById(R.id.title);
    // Fill topic spinner
    final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, saTopicTitles);

    final TextView tx = (TextView) findViewById(R.id.textView1);
    //      final float minm = tx.getTextSize();
    //      final float maxm = (minm + 24);

    // Get active topic
    int iTopicNum;
    // If we have returned from a pause
    if (iPrvSelectedItem >= 0)
        // use previous selection before pause
        iTopicNum = iPrvSelectedItem;
    // else
    else
        // use selection from topic page
        iTopicNum = extras.getInt(TOPIC_ID_INTENT_VAR);
    final int num = iTopicNum;

    // create an invisible spinner just to control the summaries of the
    // category (i will use it later on Swipe)
    final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            spinner.setAdapter(adapter);

            // Scroll view init
            final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
            final String[] saTopicTitlesArg = saTopicTitles;
            final String[] saTopicIDsArg = saTopicIDs;
            final String[] SaTopicDatesArg = saTopicDates;

            // Add selection event
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    // Changing summary
                    loading = true;
                    showWaitingDialog();
                    // Update visibility of rating bar
                    final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar);
                    rb.setRating(0.0f);
                    rb.setVisibility(View.VISIBLE);
                    final TextView rateLbl = (TextView) findViewById(R.id.rateLbl);
                    rateLbl.setVisibility(View.VISIBLE);
                    scroll.scrollTo(0, 0);

                    String UserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

                    String[] saTopicIDs = saTopicIDsArg;

                    // track summary views per category and topic title
                    if (getAnalyticsPref()) {
                        EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, Category,
                                saTopicTitlesArg[arg2], 0l);
                    }

                    if (sCustomCategory.trim().length() > 0) {
                        if (Category.equals(sCustomCategory)) {
                            Context ctxCur = NewSumUiActivity.getAppContext(ViewActivity.this);
                            String sCustomCategoryURL = ctxCur.getResources()
                                    .getString(R.string.custom_category_url);
                            // Check if specific element needs to be read
                            String sElementID = ctxCur.getResources()
                                    .getString(R.string.custom_category_elementId);
                            // If an element needs to be selected
                            if (sElementID.trim().length() > 0) {
                                try {
                                    // Check if specific element needs to be read
                                    String sViewOriginalPage = ctxCur.getResources()
                                            .getString(R.string.custom_category_visit_source);
                                    // Init text by a link to the original page
                                    sText = "<p><a href='" + sCustomCategoryURL + "'>" + sViewOriginalPage
                                            + "</a></p>";
                                    // Get document
                                    Document doc = Jsoup.connect(sCustomCategoryURL).get();
                                    // If a table
                                    Element eCur = doc.getElementById(sElementID);
                                    if (eCur.tagName().equalsIgnoreCase("table")) {
                                        // Get table rows
                                        Elements eRows = eCur.select("tr");

                                        // For each row
                                        StringBuffer sTextBuf = new StringBuffer();
                                        for (Element eCurRow : eRows) {
                                            // Append content
                                            // TODO: Use HTML if possible. Now problematic (crashes when we click on link)
                                            sTextBuf.append("<p>" + eCurRow.text() + "</p>");
                                        }
                                        // Return as string
                                        sText = sText + sTextBuf.toString();
                                    } else
                                        // else get text
                                        sText = eCur.text();

                                } catch (IOException e) {
                                    // Show unavailable text
                                    sText = ctxCur.getResources()
                                            .getString(R.string.custom_category_unavailable);
                                    e.printStackTrace();
                                }

                            } else
                                sText = Utils.getFromHttp(sCustomCategoryURL, false);
                        }

                    } else {
                        // call getSummary with (sTopicID, sUserSources). Use "All" for
                        // all Sources
                        String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources);
                        // check if Summary exists, otherwise display message
                        if (Summary.length == 0) { // DONE APPLICATION HANGS, DOES NOT
                            // WORK. Updated: Probably OK
                            nothingFound = true;
                            AlertDialog.Builder al = new AlertDialog.Builder(ViewActivity.this);
                            al.setMessage(R.string.shouldReloadSummaries);
                            al.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // Reset cache
                                    CacheController.clearCache();
                                    // Restart main activity
                                    startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class)
                                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                                }
                            });
                            al.setCancelable(false);
                            al.show();
                            // Return to home activity
                            loading = false;
                            return;
                        }
                        // Generate Summary text for normal categories
                        sText = generateSummaryText(Summary, ViewActivity.this);
                        pText = generatesummarypost(Summary, ViewActivity.this);
                    }

                    // Update HTML
                    tx.setText(Html.fromHtml(sText));
                    // Allow links to be followed into browser
                    tx.setMovementMethod(LinkMovementMethod.getInstance());
                    // Also Add Date to Topic Title inside Summary
                    title.setText(saTopicTitlesArg[arg2] + " : " + SaTopicDatesArg[arg2]);

                    // Update size
                    updateTextSize();

                    // Update visited topics
                    TopicActivity.addVisitedTopicID(saTopicIDs[arg2]);
                    // Done
                    loading = false;
                    closeWaitingDialog();
                }

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

            });

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // Get active topic
                    spinner.setSelection(num);
                }
            });

        }
    });

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            showHelpDialog();
        }
    });

    closeWaitingDialog();
}