Populating Spinner using a HashMap? - android

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.

Related

Android - Two spinners in one Activity - Saving Data is not working

my problem is the following. I have 2 Spinners in one activity. I want that both spinner items should be saved in the DB. But there is a slight difference between both spinners:
Spinner 1: Is populated by data from other db-table - when it is the only spinner in the mentioned activity, it works.
Spinner 2: Has default values. I am not sure if added it correctly to my activity. Anyway, after i added it to my saving the data is not working anymore.
Please help me what am I doing wrong??
My Activity Code:
public class activity_transport extends AppCompatActivity {
private BottomNavigationViewEx bottomNavigationViewEx;
DatabaseHelper myDb;
Button btn_save;
Spinner ChooseProject,ChooseTransport;
EditText Entfernung,Price,MWST;
String selectedspinner, selectedTransport;
ImageView imageView2;
private static int PICK_IMAGE = 100;
Uri imageUri;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transport);
myDb = new DatabaseHelper(this);
ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
ChooseTransport = (Spinner) findViewById(R.id.ChooseTransport);
Entfernung = (EditText) findViewById(R.id.Entfernung);
Price = (EditText) findViewById(R.id.Preis);
MWST = (EditText) findViewById(R.id.MwSt);
btn_save=(Button) findViewById(R.id.btn_save);
//bildanzeigebereich im layout
imageView2=(ImageView) findViewById(R.id.imageView2);
loadProjectSpinnerData();
//loadTransportSpinnerData();
SaveData();
//+++++++++++++++Function to load the spinner data from SQLite database++++++++++//
private void loadProjectSpinnerData() {
// database handler
DatabaseHelper db = new DatabaseHelper (getApplicationContext());
// Spinner Drop down elements
List<String> projects = db.getAllProjects();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseProject.setPrompt("Projekt auswählen");
// attaching data adapter to spinner
ChooseProject.setAdapter(dataAdapter);
//Choose Transport Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {
new String("Auto"),
new String("Flugzeug"),
new String("Taxi"),
new String("Bahn")});
ChooseTransport.setAdapter(spinnerArrayAdapter);
// Drop down layout style - list view with radio button
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseTransport.setPrompt("Transport auswählen");
// attaching data adapter to spinner
ChooseTransport.setAdapter(spinnerArrayAdapter);
//Listener für den Projekt Spinner damit ich den Wert abspeichern kann
ChooseProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.ChooseProject)
{
selectedspinner = (String) ChooseProject.getSelectedItem();
}
else if(spinner.getId() == R.id.ChooseTransport)
{
selectedTransport = (String) ChooseTransport.getSelectedItem();
}
//selectedspinner =String.ValueOf(parent.getItemAtPosition(pos));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/*private void loadTransportSpinnerData() {
// Spinner method to read the on selected value
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {
new String("Auto"),
new String("Flugzeug"),
new String("Taxi"),
new String("Bahn")});
ChooseTransport.setAdapter(spinnerArrayAdapter);
// Creating adapter for spinner
//ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseTransport.setPrompt("Transport auswählen");
// attaching data adapter to spinner
ChooseTransport.setAdapter(spinnerArrayAdapter);
//Listener für den Projekt Spinner damit ich den Wert abspeichern kann
ChooseTransport.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//selectedspinner =String.ValueOf(parent.getItemAtPosition(pos));
selectedTransport = (String) ChooseTransport.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}*/
//++++++++++++Save Data++++++//
public void SaveData(){
btn_save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.createTransport(
selectedspinner,
selectedTransport,
Integer.valueOf(Price.getText().toString()),
Integer.valueOf(MWST.getText().toString()),
Integer.valueOf(Entfernung.getText().toString()),
imageViewToByte(imageView2)
);
if(isInserted=true)
Toast.makeText(activity_transport.this, "Daten gespeichert", Toast.LENGTH_LONG).show();
else
Toast.makeText(activity_transport.this, "Daten nicht gespeichert", Toast.LENGTH_LONG).show();
}
}
);
}
}
EDIT:
I tried to run the app by setting a few breakpoints.
When trying to run this line selectedTransport = (String) ChooseTransport.getSelectedItem(); the debugger posts Cannot find local variable 'ChooseTransport'
I solved the problem:
I implemented an own method for ChooseTransport- Spinner and now it works. I also figured out that the order how I add the data to the DB was not right. I changed this too.
See here my method for my second spinner:
private void loadTransportSpinnerData(){
ArrayAdapter<CharSequence> spinnerArrayAdapter = ArrayAdapter.createFromResource(this, R.array.transport, android.R.layout.simple_spinner_dropdown_item);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseTransport.setPrompt("Transport auswählen");
ChooseTransport.setAdapter(spinnerArrayAdapter);
ChooseTransport.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedTransport = (String) ChooseTransport.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}

