I am trying to insert an item into an Adapter that multiple Spinners are using. However when I insert into the adapter, I would like the Spinners to retain their original selection based off the object and not the position.
In the case below, the Spinner is originally selecting "four", but when I click the button to insert "three", the spinner is now set to "three" instead of updating to the new position of "four". How can I achieve this?
public class MyActivity extends Activity {
List list;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("four");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, list);
spinner.setAdapter(adapter);
// set selection to "four"
spinner.setSelection(2);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//list.add(2, "three") causes the same problem
adapter.insert("three", 2);
adapter.notifyDataSetChanged();
}
});
}
Should you call spinner.setAdapter(adapter); or a similar method after inserting a new value into the adaptor?
spinner.setSelection(list.indexOf("four"));
This will set the selection to "four" no matter on what position it is.
Related
I am a beginner in Android. I have a spinner in my android code. It takes values from room database and once selected the value will be added to the listview. I have two issues
a) I am seeing values in my Spinner. But I am not able to select it and also onItemSelected for this spinner is not working
b) I would like to add a delete icon in my list view along with these values so that if the user is not interested in the value he can delete it.
Please can someone help me to resolve this?
Code is provided below:
public class MainActivity extends AppCompatActivity
{
private List<String> tasks = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private ListView consultantsList;
private Spinner spinner;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consultantsRepository consrepo =
new consultantsRepository (getApplicationContext());
ArrayList<String> oncons = consrepo.getConsultants();
ArrayAdapter<String> consarrayadapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
oncons);
adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,tasks);
ListView consultantsList = (ListView) findViewById(R.id.ListToSend);
consultantsList.setAdapter(adapter);
spinner = (Spinner) findViewById(R.id.consSpinner);
spinner.setAdapter(consarrayadapter);
consarrayadapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener
(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected
(AdapterView<?> parent, View view, int position, long id)
{
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), item,
Toast.LENGTH_LONG).show();
tasks.add(item);
adapter.notifyDataSetChanged();
}
});
}
}
try-
String item=spinner.getSelectedItem().toString();
I am trying to set and get value to a spinner for item dynamically ?
any ideas ?
I just need help with the Spinner behavior right now, the rest should be quite easy.
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android.R.id.text1);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerAdapter.add("value");
spinnerAdapter.notifyDataSetChanged();
spinner.setSelection(0);
String text = spinner.getSelectedItem().toString();
1
2
3
XML file:
<Spinner android:id="#+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Java file:
public class SpinnerExample extends Activity {
private String[] arraySpinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.arraySpinner = new String[] {
"1", "2", "3", "4", "5"
};
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySpinner);
s.setAdapter(adapter);
}
// To get value from spenner
spinner.setOnItemSelectedListener(newAdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView parent) {
}
});
}
Try this this will help you.
Spinner mySpinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> myAdapter= new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item);
mySpinner.setAdapter(myAdapter);
If you want to add the elements dynamically, you can by doing this:
myAdapter.add("newelement");
myAdapter.notifyDataSetChanged();
Spinner spinn = findViewById(R.id.socialmedia_spinner_adsocmeda);
ArrayList<String> fam = new ArrayList<>();
fam.add("INSTAGRAM");
fam.add("FACEBOOK");
fam.add("GOODWALL");
fam.add("TWITTER");
fam.add("YOUTUBE");
fam.add("LINKEDIN");
fam.add("SNAPCHAT");
ArrayAdapter<String> myAdapter= new ArrayAdapter<String> (ProfileActivity.this,
android.R.layout.simple_list_item_1, fam.toArray(new String[0]));
spinn.setAdapter(myAdapter);
That's a way we can add data to spinner.
I am trying to populate a spinner using items from a custom class I created via a simple adapter, containing a HashMap. My app keeps crashing when I use setSimpleAdapter(), so I commented it out. But when I use spinner1.setAdapter(dataAdapter), it shows no items on the spinner. Here's my code:
This is in my onCreate():
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter <CharSequence> dataAdapter =
new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
//setSimpleAdapter();
// Spinner item selection Listener
addListenerOnSpinnerItemSelection();
// Button click Listener
addListenerOnButton();
// Add spinner data
public void addListenerOnSpinnerItemSelection(){
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("X");
alertDialog.setMessage("" + String.valueOf(spinner1.getSelectedItem()));
alertDialog.setButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Dismisses alert
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
}
Can anyone point me in the right direction? I have been googling for like an hour now. Any help will be appreciated.
Well you didn't post half enough code, but say you have a HashMap<String, Object> then you'd wanna do something like this, passing the array of values into the constructor:
Collection<Object> vals = hashMap.values();
Object[] array = vals.toArray(new Object[vals.size()]);
ArrayAdapter<CharSequence> dataAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, array);
Just replace Object with whatever your custom class is and ensure that you override toString() to define what should be displayed as text.
I have code to load spinner with class extends Activity. It is work successfully. This is the code ...
package nielpoenya.blogspot.com;
import....
public class MySQLite extends Activity implements OnItemSelectedListener {
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected.....
Now i want to try in class with extends Fragment, but it make it stop working..
package com.tugasbesar.medantrain;
import....
public class InfoJadwal extends Fragment implements OnItemSelectedListener {
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.info_jadwal, container, false);
spinner = (Spinner) getActivity().findViewById(R.id.spin_tujuan);
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
return rootView;
}
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(this.getActivity());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this.getActivity(), android.R.layout.simple_spinner_item,
lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected....
What was lacking with my fragment class ? Thanks
The error is in your onCreateView, you need to replace :
spinner = (Spinner) getActivity().findViewById(R.id.spin_tujuan);
by :
spinner = (Spinner) rootView.findViewById(R.id.spin_tujuan);
because with getActivity().findViewById() it will try to search a view in the contentview of your Activity, not in your Fragment.
i had a EditText , a button and a spinner . When click the button , the spinner will add a new item with name you entered in the EditText. But here is the question, my adapter.add() method seems doesn't work...here is my code:
public class Spr extends Activity {
Button bt1;
EditText et;
ArrayAdapter<CharSequence> adapter;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt1 = (Button)this.findViewById(R.id.bt1);
et = (EditText)this.findViewById(R.id.et);
spinner = (Spinner)this.findViewById(R.id.spr);
adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = et.getText().toString();
adapter.add(temp);
adapter.notifyDataSetChanged();
spinner.setAdapter(adapter);
}
});
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Toast.makeText(parent.getContext(), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
}
}
thanks! ...still waitting
When you have created your ArrayAdapter you haven't assigned a resizeable List to it, so when you do add() it cannot increment the size of it and throws a UnsupportedOperationException.
Try something like this:
List<CharSequence> planets = new ArrayList<CharSequence>();
adapter = new ArrayAdapter<CharSequence>(context,
R.array.planets_array, planets);
//now you can call adapter.add()
You should use a List. With an Array such as CharSequence[] you would get the same UnsupportedOperationException exception.
Javi is right except don't reference an array for the second parameter.
adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item,
someList);
I believe this is working as designed, but not as expected. ArrayAdapter used to only take an array, but the list constructor was added later. I'm guessing its just doing a toArray() on your list. This is why you have to either call add on the adapter, or create a new adapter when your List changes.
you can create an arraylist and copy all recourse to this object then create arrayadaptor and send this arraylist and in onclicklistener of button, add edittext content to arraylist object then call notifydatasetchanged of adator