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:com.near.chimerarevo.fragments.ProductsListFragment.java

private void setSpinnerValues(Spinner sp, String result) {
    SharedPreferences prefs = getActivity().getSharedPreferences("chimerarevo", Context.MODE_PRIVATE);

    if (sp.getId() == R.id.brand_spinner) {
        try {//from ww  w.  j av  a  2s .  c om
            JSONObject jObj = new JSONObject(result);
            JSONArray jArr = jObj.getJSONArray(Constants.KEY_BRANDS);
            prefs.edit().putString("brands_array", result).apply();

            brandsList.add(getResources().getString(R.string.text_brands_all));
            for (int i = 0; i < jArr.length(); i++) {
                brandsList.add(jArr.getString(i));
            }

            sp.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item,
                    brandsList));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else if (sp.getId() == R.id.category_spinner) {
        try {
            JSONObject jObj = new JSONObject(result);
            JSONArray jArr = jObj.getJSONArray(Constants.KEY_CAT);
            prefs.edit().putString("category_array", result).apply();

            catList.add(getResources().getString(R.string.text_categories_all));
            for (int i = 0; i < jArr.length(); i++) {
                JSONObject jCat = jArr.getJSONObject(i);
                catList.add(jCat.getString(Constants.KEY_NAME));
                catIdList.add(jCat.getInt(Constants.KEY_ID));
            }

            sp.setAdapter(
                    new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, catList));

            OkHttpUtils.getInstance()
                    .newCall(new Request.Builder().tag(FRAGMENT_TAG).url(Constants.BRANDS_URL).build())
                    .enqueue(new GetSpinnerCallback(mBrand));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

From source file:com.vkassin.mtrade.Common.java

public static void putOrder(final Context ctx, Quote quote) {

    final Instrument it = Common.selectedInstrument;// adapter.getItem(selectedRowId);

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.order_dialog);
    dialog.setTitle(R.string.OrderDialogTitle);

    datetxt = (EditText) dialog.findViewById(R.id.expdateedit);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date dat1 = new Date();
    datetxt.setText(sdf.format(dat1));//from w  ww. j  av  a  2  s.  c  om
    mYear = dat1.getYear() + 1900;
    mMonth = dat1.getMonth();
    mDay = dat1.getDate();
    final Date dat = new GregorianCalendar(mYear, mMonth, mDay).getTime();

    datetxt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i(TAG, "Show DatePickerDialog");
            DatePickerDialog dpd = new DatePickerDialog(ctx, mDateSetListener, mYear, mMonth, mDay);
            dpd.show();
        }
    });

    TextView itext = (TextView) dialog.findViewById(R.id.instrtext);
    itext.setText(it.symbol);

    final Spinner aspinner = (Spinner) dialog.findViewById(R.id.acc_spinner);
    List<String> list = new ArrayList<String>(Common.getAccountList());
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Common.app_ctx,
            android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
    aspinner.setAdapter(dataAdapter);

    final EditText pricetxt = (EditText) dialog.findViewById(R.id.priceedit);
    final EditText quanttxt = (EditText) dialog.findViewById(R.id.quantedit);

    final Button buttonpm = (Button) dialog.findViewById(R.id.buttonPriceMinus);
    buttonpm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                double price = Double.valueOf(pricetxt.getText().toString());
                price -= 0.01;
                if (price < 0)
                    price = 0;
                pricetxt.setText(twoDForm.format(price));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonpp = (Button) dialog.findViewById(R.id.buttonPricePlus);
    buttonpp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                double price = Double.valueOf(pricetxt.getText().toString());
                price += 0.01;
                pricetxt.setText(twoDForm.format(price));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonqm = (Button) dialog.findViewById(R.id.buttonQtyMinus);
    buttonqm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                long qty = Long.valueOf(quanttxt.getText().toString());
                qty -= 1;
                if (qty < 0)
                    qty = 0;
                quanttxt.setText(String.valueOf(qty));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final Button buttonqp = (Button) dialog.findViewById(R.id.buttonQtyPlus);
    buttonqp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            try {

                long qty = Long.valueOf(quanttxt.getText().toString());
                qty += 1;
                quanttxt.setText(String.valueOf(qty));

            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
            }
        }
    });

    final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.radio0);
    final RadioButton bu1 = (RadioButton) dialog.findViewById(R.id.radio1);

    if (quote != null) {

        // pricetxt.setText(quote.price.toString());
        pricetxt.setText(quote.getPriceS());
        if (quote.qtyBuy > 0) {

            quanttxt.setText(quote.qtyBuy.toString());
            bu1.setChecked(true);
            bu0.setChecked(false);

        } else {

            quanttxt.setText(quote.qtySell.toString());
            bu1.setChecked(false);
            bu0.setChecked(true);

        }
    }

    Button customDialog_Cancel = (Button) dialog.findViewById(R.id.cancelbutt);
    customDialog_Cancel.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.dismiss();
        }

    });

    Button customDialog_Put = (Button) dialog.findViewById(R.id.putorder);
    customDialog_Put.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            Double price = new Double(0);
            Long qval = new Long(0);

            try {

                price = Double.valueOf(pricetxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
                return;
            }
            try {

                qval = Long.valueOf(quanttxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
                return;
            }

            if (dat.compareTo(new GregorianCalendar(mYear, mMonth, mDay).getTime()) > 0) {

                Toast.makeText(ctx, R.string.CorrectDate, Toast.LENGTH_SHORT).show();

                return;

            }

            JSONObject msg = new JSONObject();
            try {

                msg.put("objType", Common.CREATE_REMOVE_ORDER);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("device", "Android");
                msg.put("instrumId", Long.valueOf(it.id));
                msg.put("price", price);
                msg.put("qty", qval);
                msg.put("ordType", 1);
                msg.put("side", bu0.isChecked() ? 0 : 1);
                msg.put("code", String.valueOf(aspinner.getSelectedItem()));
                msg.put("orderNum", ++ordernum);
                msg.put("action", "CREATE");
                boolean b = (((mYear - 1900) == dat.getYear()) && (mMonth == dat.getMonth())
                        && (mDay == dat.getDate()));
                if (!b)
                    msg.put("expired", String.format("%02d.%02d.%04d", mDay, mMonth + 1, mYear));

                if (isSSL) {

                    //                ? ?:    newOrder-orderNum-instrumId-side-price-qty-code-ordType
                    //               :                  newOrder-16807-20594623-0-1150-13-1027700451-1
                    String forsign = "newOrder-" + ordernum + "-" + msg.getString("instrumId") + "-"
                            + msg.getString("side") + "-"
                            + JSONObject.numberToString(Double.valueOf(msg.getDouble("price"))) + "-"
                            + msg.getString("qty") + "-" + msg.getString("code") + "-"
                            + msg.getString("ordType");
                    byte[] signed = Common.signText(Common.signProfile, forsign.getBytes(), true);
                    String gsign = Base64.encodeToString(signed, Base64.DEFAULT);
                    msg.put("gostSign", gsign);
                }
                mainActivity.writeJSONMsg(msg);

            } catch (Exception e) {

                e.printStackTrace();
                Log.e(TAG, "Error! Cannot create JSON order object", e);
            }

            dialog.dismiss();
        }

    });

    dialog.show();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(dialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.FILL_PARENT;
    lp.height = WindowManager.LayoutParams.FILL_PARENT;
    dialog.getWindow().setAttributes(lp);

}

