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.survivingwithandroid.accountnavigationdrawer.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String[] itmes = getResources().getStringArray(R.array.items_array);

    frame = (FrameLayout) findViewById(R.id.content_frame);

    Spinner spinner = (Spinner) findViewById(R.id.spinnerAccount);

    String[] items = new String[] { "item1", "item2", "item3" };

    AccountManager accMgr = AccountManager.get(this);

    Account[] accountList = accMgr.getAccounts();
    final String[] accountNames = new String[accountList.length + 1];
    int i = 1;/*from   w w w.j a  va  2 s.c o m*/
    accountNames[0] = getResources().getString(R.string.infospinner);

    for (Account account : accountList) {
        String name = account.name;
        accountNames[i++] = name;
    }

    ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            accountNames);
    spinner.setAdapter(adp);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            System.out.println("Pos [" + position + "]");
            if (position == 0)
                return;

            String currentAccount = accountNames[position];
            credential = GoogleAccountCredential.usingOAuth2(MainActivity.this, DriveScopes.DRIVE);
            credential.setSelectedAccountName(currentAccount);
            service = getDriveService(credential);
            AsyncAuth auth = new AsyncAuth();
            auth.execute("");
        }

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

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, itmes));

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);
    // We should handle actionbar event correctly
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void ShowTaskDialog(Task task, OnClickListener okListener) {
    LayoutInflater inflater = this.getLayoutInflater();
    View dlgView = inflater.inflate(R.layout.dialog_task, null);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(dlgView);//from   w  w w  .ja v  a  2 s  .  co m
    builder.setTitle("Task");

    final TextView nameEdit = (TextView) dlgView.findViewById(R.id.task_name_edit);
    nameEdit.setText(task.mName);
    final TextView descriptionEdit = (TextView) dlgView.findViewById(R.id.task_description_edit);
    descriptionEdit.setText(task.mDescription);
    final TextView dueDateView = (TextView) dlgView.findViewById(R.id.task_due_date);
    SetFriendlyDueDateText(dueDateView, task.mDueDate);
    Button dueDateButton = (Button) dlgView.findViewById(R.id.task_due_date_choose);
    final Calendar dueDate = task.mDueDate;
    final Task thisTask = task;
    dueDateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ShowDueDateDialog(dueDate, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int id) {
                    Dialog dlg = (Dialog) dialogInterface;
                    DatePicker datePicker = (DatePicker) dlg.findViewById(R.id.due_date_calendar);
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
                    thisTask.mDueDate = calendar;
                    SetFriendlyDueDateText(dueDateView, thisTask.mDueDate);
                }
            });
        }
    });

    final CheckBox repeatCheck = (CheckBox) dlgView.findViewById(R.id.repeat);
    repeatCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            View dialog = (View) buttonView.getParent();
            SetRepeatVisibility(dialog, isChecked);
        }
    });

    Boolean repeat = task.mRepeatUnit != Task.RepeatUnit.NONE;
    repeatCheck.setChecked(repeat);
    SetRepeatVisibility(dlgView, repeat);

    final EditText repeatTimeEdit = (EditText) dlgView.findViewById(R.id.repeat_time);
    repeatTimeEdit.setText(Integer.toString(task.mRepeatTime));

    final Spinner repeatUnitSpinner = (Spinner) dlgView.findViewById(R.id.repeat_unit);
    String[] repeatUnits = { "Days", "Weeks", "Months", "Years" };
    repeatUnitSpinner
            .setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, repeatUnits));
    int repeatUnitPos = 0;
    switch (task.mRepeatUnit) {
    case DAYS:
        repeatUnitPos = 0;
        break;
    case WEEKS:
        repeatUnitPos = 1;
        break;
    case MONTHS:
        repeatUnitPos = 2;
        break;
    case YEARS:
        repeatUnitPos = 3;
        break;
    case NONE:
        repeatUnitPos = 0;
    }
    repeatUnitSpinner.setSelection(repeatUnitPos);

    final RadioButton repeatFromComplete = (RadioButton) dlgView.findViewById(R.id.repeat_from_complete);
    final RadioButton repeatFromDue = (RadioButton) dlgView.findViewById(R.id.repeat_from_due);
    if (task.mRepeatFromComplete) {
        repeatFromComplete.setChecked(true);
    } else {
        repeatFromDue.setChecked(true);
    }

    // Here's a trick:  We cascade the OnClick listeners so we can extract
    // the dialog contents into the task before calling the second listener.
    final OnClickListener userListener = okListener;
    final Task myTask = task;
    OnClickListener cascadedListener = new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            myTask.mName = nameEdit.getText().toString();
            myTask.mDescription = descriptionEdit.getText().toString();

            myTask.mRepeatUnit = Task.RepeatUnit.NONE;
            if (repeatCheck.isChecked()) {
                switch (repeatUnitSpinner.getSelectedItemPosition()) {
                case 0:
                    myTask.mRepeatUnit = Task.RepeatUnit.DAYS;
                    break;
                case 1:
                    myTask.mRepeatUnit = Task.RepeatUnit.WEEKS;
                    break;
                case 2:
                    myTask.mRepeatUnit = Task.RepeatUnit.MONTHS;
                    break;
                case 3:
                    myTask.mRepeatUnit = Task.RepeatUnit.YEARS;
                    break;
                }

                myTask.mRepeatTime = Integer.parseInt(repeatTimeEdit.getText().toString());
                myTask.mRepeatFromComplete = repeatFromComplete.isChecked();
            }

            userListener.onClick(dialog, which);
        }
    };

    builder.setNegativeButton("Cancel", null);
    builder.setPositiveButton("OK", cascadedListener);

    builder.show();
}

