To get the value of the entries in the spinner - android

I need some help guys.
The problem is that I have a spinner that has commodities in it, such as chemicals,biscuits etc. but these commodities are stored in the database. I have written a web service that retrieves the commodities and the corresponding commodity code from database the web service works fine. I am getting the data in my android code. So I have stored the commodity in one array list say ar1, and the commodity code in one more array list say ar2. Now I want these commodity, what I have stored in ar1 to be displayed as spinner items and when user selects one of the spinner items, I must be able to retrieve the corresponding commodity code of that commodity.
Can some body help me??
I am using the below code but i am not able to get the desired result
String[] arr_Commodities = new String[ar2.size()];
spinnerMap = new HashMap<String, String>();
for (int i = 0; i < ar2.size(); i++)
{
spinnerMap.put(ar2.get(i),ar1.get(i));
arr_Commodities[i] = ar2.get(i);
System.out.println(arr_Commodities[i]);
}
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
spin_commodity.setAdapter(adapter);
I find nothing is wrong with this code but i am still not able to pop[ulate the spinner some one please modify the above code..thank you

you can try this and improvise the loop on populating items:
final ArrayList<String[]> items = new ArrayList<String[]>();
for(int i= 0; i <10 ; i++){//sample loop populating items
String[] item = new String[2];
item[0] = "id";
item[1] = "commodities";
items.add(item);
}
Spinner s = new Spinner(context);//sample spinner
ArrayAdapter<String[]> adapter = new ArrayAdapter<String[]>(context , android.R.layout.simple_list_item_1, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
String[] selected = items.get(position);
//commodity id
String comId = selected[0];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});

String[] ar1={"chemicals","biscuits"};
String[] ar2={"1","2"};
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ar1); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
your_spinner.setAdapter(adapter);
//to get the selected item position
int x=your_spinner.getSelectedItemPosition();
Your required code is
String code=ar2[x];

Related

Spinner populated shows wrong characters

thanks for your help
I'm trying populate a spinner with data from an embedded database, and everything seems right:
public ArrayList<String[]> getCountries()
{
ArrayList<String[]> array = new ArrayList<>();
String columnas[] = new String[]{"COUNTRY","COUNTRYCODE"};
Cursor c = db.query("countryCodT",columnas,null,null,null,null,null);
if(c.moveToFirst()){
do{
String[] obj = new String[2];
obj[0]=c.getString(0);
obj[1]=c.getString(1);
array.add(obj);
}while(c.moveToNext());
c.close();
db.close();
}
return array;
}
with this code the spinner is populated:
public void popSpinnerC(){
BDCountries bdCountries = new BDCountries(this);
final ArrayList<String[]> dataGot = bdCountries.getCountries();
ArrayAdapter<String[]> dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,dataGot);
spnCountry.setAdapter(dataAdapter);
spnCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String listId = Integer.toString(i);
strCounty = listId + dataGot.get(i)[0] + dataGot.get(i)[1];
msgData.setText(strCounty);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
the spinner text shown is wrong, the data amount is correct, when something is selected is shown the right information in a text view with test purposes, how can I correct it?
Results:
The spinner option list is a list of string arrays rather than strings so it is printing toString() of each string array as a spinner item.
Look at your getCountries() method. It is returning ArrayList<String[]> instead of ArrayList<String>.

How to get list of data from database to spinner

I want to get all username from my user table to be displayed in my spinner for selection but instead of displaying all username from my list it displays only one which is the first user from my database.. how can i get all username?
String q = "SELECT * FROM " + User.TABLE;
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(q, null);
String[] ComRep = new String[0];
if (cursor.moveToFirst()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
do {
ComRep = new String[]{rep};
} while (cursor.moveToNext());
}
cursor.close();
Comrep = (Spinner) findViewById(R.id.spincomrep);
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, ComRep);
adapterrep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Comrep.setAdapter(adapterrep);
Comrep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Comrep.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
thanks in advance..
You're not actually accumulating any values in your array. You're making a new array each time you go through the loop.
ArrayList<String> values = new ArrayList<String>();
while (cursor.moveToNext()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
values.add(rep);
}
cursor.close();
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, values.toArray(new String[values.size]));
You should look at CursorAdapter. You could make an adapter directly from your cursor so you don't need to code the loop.

Set Value and Text in spinner from ArrayAdapter & Gson