From source file:com.vexigon.libraries.onboarding.ui.fragments.SelfSelectFragment.java

@SuppressWarnings("ConstantConditions")
@Override/* ww  w. j a v  a  2 s .  c  o  m*/
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Fragment view containers
    LinearLayout userView = getView().findViewById(R.id.userScreenView);
    LinearLayout selectionView = getView().findViewById(R.id.selectionScreenView);

    // Fragment 1 views
    ImageView userScreenImage = getView().findViewById(R.id.userScreenImage);
    final Spinner userDropdown = getView().findViewById(R.id.userScreenDropdown);
    final Button confirmButton = getView().findViewById(R.id.userScreenConfirmButton);

    // Fragment 2 views
    TextView selectionViewTitle = getView().findViewById(R.id.selectionScreenTitle);
    TextView selectionViewSubtitle = getView().findViewById(R.id.selectionScreenSubtitle);
    selfSelectItems = getView().findViewById(R.id.selectionScreenItems);
    selfSelectGridItems = getView().findViewById(R.id.selectionScreenGridItems);

    switch (position) {
    case 0:
        userView.setVisibility(View.VISIBLE);

        Glide.with(getActivity()).load(getUserScreenImage(position)).dontAnimate().into(userScreenImage);

        userDropdown.setAdapter(new CustomUserAdapter(getLoggedInUsers()));
        userDropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                confirmButton.setText("Continue as " + ((User) userDropdown.getSelectedItem()).getName());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                confirmButton.setText("Continue as " + ((User) userDropdown.getSelectedItem()).getName());
            }
        });

        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((SelfSelectActivity) getActivity()).viewPager.setCurrentItem(1, true);
            }
        });
        break;
    case 1:
        selectionView.setVisibility(View.VISIBLE);

        selectionViewTitle.setText(getSelfSelectTitle());
        selectionViewSubtitle.setText(getSelfSelectSubtitle());

        configureSelfSelectionList();
        break;
    }
}