From source file:org.sufficientlysecure.keychain.ui.SafeSlingerActivity.java

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

    setContentView(R.layout.safe_slinger_activity);

    mMasterKeyId = getIntent().getLongExtra(EXTRA_MASTER_KEY_ID, 0);

    // NOTE: there are two versions of this layout, for API >= 11 and one for < 11
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        NumberPicker picker = (NumberPicker) findViewById(R.id.safe_slinger_picker);
        picker.setMinValue(2);//from   w w w .j a v a 2s  .  c o  m
        picker.setMaxValue(10);
        picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                mSelectedNumber = newVal;
            }
        });
    } else {
        Spinner spinner = (Spinner) findViewById(R.id.safe_slinger_spinner);

        List<String> list = new ArrayList<String>();
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");
        list.add("7");
        list.add("8");
        list.add("9");
        list.add("10");

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mSelectedNumber = position + 2;
            }

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

            }
        });
    }

    ImageView buttonIcon = (ImageView) findViewById(R.id.safe_slinger_button_image);
    buttonIcon.setColorFilter(getResources().getColor(R.color.tertiary_text_light), PorterDuff.Mode.SRC_IN);

    View button = findViewById(R.id.safe_slinger_button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startExchange(mMasterKeyId, mSelectedNumber);
        }
    });
}

From source file:org.thialfihar.android.apg.ui.dialog.CreateKeyDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final FragmentActivity context = getActivity();
    final LayoutInflater mInflater;

    final int childCount = getArguments().getInt(ARG_EDITOR_CHILD_COUNT);
    mInflater = context.getLayoutInflater();

    AlertDialog.Builder dialog = new AlertDialog.Builder(context);

    View view = mInflater.inflate(R.layout.create_key_dialog, null);
    dialog.setView(view);//from   www .  ja  v  a2  s . co  m
    dialog.setTitle(R.string.title_create_key);

    boolean wouldBeMasterKey = (childCount == 0);

    final Spinner algorithm = (Spinner) view.findViewById(R.id.create_key_algorithm);
    ArrayList<Choice> choices = new ArrayList<Choice>();
    choices.add(new Choice(Id.choice.algorithm.dsa, getResources().getString(R.string.dsa)));
    if (!wouldBeMasterKey) {
        choices.add(new Choice(Id.choice.algorithm.elgamal, getResources().getString(R.string.elgamal)));
    }

    choices.add(new Choice(Id.choice.algorithm.rsa, getResources().getString(R.string.rsa)));

    ArrayAdapter<Choice> adapter = new ArrayAdapter<Choice>(context, android.R.layout.simple_spinner_item,
            choices);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    algorithm.setAdapter(adapter);
    // make RSA the default
    for (int i = 0; i < choices.size(); ++i) {
        if (choices.get(i).getId() == Id.choice.algorithm.rsa) {
            algorithm.setSelection(i);
            break;
        }
    }

    final Spinner keySize = (Spinner) view.findViewById(R.id.create_key_size);
    ArrayAdapter<CharSequence> keySizeAdapter = ArrayAdapter.createFromResource(context,
            R.array.key_size_spinner_values, android.R.layout.simple_spinner_item);
    keySizeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    keySize.setAdapter(keySizeAdapter);
    keySize.setSelection(3); // Default to 4096 for the key length
    dialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface di, int id) {
            di.dismiss();
            try {
                int nKeyIndex = keySize.getSelectedItemPosition();
                switch (nKeyIndex) {
                case 0:
                    mNewKeySize = 512;
                    break;
                case 1:
                    mNewKeySize = 1024;
                    break;
                case 2:
                    mNewKeySize = 2048;
                    break;
                case 3:
                    mNewKeySize = 4096;
                    break;
                }
            } catch (NumberFormatException e) {
                mNewKeySize = 0;
            }

            mNewKeyAlgorithmChoice = (Choice) algorithm.getSelectedItem();
            mAlgorithmSelectedListener.onAlgorithmSelected(mNewKeyAlgorithmChoice, mNewKeySize);
        }
    });

    dialog.setCancelable(true);
    dialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface di, int id) {
            di.dismiss();
        }
    });

    return dialog.create();
}

