Amanda Watson
Amanda Watson

Reputation: 370

How do I add a user inputted value to a spinner in android?

I have created a spinner that with one of the options being "Add url". When "add url" is selected, it pops up an alert that allows the user to type in their new url. All of this works. The problem is that it does not add the new url to the spinner. I am notifying the array adapter after the user adds the new url. How can I fix this so that the new url value is put into the spinner.

Here is my code for the spinner:

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

// Create an ArrayAdapter using the string array and a default spinner layout
ArrayList<String>urls = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.url_array)));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, urls);

// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);

spinner.setOnItemSelectedListener(this);

Here is my code for onItemSelected():

public void onItemSelected(AdapterView<?> parent, View view, int pos, long l) {
    if (pos==3) {
        // Set an EditText view to get user input
        final EditText input = new EditText(DeviceServicesActivity.this);

        new AlertDialog.Builder(DeviceServicesActivity.this)
                .setMessage("Enter your Point here")
                .setView(input)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Editable editable = input.getText();
                        String newString = editable.toString();

                        urls.add(newString);
                        adapter.notifyDataSetChanged();



                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Do nothing.
                    }
                }).show();
    }
}

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

}

I found this message in the logcat whenever I try to add a url: W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.

Upvotes: 0

Views: 752

Answers (1)

SUDARSHAN BHALERAO
SUDARSHAN BHALERAO

Reputation: 475

Instead of using

  urls.add(newString);

use

  adaptor.setNotifyOnChange(true);
  adapter.add(newString);

This might help you out

Upvotes: 4

Related Questions