From source file:nf.frex.android.FrexActivity.java

private void prepareDecorationsDialog(final Dialog dialog) {
    final Registry<DistanceFunction> distanceFunctions = Registries.distanceFunctions;
    int checkedIndex = distanceFunctions.getIndex(view.getDistanceFunctionId());

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            distanceFunctions.getIds());
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    final Spinner distanceFunctionSpinner = (Spinner) dialog.findViewById(R.id.distance_function_spinner);
    distanceFunctionSpinner.setAdapter(arrayAdapter);
    distanceFunctionSpinner.setSelection(checkedIndex, false);

    final SeekBarConfigurer dilationSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.dilation_seek_bar), -3.0, 1.0, true, view.getDistanceDilation());
    final SeekBarConfigurer translateXSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.transl_x_seek_bar), -2.5, 2.5, false,
            view.getDistanceTranslateX());
    final SeekBarConfigurer translateYSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.transl_y_seek_bar), -2.5, 2.5, false,
            view.getDistanceTranslateY());

    final CheckBox turbulenceCheckBox = (CheckBox) dialog.findViewById(R.id.turbulence);
    turbulenceCheckBox.setChecked(view.getGeneratorConfig().isTurbulenceEnabled());

    final SeekBarConfigurer turbIntensSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.turb_intens_seek_bar), -1.0, 1.0, true,
            view.getGeneratorConfig().getTurbulenceIntensity());
    final SeekBarConfigurer turbScaleSeekBarConfigurer = SeekBarConfigurer.create(
            (SeekBar) dialog.findViewById(R.id.turb_scale_seek_bar), -1.0, 1.0, true,
            view.getGeneratorConfig().getTurbulenceScale());

    Button randomButton = (Button) dialog.findViewById(R.id.random_button);
    randomButton.setOnClickListener(new View.OnClickListener() {
        @Override//from w  w w. j  a  v a2  s. c om
        public void onClick(View v) {
            distanceFunctionSpinner.setSelection((int) (Math.random() * distanceFunctions.getSize()));
            dilationSeekBarConfigurer.setRandomValue();
            translateXSeekBarConfigurer.setRandomValue();
            translateYSeekBarConfigurer.setRandomValue();
            if (Math.random() < 0.5) {
                turbIntensSeekBarConfigurer.setRandomValue();
                turbScaleSeekBarConfigurer.setRandomValue();
            }
        }
    });

    Button okButton = (Button) dialog.findViewById(R.id.ok_button);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int index = distanceFunctionSpinner.getSelectedItemPosition();
            dialog.dismiss();
            view.setDecoratedFractal(true);
            view.setDistanceFunctionId(distanceFunctions.getId(index));
            view.setDistanceDilation(dilationSeekBarConfigurer.getValue());
            view.setDistanceTranslateX(translateXSeekBarConfigurer.getValue());
            view.setDistanceTranslateY(translateYSeekBarConfigurer.getValue());
            view.getGeneratorConfig().setTurbulenceEnabled(turbulenceCheckBox.isChecked());
            view.getGeneratorConfig().setTurbulenceIntensity(turbIntensSeekBarConfigurer.getValue());
            view.getGeneratorConfig().setTurbulenceScale(turbScaleSeekBarConfigurer.getValue());
            view.recomputeAll();
        }
    });
    Button cancelButton = (Button) dialog.findViewById(R.id.cancel_button);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
}