From source file:com.anton.gavel.GavelMain.java

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

    setContentView(R.layout.activity_gavel_main);

    // set up edit text input style for complaints (multiline, capitalize sentences)
    EditText edit = (EditText) findViewById(R.id.complaint_body);
    edit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
            | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
    // set up cities spinner
    Spinner citiesSpinner = (Spinner) findViewById(R.id.cities_spinner);
    ArrayAdapter<CharSequence> citiesAdapter = ArrayAdapter.createFromResource(this, R.array.cities,
            android.R.layout.simple_spinner_item);
    citiesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    citiesSpinner.setAdapter(citiesAdapter);

    // set up complaints map
    List<String> standardComplaints = this.getStandardComplaints();
    List<String> complaintSubmitValues = this.getComplaintSubmitValues();

    Iterator<String> standard = standardComplaints.iterator();
    Iterator<String> submit = complaintSubmitValues.iterator();
    complaintsMap = new HashMap<String, String>();
    //standard.next(); submit.next(); //skip the first item 'select a complaint'
    while (standard.hasNext() && submit.hasNext())
        complaintsMap.put(standard.next().toString(), submit.next().toString());

    // set up complaint spinner
    List<String> complaints_list = this.getStandardComplaints();
    complaintSpinner = (Spinner) findViewById(R.id.complaint_spinner);
    complaintsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
            complaints_list);/* w  ww .ja  v a2  s .co  m*/
    complaintsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    complaintSpinner.setAdapter(complaintsAdapter);
    complaintSpinner.setOnItemSelectedListener(this);
    complaintSpinner.setOnItemLongClickListener(this);// this doesn't actually work yet bc not supported by API - events don't get fired

    //attach location listener to button
    findViewById(R.id.location_button).setOnClickListener(this);

    // make link in disclaimer clickable
    TextView disclaimer = (TextView) findViewById(R.id.disclaimer_textview);
    disclaimer.setMovementMethod(LinkMovementMethod.getInstance());

    // check &or load shared preferences to populate saved personal information
    mPersonalInfo = new PersonalInfo();
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    mPersonalInfo.loadFromPreferences(preferences);

    // suppress keyboard
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    // set complaint location to multiline for large layouts
    if (findViewById(R.id.layout_large_land) != null || findViewById(R.id.layout_large) != null) {
        ((EditText) findViewById(R.id.complaint_address)).setInputType(InputType.TYPE_CLASS_TEXT
                | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
    }

}

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

/**
 * load spinner from jsonarray/*from   ww w.j a va 2  s .  co m*/
 * @throws JSONException 
 */

public void loadCitiesFromJsonArray(Spinner dropdown) throws JSONException {

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

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

    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:com.example.drugsformarinemammals.Combined_Search.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.combined_search);
    helper = new Handler_Sqlite(this);
    userEntryAnatomicalTarget = "";
    userEntryTherapeuticTarget = "";
    userEntryAnimalTarget = "";
    TextView title = (TextView) findViewById(R.id.CombinedSearch);
    title.setTypeface(Typeface.SANS_SERIF);
    Button go = (Button) findViewById(R.id.goButton);
    go.setTypeface(Typeface.SANS_SERIF);
    go.setOnClickListener(new OnClickListener() {

        @Override//from  w ww  .  ja  v a 2  s.c  om
        public void onClick(View v) {
            userEntryTherapeuticTarget = actv.getText().toString();
            search();
        }

    });

    Spinner spinnerAnatomicalTarget = (Spinner) findViewById(R.id.SpinAnatomicalTarget);
    SpinnerAdapter adapterAnatomicalTarget = new SpinnerAdapter(this, R.layout.item_spinner,
            Arrays.asList(getResources().getStringArray(R.array.AnatomicalTarget)));
    adapterAnatomicalTarget.setDropDownViewResource(R.layout.spinner_dropdown_item);
    spinnerAnatomicalTarget.setAdapter(adapterAnatomicalTarget);
    spinnerAnatomicalTarget.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
            userEntryAnatomicalTarget = parent.getSelectedItem().toString();
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });

    String[] urls = { "http://formmulary.tk/Android/getTherapeuticGroups.php" };
    new GetTherapeuticGroups(this).execute(urls);
    Spinner spinnerAnimals = (Spinner) findViewById(R.id.SpinAnimals);
    SpinnerAdapter adapterAnimals = new SpinnerAdapter(this, R.layout.item_spinner,
            Arrays.asList(getResources().getStringArray(R.array.Animals)));
    adapterAnimals.setDropDownViewResource(R.layout.spinner_dropdown_item);
    spinnerAnimals.setAdapter(adapterAnimals);

    spinnerAnimals.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View arg1, int arg2, long arg3) {
            userEntryAnimalTarget = parent.getSelectedItem().toString();
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });

}