Opening different layouts based on values selected in two spinners

I am new to android,and in this code i have two spinners and based on the values selected,different layouts should open accordingly. Im stuck with what logic should i use to open different layouts, inside the OnItemSelected for the spinner.Say i have 5 items in spinner and i have 5 different layouts for each item.So how should i do??
Any help or ideas would be much appreciated. Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
// Spinner element
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
Button button = (Button) findViewById(R.id.button);
// Spinner click listener
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Maruti");
categories.add("Ford");
categories.add("Nissan");
categories.add("TATA");
List<String> types = new ArrayList<String>();
types.add("1Lakh-5Lakh");
types.add("5Lakh-10Lakh");
types.add("10Lakh-20Lakh");
types.add("20Lakh-50Lakh");
types.add("Above 50Lakhs");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayAdapter<String> spinner2Adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,types);
spinner2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner1.setAdapter(dataAdapter);
spinner2.setAdapter(spinner2Adapter);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(SecondActivity.this,ThirdActivity.class);
startActivity(i);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner spinner1 = (Spinner)parent;
Spinner spinner2 = (Spinner)parent;
if(spinner1.equals(position))
{
}
if(spinner2.getId() == R.id.spinner2)
{
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}}
Try below.
check the onClickListener of button which will decide which activity to open.
Spinner spinner1;
Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
// Spinner element
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
Button button = (Button) findViewById(R.id.button);
// Spinner click listener
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Maruti");
categories.add("Ford");
categories.add("Nissan");
categories.add("TATA");
List<String> types = new ArrayList<String>();
types.add("1Lakh-5Lakh");
types.add("5Lakh-10Lakh");
types.add("10Lakh-20Lakh");
types.add("20Lakh-50Lakh");
types.add("Above 50Lakhs");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayAdapter<String> spinner2Adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,types);
spinner2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner1.setAdapter(dataAdapter);
spinner2.setAdapter(spinner2Adapter);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
if(spinner1_selected_item.equals("Maruti"))
{
if(spinner2_selected_item.equals("1Lakh-5Lakh"))
i=new Intent(SecondActivity.this,ThirdActivity.class);
if(spinner2_selected_item.equals("5Lakh-10Lakh"))
i=new Intent(SecondActivity.this,FourthActivity.class);
if(spinner2_selected_item.equals("10Lakh-20Lakh"))
i=new Intent(SecondActivity.this,FifthActivity.class);
}
startActivity(i);
}
});
}
String spinner1_selected_item;
String spinner2_selected_item;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(spinner1.getId() == R.id.spinner1)
{
spinner1_selected_item = parent.getItemAtPosition(position).toString();
}
if(spinner2.getId() == R.id.spinner2)
{
spinner2_selected_item = parent.getItemAtPosition(position).toString();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}}

Inserting into ArrayAdapter does not update Spinner selection

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.

Android - Spinner not able to select items

I have a problem with my spinner. I add the items on the spinner dinamically, from a edittext when a button it's pressed. The items are correctly shown when the spinner is pressed, but no selection can be done and there's no display on the spinner.
Here's the code:
final ArrayList<String> players = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_dropdown_item, players);
final Spinner spinnerplayers = (Spinner)findViewById(R.id.spinnerplayers);
final ImageButton addbutton = (ImageButton)findViewById(R.id.addbutton);
final EditText editname = (EditText)findViewById(R.id.editname);
final EditText editnum = (EditText)findViewById(R.id.editnum);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
players.add(editname.getText().toString()+ " " + editnum.getText().toString());
editname.setText("");
editnum.setText("");
}
});
spinnerplayers.setAdapter(adapter);
final ImageButton removebutton = (ImageButton)findViewById(R.id.removebutton);
removebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//players.remove(spinnerplayers.getSelectedItem().toString());
}
});
If it's needed, the spinner xml is:
<Spinner
android:id="#+id/spinnerplayers"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
Any idea about where's the problem?
Thanks in advance.
Have you tried to specify:
adapter.setNotifyOnChange(true);
to refresh adapter showing each add/remove you make ?
The reason is you set it with android.R.layout.simple_spinner_item.
You can write your own Adapter class:
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
spinner.setAdapter(new MyCustomAdapter(CLASS.this, R.layout.spinner_layout, players));
Then it will look like the way you design in spinner_layout
You have to make a custom adapter for this if you mean the clicklistenrs on your button are not working. You will apply listeners in getView method of the adapter.
Add you have to add OnItemSelectedListener.
YOUR_SPINNER.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
The position gives you your item.

how to add item to Spinner's ArrayAdapter?

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

Categories

Resources