From source file:com.adithya321.sharesanalysis.fragments.PurchaseShareFragment.java

private void setRecyclerViewAdapter() {
    sharesList = databaseHandler.getShares();
    purchaseList = databaseHandler.getPurchases();

    if (sharesList.size() < 1) {
        emptyTV.setVisibility(View.VISIBLE);
        arrow.setVisibility(View.VISIBLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (getResources().getConfiguration().orientation == 1) {
                arrow.setBackground(getResources().getDrawable(R.drawable.curved_line_vertical));
            } else {
                arrow.setBackground((getResources().getDrawable(R.drawable.curved_line_horizontal)));
            }// w  w  w  . j a  v a 2  s . c  o m
        }
    } else {
        emptyTV.setVisibility(View.GONE);
        arrow.setVisibility(View.GONE);
    }

    PurchaseShareAdapter purchaseAdapter = new PurchaseShareAdapter(getContext(), purchaseList);
    purchaseAdapter.setOnItemClickListener(new PurchaseShareAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            final Purchase purchase = purchaseList.get(position);

            final Dialog dialog = new Dialog(getContext());
            dialog.setTitle("Edit Share Purchase");
            dialog.setContentView(R.layout.dialog_add_share_purchase);
            dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            dialog.show();

            RadioButton newRB = (RadioButton) dialog.findViewById(R.id.radioBtn_new);
            RadioButton existingRB = (RadioButton) dialog.findViewById(R.id.radioBtn_existing);
            AutoCompleteTextView name = (AutoCompleteTextView) dialog.findViewById(R.id.share_name);
            newRB.setVisibility(View.GONE);
            existingRB.setChecked(true);
            name.setVisibility(View.GONE);

            final Spinner spinner = (Spinner) dialog.findViewById(R.id.existing_spinner);
            ArrayList<String> shares = new ArrayList<>();
            int pos = 0;
            for (int i = 0; i < sharesList.size(); i++) {
                shares.add(sharesList.get(i).getName());
                if (sharesList.get(i).getName().equals(purchase.getName()))
                    pos = i;
            }
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(),
                    android.R.layout.simple_spinner_item, shares);
            spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(spinnerAdapter);
            spinner.setSelection(pos);
            spinner.setVisibility(View.VISIBLE);

            final EditText quantity = (EditText) dialog.findViewById(R.id.no_of_shares);
            final EditText price = (EditText) dialog.findViewById(R.id.buying_price);
            quantity.setText(String.valueOf(purchase.getQuantity()));
            price.setText(String.valueOf(purchase.getPrice()));

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(purchase.getDate());
            year_start = calendar.get(Calendar.YEAR);
            month_start = calendar.get(Calendar.MONTH) + 1;
            day_start = calendar.get(Calendar.DAY_OF_MONTH);
            final Button selectDate = (Button) dialog.findViewById(R.id.select_date);
            selectDate.setText(new StringBuilder().append(day_start).append("/").append(month_start).append("/")
                    .append(year_start));
            selectDate.setOnClickListener(PurchaseShareFragment.this);

            Button addPurchaseBtn = (Button) dialog.findViewById(R.id.add_purchase_btn);
            addPurchaseBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Purchase p = new Purchase();
                    p.setId(purchase.getId());

                    String stringStartDate = year_start + " " + month_start + " " + day_start;
                    DateFormat format = new SimpleDateFormat("yyyy MM dd", Locale.ENGLISH);
                    try {
                        Date date = format.parse(stringStartDate);
                        p.setDate(date);
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "Invalid Date", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {
                        p.setQuantity(Integer.parseInt(quantity.getText().toString()));
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "Invalid Number of Shares", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {
                        p.setPrice(Double.parseDouble(price.getText().toString()));
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "Invalid Buying Price", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    p.setType("buy");
                    p.setName(spinner.getSelectedItem().toString());
                    databaseHandler.updatePurchase(p);
                    setRecyclerViewAdapter();
                    dialog.dismiss();
                }
            });
        }
    });
    sharePurchasesRecyclerView.setHasFixedSize(true);
    sharePurchasesRecyclerView.setAdapter(purchaseAdapter);
    sharePurchasesRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}