From source file:com.app.blockydemo.content.bricks.ChangeVariableBrick.java

@Override
public View getPrototypeView(Context context) {
    View prototypeView = View.inflate(context, R.layout.brick_change_variable_by, null);
    Spinner variableSpinner = (Spinner) prototypeView.findViewById(R.id.change_variable_spinner);
    variableSpinner.setFocusableInTouchMode(false);
    variableSpinner.setFocusable(false);
    UserVariableAdapter changeVariableSpinnerAdapter = ProjectManager.getInstance().getCurrentProject()
            .getUserVariables().createUserVariableAdapter(context, sprite);

    UserVariableAdapterWrapper userVariableAdapterWrapper = new UserVariableAdapterWrapper(context,
            changeVariableSpinnerAdapter);
    userVariableAdapterWrapper.setItemLayout(android.R.layout.simple_spinner_item, android.R.id.text1);
    variableSpinner.setAdapter(userVariableAdapterWrapper);
    setSpinnerSelection(variableSpinner, null);

    TextView textChangeVariable = (TextView) prototypeView
            .findViewById(R.id.brick_change_variable_prototype_view);
    textChangeVariable.setText(String.valueOf(variableFormula.interpretDouble(sprite)));
    return prototypeView;
}

From source file:com.google.sample.beaconservice.ManageBeaconFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_manage_beacon, container, false);

    advertisedId_Type = (TextView) rootView.findViewById(R.id.advertisedId_Type);
    advertisedId_Id = (TextView) rootView.findViewById(R.id.advertisedId_Id);
    status = (TextView) rootView.findViewById(R.id.status);
    placeId = (TextView) rootView.findViewById(R.id.placeId);
    placeId.setOnClickListener(new View.OnClickListener() {
        @Override//w  ww  .  ja  v  a  2  s  . c o  m
        public void onClick(View v) {
            editLatLngAction();
        }
    });
    latLng = (TextView) rootView.findViewById(R.id.latLng);
    latLng.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editLatLngAction();
        }
    });
    mapView = (ImageView) rootView.findViewById(R.id.mapView);
    mapView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editLatLngAction();
        }
    });

    expectedStability = (TextView) rootView.findViewById(R.id.expectedStability);
    expectedStability.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit Stability");
            final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                    R.array.stability_enums, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            final Spinner spinner = new Spinner(getActivity());
            spinner.setAdapter(adapter);
            // Set the position of the spinner to the current value.
            if (beacon.expectedStability != null
                    && !beacon.expectedStability.equals(Beacon.STABILITY_UNSPECIFIED)) {
                for (int i = 0; i < spinner.getCount(); i++) {
                    if (beacon.expectedStability.equals(spinner.getItemAtPosition(i))) {
                        spinner.setSelection(i);
                    }
                }
            }
            builder.setView(spinner);
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    beacon.expectedStability = (String) spinner.getSelectedItem();
                    updateBeacon();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
    });

    description = (TextView) rootView.findViewById(R.id.description);
    description.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit description");
            final EditText editText = new EditText(getActivity());
            editText.setText(description.getText());
            builder.setView(editText);
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    beacon.description = editText.getText().toString();
                    updateBeacon();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
    });

    actionButton = (Button) rootView.findViewById(R.id.actionButton);

    decommissionButton = (Button) rootView.findViewById(R.id.decommissionButton);
    decommissionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(getActivity()).setTitle("Decommission Beacon")
                    .setMessage("Are you sure you want to decommission this beacon? This operation is "
                            + "irreversible and the beacon cannot be registered again")
                    .setPositiveButton("Decommission", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Callback decommissionCallback = new Callback() {
                                @Override
                                public void onFailure(Request request, IOException e) {
                                    logErrorAndToast("Failed request: " + request, e);
                                }

                                @Override
                                public void onResponse(Response response) throws IOException {
                                    if (response.isSuccessful()) {
                                        beacon.status = Beacon.STATUS_DECOMMISSIONED;
                                        updateBeacon();
                                    } else {
                                        String body = response.body().string();
                                        logErrorAndToast("Unsuccessful decommissionBeacon request: " + body);
                                    }
                                }
                            };
                            client.decommissionBeacon(decommissionCallback, beacon.getBeaconName());
                        }
                    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
        }
    });

    attachmentsDivider = rootView.findViewById(R.id.attachmentsDivider);
    attachmentsLabel = (TextView) rootView.findViewById(R.id.attachmentsLabel);
    attachmentsTable = (TableLayout) rootView.findViewById(R.id.attachmentsTableLayout);

    // Fetch the namespace for the developer console project ID. We redraw the UI once that
    // request completes.
    // TODO: cache this.
    Callback listNamespacesCallback = new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            logErrorAndToast("Failed request: " + request, e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(body);
                    JSONArray namespaces = json.getJSONArray("namespaces");
                    // At present there can be only one namespace.
                    String tmp = namespaces.getJSONObject(0).getString("namespaceName");
                    if (tmp.startsWith("namespaces/")) {
                        namespace = tmp.substring("namespaces/".length());
                    } else {
                        namespace = tmp;
                    }
                    redraw();
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException", e);
                }
            } else {
                logErrorAndToast("Unsuccessful listNamespaces request: " + body);
            }
        }
    };
    client.listNamespaces(listNamespacesCallback);
    return rootView;
}