I am using Json Asp.NET Webservice and Android Soap service to retrive data.
And It is working fine. Now, I want to set Value and Text in Spinner from ArrayAdapter & Gson. How to do it ?
My Code :
placelist = gson.fromJson(result, City[].class);
ArrayAdapter<City> adapter = new ArrayAdapter<City>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, placelist);
spinnerFood.setAdapter(adapter);
My Output:
[{"CityId":1,"CityName":"Vadodara"},{"CityId":2,"CityName":"ahmedabad"},{"CityId":3,"CityName":"Gandhinagar"},{"CityId":4,"CityName":"Bhavnagar"},{"CityId":7,"CityName":"Eluru"},{"CityId":8,"CityName":"Visakhapatnam"},{"CityId":15,"CityName":"Anantapur"},{"CityId":16,"CityName":"Srikakulam"}]
I want to set CityName as Spinner Text and CityId as Spinnet Value. City is java class file which contains CityId and CityName parameters.
If you want only CityName to be dropdown value of Spinner
then you should pass only the list of CityName not the array of City class to the adapter.
So, to extract the CityName from your array you can do like this:
List lList = Arrays.asList(placelist);
List<String> cityName = new ArrayList<String>();
List<String> cityId = new ArrayList<String>();
City obj;
for (int i=0; i < lList .size(); i++)
{
obj= lList.get(i);
cityName.add(obj.getCityName());
cityId.add(obj.getCityId()); // City Id will be the value for on click of spinner items
}
Now you can pass this cityName list to you arrayadapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, cityName);
Coming to Second part of your question, you need to set a listener for spinner where you can get Value of respective cityId's from "cityId" array list created
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
String Id;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// TODO Auto-generated method stub
id= cityId.get(pos);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Let me know if it works
Regards
Please follow the following tutorial Json parsing
First retrieve the response in JsonArray and From array retrieve JsonObjects. and store both in array, and you can use that value for spinner

Delete multiple selected items in ListView

I have a list view that displays records from a database. Each row in the listview has a checkbox. How do I...
Create a toast message displaying the value of the selected item?
Identify the records selected by the user in the listview?
Iterate through each selected item and delete only the rows selected in the listview from the database?
I've been following this helpful tutorial here: //http://www.vogella.com/articles/AndroidSQLite/article.html
public class PhoneNumberDataBaseListView extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
String number = "123";
datasource.createNumber(number);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
}
public void deleteNumber() {
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
ListView LV = (ListView) findViewById(android.R.id.list);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
SparseBooleanArray checkedItems = LV.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
Number item = adapter.getItem(i);
Toast t = Toast.makeText(this, item.getNumber().toString(), Toast.LENGTH_LONG);
t.show();
}
}
}
Method getCheckedItemPositions() returns SparseBooleanArray that indicates which items are checked (if item on specific position is checked, method valueAt(position) invoked on that array returns true). Class DBAdapter from tutorial you are following provides you with deleteTitle(long rowId) method which you should use to acheive what you want.Therefore your code should look more or less like this:
SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
db.deleteTitle(adapter.getItemId(i));
}
}
Of course SimpleCursorAdapter and DBAdapter should be stored in object attributes so that you have access to them from both methods (onCreate and deleteRecord). By the way, View parameter passed to deleteRecord method is not needed.

Application crashes trying to retrieve view contents from ListView using SimpleAdapter

I am having an issue with trying to retrieve the contents of the view that the the user has clicked within a ListView. My ListView is setup using a SimpleAdapter and is comprised of a "heading" and a "sub-title" for each of the items in the list. These are stored using a HashMap.
Within the activity also, is a spinner, when the user selects an item in the spinner, the ListView is updated. This is working fine and I just thought it necessary to mention what is happening within the activity as well.
What I am trying to do, is retrieve which item the user has selected so I can guide them to a new activity based on their selection (right now just trying to display the view contents with Toast). I want to retrieve the contents of what is stored under the "engExp" key for the item.
Here is my code:
// HASHMAP FOR LISTVIEW
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for(int x = 0; x < expressionListForModule.getCount(); x++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("engExp", expressionListForModule.getString(0));
map.put("japDef", expressionListForModule.getString(1));
fillMaps.add(map);
expressionListForModule.moveToNext();
}
// SETUP LISTVIEW
SimpleAdapter adapter2 = new SimpleAdapter(this, fillMaps, android.R.layout.simple_list_item_2, new String[] {"engExp","japDef"}, new int[] {android.R.id.text1, android.R.id.text2});
ListView lv = (ListView) findViewById(R.id.expressionList);
lv.setAdapter(adapter2);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_LONG).show();
}
});
Specifically, the item that is causing the application to crash is this:
((TextView) view).getText()
If you need to see any more of my code, please let me know.
Any help is appreciated, thanks in advance.
try
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView v = (TextView) view.findViewById(android.R.id.text1);
String contentForLink = v.getText().toString();
Toast.makeText(getApplicationContext(), contentForLink, Toast.LENGTH_LONG).show();
}
});

Categories

Resources