From source file:com.mifos.mifosxdroid.online.generatecollectionsheet.GenerateCollectionSheetFragment.java

private void setSpinner(Spinner spinner, List<String> values) {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
            values);/*from   ww w .  j a  v a  2 s . c om*/
    adapter.notifyDataSetChanged();
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
}

From source file:pl.wasat.smarthma.ui.frags.base.BaseCollectionDetailsFragment.java

@NonNull
private Spinner buildSpinnerView(final Parameter param) {
    Spinner spinner = new Spinner(getActivity());
    spinner.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
            TableLayout.LayoutParams.WRAP_CONTENT, 1f));
    spinner.setPadding(20, 0, 20, 0);/*from  w  w w .j  a  v a2 s .  c o  m*/

    final List<String> optList = new ArrayList<>();
    optList.add(String.format(getContext().getString(R.string.choose_osdd_param), param.getName()));
    for (Option opt : param.getOptions()) {
        optList.add(opt.getLabel());
    }

    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item_slider,
            optList);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(spinnerAdapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String optValue = "";
            if (l > 0) {
                optValue = param.getOptions().get(i - 1).getValue();
                checkParamType(param, optValue);
            }
            fedeoRequestParams.addOsddValue(param.getValue(), optValue);
        }

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

    });
    return spinner;
}