From source file:org.tomahawk.tomahawk_android.fragments.ChartsSelectorFragment.java

private void populateCountryCodeSpinner(final ScriptChartsProvider provider, final boolean isInitial) {
    if (mCountryCodePicker != null && provider != null) {
        provider.getCountryCodes().done(new DoneCallback<ScriptChartsCountryCodes>() {
            @Override/*from ww  w. j ava  2  s .  c  o  m*/
            public void onDone(final ScriptChartsCountryCodes result) {
                final ArrayList<String> countryCodes = new ArrayList<>();
                final ArrayList<String> displayedCountryCodes = new ArrayList<>();
                final ArrayList<String> displayedCountryCodeNames = new ArrayList<>();
                for (Pair<String, String> countryCode : result.codes) {
                    countryCodes.add(countryCode.second);
                    displayedCountryCodes.add(countryCode.second.toUpperCase());
                    displayedCountryCodeNames.add(countryCode.first);
                }
                int initialPosition = -1;
                if (isInitial) {
                    // Must be the first call of this method. So we should set the initially
                    // stored (or default) selection of the spinner
                    String storedCountryCode = ChartsSelectorFragment.this.getStoredCountryCode(provider);
                    if (storedCountryCode == null) {
                        storedCountryCode = result.defaultCode;
                    }
                    for (int i = 0; i < countryCodes.size(); i++) {
                        if (countryCodes.get(i).equalsIgnoreCase(storedCountryCode)) {
                            initialPosition = i;
                        }
                    }
                }
                Spinner mCountryCodePickerSpinner = (Spinner) mCountryCodePicker.getActionView();
                CountryCodeSpinnerAdapter adapter = new CountryCodeSpinnerAdapter(TomahawkApp.getContext(),
                        R.layout.spinner_textview_country_code, displayedCountryCodes,
                        displayedCountryCodeNames);
                adapter.setDropDownViewResource(R.layout.spinner_dropdown_textview_country_code);
                mCountryCodePickerSpinner.setAdapter(adapter);
                mCountryCodePickerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        String selectedCountryCode = countryCodes.get(position);
                        String storedCountryCode = ChartsSelectorFragment.this.getStoredCountryCode(provider);
                        if (storedCountryCode == null) {
                            storedCountryCode = result.defaultCode;
                        }
                        if (!storedCountryCode.equals(selectedCountryCode)) {
                            storeCountryCode(provider, selectedCountryCode);
                            mSelectedFragmentInfo.mBundle.putString(
                                    ChartsPagerFragment.CHARTSPROVIDER_COUNTRYCODE, selectedCountryCode);
                            // Refresh the currently shown ChartsPagerFragment
                            FragmentUtils.replace((TomahawkMainActivity) getActivity(),
                                    mSelectedFragmentInfo.mClass, mSelectedFragmentInfo.mBundle,
                                    R.id.content_frame);
                        }
                    }

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

                        //oast.makeText(getActivity(), "Kliknut cancel", Toast.LENGTH_SHORT).show();
                    }
                });
                if (initialPosition >= 0) {
                    mCountryCodePickerSpinner.setSelection(initialPosition);
                }
            }
        });
    }
}