From source file:com.cmput301w17t07.moody.CreateMoodActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_mood);
    UserController userController = new UserController();
    userName = userController.readUsername(CreateMoodActivity.this).toString();
    setUpMenuBar(this);
    location = null;//from   w  w  w . j av  a 2 s. co  m
    date = new Date();
    Intent intent = getIntent();
    locationText = (TextView) findViewById(R.id.locationText);
    Description = (EditText) findViewById(R.id.Description);
    mImageView = (ImageView) findViewById(R.id.editImageView);

    //try to get picklocation, if it is equal to 1 that means, user just back from map not
    //other activities
    try {
        pickLocation = (int) intent.getExtras().getInt("pickLocation");
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (pickLocation == 1) {
        tempMood = (Mood) intent.getSerializableExtra("editMood");
        bitmap = (Bitmap) intent.getParcelableExtra("bitmapback");
        latitude = tempMood.getLatitude();
        longitude = tempMood.getLongitude();
        address = tempMood.getDisplayLocation();
        locationText.setText(address);
        Description.setText(tempMood.getMoodMessage());
        mImageView.setImageBitmap(bitmap);
        date = tempMood.getDate();
        displayAttributes();
    }

    /**
     * Spinner dropdown logic taken from http://stackoverflow.com/questions/13377361/how-to-create-a-drop-down-list <br>
     * Author: Nicolas Tyler, 2013/07/15 8:47 <br>
     * taken by Xin Huang 2017/03/10 <br>
     */
    //Spinner for emotion and socialsituatuion
    if (pickLocation == 0) {
        Spinner dropdown = (Spinner) findViewById(R.id.Emotion);

        String[] items = new String[] { "anger", "confusion", "disgust", "fear", "happiness", "sadness",
                "shame", "surprise" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, items);
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                EmotionText = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(CreateMoodActivity.this, "Please pick a feeling!", Toast.LENGTH_SHORT).show();
            }
        });

        Spinner dropdown_SocialSituation = (Spinner) findViewById(R.id.SocialSituation);
        String[] item_SocialSituation = new String[] { "", "alone", "with one other person", "with two people",
                "with several people", "with a crowd" };
        ArrayAdapter<String> adapter_SocialSituation = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_dropdown_item, item_SocialSituation);
        dropdown_SocialSituation.setAdapter(adapter_SocialSituation);

        dropdown_SocialSituation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                SocialSituation = parent.getItemAtPosition(position).toString();
                TextView sizeView = (TextView) findViewById(R.id.SocialText);
                sizeView.setText("  " + SocialSituation);
            }

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

    ImageButton chooseButton = (ImageButton) findViewById(R.id.Camera);

    ImageButton locationButton = (ImageButton) findViewById(R.id.location);

    ImageButton PickerButton = (ImageButton) findViewById(R.id.Picker);

    //click on PickerButton, call the datetimePicker
    PickerButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            innit();
            TimeDialog.show();
        }
    });

    chooseButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, 1);
            } catch (Exception e) {
                Intent intent = new Intent(getApplicationContext(), CreateMoodActivity.class);
                startActivity(intent);
            }
        }
    });

    chooseButton.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            try {
                Intent intent = new Intent("android.intent.action.PICK");
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            } catch (Exception e) {
                Intent intent = new Intent(getApplicationContext(), CreateMoodActivity.class);
                startActivity(intent);
            }
            return true;
        }
    });

    locationButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            //check available tools
            List<String> locationList = locationManager.getProviders(true);
            if (locationList.contains(LocationManager.GPS_PROVIDER)) {
                provider = LocationManager.GPS_PROVIDER;
            } else if (locationList.contains(LocationManager.NETWORK_PROVIDER)) {
                provider = LocationManager.NETWORK_PROVIDER;
            } else {
                Toast.makeText(getApplicationContext(), "Please check application permissions",
                        Toast.LENGTH_LONG).show();
            }

            //check the permission
            if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getApplicationContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                Toast.makeText(getApplicationContext(), "Get location failed, Please check the Permission",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            location = locationManager.getLastKnownLocation(provider);
            if (location == null) {
                latitude = 0;
                longitude = 0;
            } else {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }

            Geocoder gcd = new Geocoder(CreateMoodActivity.this, Locale.getDefault());
            try {
                List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
                if (addresses.size() > 0)
                    address = "  " + addresses.get(0).getFeatureName() + " "
                            + addresses.get(0).getThoroughfare() + ", " + addresses.get(0).getLocality() + ", "
                            + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryCode();
                locationText.setText(address);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    //pass users' changes to map, will be passed back
    locationButton.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            int fromCreate = 123;
            moodMessage_text = Description.getText().toString();
            tempMood = new Mood(EmotionText, userName, moodMessage_text, latitude, longitude, null,
                    SocialSituation, date, address);
            Intent editLocation = new Intent(CreateMoodActivity.this, EditLocation.class);
            editLocation.putExtra("EditMood", tempMood);
            editLocation.putExtra("fromCreate", fromCreate);
            editLocation.putExtra("bitmap", compress(bitmap));
            startActivity(editLocation);
            return true;
        }
    });

    Button submitButton = (Button) findViewById(R.id.button5);
    submitButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            moodMessage_text = Description.getText().toString();
            MoodController moodController = new MoodController();

            // --------------------------- achievements -------------------------------------
            AchievementManager.initManager(CreateMoodActivity.this);
            AchievementController achievementController = new AchievementController();
            achievements = achievementController.getAchievements();
            achievements.moodCount += 1;
            achievementController.incrementMoodCounter(EmotionText);
            achievementController.saveAchievements();
            // ------------------------------------------------------------------------------
            if (location != null || pickLocation == 1) {
                //todo can remove these if/else statements that toast message too long. They could
                // be handled in the controller
                if (!MoodController.createMood(EmotionText, userName, moodMessage_text, latitude, longitude,
                        bitmap, SocialSituation, date, address, CreateMoodActivity.this)) {
                    Toast.makeText(CreateMoodActivity.this,
                            "Mood message length is too long. Please try again.", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(CreateMoodActivity.this, TimelineActivity.class);
                    startActivity(intent);
                    finish();
                }
            } else {
                if (!MoodController.createMood(EmotionText, userName, moodMessage_text, 0, 0, bitmap,
                        SocialSituation, date, address, CreateMoodActivity.this)) {
                    Toast.makeText(CreateMoodActivity.this,
                            "Mood message length is too long. Please try again.", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(CreateMoodActivity.this, TimelineActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        }
    });
}

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

private void setViews() {

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

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

    for (RecType type : RecType.values()) {
        if (type == RecType.DONT || type == RecType.OVERRIDE)
            continue;
        typeAdapter.add(type.msg());//from  w  w  w.ja v  a2 s  .c om
    }

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

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

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

    });

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

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

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

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

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

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

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

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

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

}

From source file:nf.frex.android.FrexActivity.java

private void prepareColorsDialog(final Dialog dialog) {

    //Log.d(TAG, "prepareColorsDialog() entered");

    getColorSchemes();/*from  w w w  . j a  v  a  2  s .com*/

    //Log.d(TAG, "prepareColorsDialog: new bitmaps are being created");
    Bitmap[] colorSchemeIcons = new Bitmap[colorSchemes.getSize()];
    for (int i = 0; i < colorSchemeIcons.length; i++) {
        ColorScheme colorScheme = colorSchemes.getValue(i);
        colorSchemeIcons[i] = colorScheme.getGradientIcon();
    }

    int checkedIndex = Registries.colorSchemes.getIndex(view.getColorSchemeId());
    //Log.d(TAG, "prepareColorsDialog: checkedIndex = " + checkedIndex);
    final Spinner colorTableSpinner = (Spinner) dialog.findViewById(R.id.color_table_spinner);
    colorTableSpinner.setAdapter(new ImageArrayAdapter(this, 0, colorSchemeIcons));
    colorTableSpinner.setSelection(checkedIndex, false);
    colorTableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View spinnerView, int position, long id) {
            view.setColorSchemeId(Registries.colorSchemes.getId(position));
            view.setColorScheme(Registries.colorSchemes.getValue(position));
            view.recomputeColors();
        }

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

    final SeekBar colorFactorSeekBar = (SeekBar) dialog.findViewById(R.id.color_gain_seek_bar);
    final double colorFactorMin = -3.0;
    final double colorFactorMax = 2.0;
    final SeekBarConfigurer colorFactorSeekBarConfigurer = SeekBarConfigurer.create(colorFactorSeekBar,
            colorFactorMin, colorFactorMax, true, view.getColorGain());
    colorFactorSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            view.setColorGain((float) colorFactorSeekBarConfigurer.getValue());
            view.recomputeColors();
        }
    });

    final SeekBar colorBiasSeekBar = (SeekBar) dialog.findViewById(R.id.color_offset_seek_bar);
    final double colorBiasMin = 0;
    final double colorBiasMax = 1024;
    final SeekBarConfigurer colorBiasSeekBarConfigurer = SeekBarConfigurer.create(colorBiasSeekBar,
            colorBiasMin, colorBiasMax, false, view.getColorOffset());
    colorBiasSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            view.setColorOffset((float) colorBiasSeekBarConfigurer.getValue());
            view.recomputeColors();
        }
    });

    final CheckBox colorRepeatCheckBox = (CheckBox) dialog.findViewById(R.id.color_repeat);
    colorRepeatCheckBox.setChecked(view.isColorRepeat());
    colorRepeatCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            view.setColorRepeat(isChecked);
            view.recomputeColors();
        }
    });

    Button randomButton = (Button) dialog.findViewById(R.id.random_button);
    randomButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            colorTableSpinner.setSelection((int) (Math.random() * colorSchemes.getSize()));
            colorFactorSeekBarConfigurer.setRandomValue();
            colorBiasSeekBarConfigurer.setRandomValue();
            view.recomputeColors();
        }
    });

    Button getPalFromImgButton = (Button) dialog.findViewById(R.id.get_pal_from_img_button);
    getPalFromImgButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            dialog.dismiss();
            startActivityForResult(photoPickerIntent, SELECT_PICTURE_REQUEST_CODE);
        }
    });

    //Log.d(TAG, "prepareColorsDialog() exited");
}