How to get spinner string value on android? - android

I have created a spinner and the items of spinner comes from database. However, When I use
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
typeOFBCard = contactSpinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
When I call this listener and try to pick the chosen string of the spinner i get a reference of the sglite something like:
android.database.sqlite.SQLiteCursor#40535568
This is the return value of typeOfBCard.
However, on the spinner I can see normal string like "Work".
Here is how I initialized the spinner :
contactSpinner = (Spinner) findViewById(R.id.contactSpinner);
mobileText =(EditText) findViewById(R.id.mobileText);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
cursor = mDbHelper.fetchAllBusinessCards();
startManagingCursor(cursor);
context =this;
contactSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

How ever on the spinner I can see normal string like "Work"
That is because you configured an Adapter on the Spinner, and the Adapter is pulling data out of the Cursor to display.
How to get spinner string value on android?
There is no "spinner string value". Spinners don't have strings. They have views. Those views might be instances of TextView, or they might be instances of ImageView, or they might be instances of a LinearLayout holding onto a TextView and an ImageView, or...
If you want to get data out of the Cursor, call getString() on the Cursor.

Every row in a spinner is a view but it's also a value/object from your source.
Try
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// Parent == where the click happened.
typeOFBCard = parent.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}

Related

how to add empty first value and set it as null appcompat Spinner

i create in a two way data binding spinner in Android, and added value into with a result of a REST GET.
I need now to add the first value of the spinner as an empty string that when it will be selected from the spinner, the value will be null.
In the fragment class i wrote this code:
//spinner
appCompatSpinner = binding.spinner;
spinnerAdapter = new SpinnerAdapter(getActivity(), viewModel.usersDetailsList );
appCompatSpinner.setAdapter(spinnerActorAdapter);
appCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
viewModel.onSelected(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mAdapter.notifyDataSetChanged();
Can someone please help me to achieve that?

How to Add a extra value to spinner

SOLVED HERE IS THE SOLUTION ANSWER http://www.congdegnu.es/2011/06/02/spinners-en-android-tres-formas-de-poblarlos/
I'm populating a spinner from my sqlite database like this:
Cursor CS = newDB.rawQuery("Select ID AS _id, Name from Schools",null);
CS.moveToFirst();
do{
Schools.add(CS.getString(CS.getColumnIndex("_id")));
} while(CS.moveToNext());
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Schools);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
My problem is that I only add an id but how can I add a value to that id so when the value get select I get the id ?
I think that "schools" is an array containing you own class "school".
You could add a propertie which contains the information.
Or you could use a 2 dimensional array.
Than you have to set up your arrayadapter to get the information (getter Method).
Hope it helps
Try Cursor Adapter
or
Take a global variable
Hashmap schoolmap=new Hashmap();
While inserting data to the list also add to Hashmap like this
CS.moveToFirst();
do{
Schools.add(CS.getString(CS.getColumnIndex("_id")));
schoolmap.put(CS.getString(CS.getColumnIndex("_id")),CS.getColumnIndex("_id"))
} while(CS.moveToNext());
onSpinner item click get the value like this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String value=((TextView)view).getText();
int id=Integer.parseInt(schoolmap.get(value));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Take a look at using a SimpleCursorAdapter for your spinner instead. Although this has been deprecated since API-11, so you may also want to think about using a LoaderManager with a CursorLoader.
An explanation on how to transition to a LoaderManager and CursorLoader can be found here:
How to transition from managedQuery to LoaderManager/CursorLoader?
I would recommend you start by using the SimpleCursorAdapter, then if confortable enough, move on to the other method.
1) Create an ArrayList<School>
2) Add all your Schools to the Arraylist
3) Create a custom adapter like this:
public class SchoolAdapter extends ArrayAdapter<School>{
public SchoolAdapter(Context ctx, List<School> schools){
super(ctx, 0, schools);
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
TextView tv;
if (convertView == null){
tv = new TextView(getContext());
} else {
tv = (TextView) convertView;
}
tv.setTextSize(16);
final School school = getItem(position);
tv.setText(school.toString());
return tv;
}
}
4) Use this in your activity:
final SchoolAdapter adapter = new SchoolAdapter(this, schools);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
School school = adapter.getItem(pos);
// Do whatever you want with your school
}
public void onNothingSelected(AdapterView<?> parent) {
}
});

Android - Populate a textview from a Spinner item

I would like to have my application populate an empty textview with the value that a user selects from a spinner. Currently it seems to work, but it only populates the textview with what I'm guessing is the entire cursor: (android.database.sqlite.SQLiteCursor#4120dd08).
Can someone help me figure out what the issue is? I can post more code if necessary.
// Set spinner listener to populate the description field onclick.
mContext = this;
commonDescSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
String stringItem = parent.getItemAtPosition(position).toString();
mDescriptionText.setText(stringItem);
}
public void onNothingSelected(AdapterView<?> parent) {}
});
Try this:
// Set spinner listener to populate the description field onclick.
mContext = this;
commonDescSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
TextView objTextView = (TextView) commonDescSpin.getSelectedView();
String stringItem = objTextView.getText().toString();
mDescriptionText.setText(stringItem);
}
public void onNothingSelected(AdapterView<?> parent) {}
});
The method toString() usually has other implementations relating to identifying object instances. If you know that the item in the spinner is without a doubt a string, you could consider performing an explicit cast:
String stringItem = (String)(spinner1.getItemAtPosition(2));
textViewStatus.setText(stringItem);

Order of OnItemSelectedListener Calls After OnCreate

I have two spinners in an Activity where the second Spinner's selection set is based on what the user picked for the first Spinner. I use a private class variable in the Activity which is set in the top Spinner's OnItemSelectedListener and then referenced in the bottom Spinner's OnItemSelectedListener to obtain the correct selection set.
This almost always works, but sometimes (mainly when app was run, not exited, and then started again by a user click some long time later) I get a null pointer exception in the second Spinner's OnItemSelectedListener due to this local variable not being set. This indicates to me that after the OnCreate that the second Spinner's OnItemSelectedListener was called before the first Spinner's.
Is there any method to force a certain order in the listeners being fired or is there a better design approach to handle this second Spinner's dependency on the first Spinner?
Example code:
package com.crashtestdummylimited.navydecoder;
public class Test extends Activity {
// Variable that at times is still null
private ReferenceData referenceData;
private void setupSpinnerFromArray (int spinnerId, String stringArray[], OnItemSelectedListener listener) {
Spinner spinner = (Spinner) findViewById(spinnerId);
ArrayAdapter <CharSequence> adapter = new ArrayAdapter <CharSequence>(
this, android.R.layout.simple_spinner_item, stringArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(listener);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
// Setup Top (main) Spinner
Spinner spinner1 = (Spinner) findViewById(R.id.mainDecodeSpinner);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.level0_list_array, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new MainDecoderItemSelectedListener());
// Setup Bottom (dependent) Spinner
setupSpinnerFromArray(R.id.secondaryDecodeSpinner, R.array.level1_list_array, new SecondaryDecoderItemSelectedListener());
}
public class MainDecoderItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String selectedString = parent.getItemAtPosition(pos).toString();
if (selectedString.equals("AAA")){
// Problem variable is set
referenceData = new RatingCodes();
setupSpinnerFromArray(R.id.secondaryDecodeSpinner, referenceData.getKeys(), new SecondaryDecoderItemSelectedListener());
}
else if (selectedString.equals("BBB")){
// Problem variable is set
referenceData = new IMSCodes();
setupSpinnerFromArray(R.id.secondaryDecodeSpinner, referenceData.getKeys(), new SecondaryDecoderItemSelectedListener());
}
// TODO: Improve what occurs if no match which should not occur
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
public class SecondaryDecoderItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String key = parent.getItemAtPosition(pos).toString();
// **** referenceData being null at this point has caused crashed ****
String value = referenceData.getValue(key);
// ... Update text on activity screen ...
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
}
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id)
{
if(pos == 0)
{ //when it loads on onCreate() then pos is always 0
//donothing
}
else
{ //If user manually select item
//do what you need to do on manual user selection
}
}

How to get an ID from database into the ListView

I learn work with Android. I started to create a project with Contacts.
I insert contacts into the SQLite database and then I put them from the database and show them in ListView. Thats OK. But I would like to click on an item in the List and then to edit the item. Therefore I need to get somehow the ID of the item and work with it...I do not know if it is clear...As you can see, in the function onItemClick() , there is running a new activity ...and in the new activity, I need the ID of the item in order to work with it.
public class ContactList extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seznam_kontaktu2);
SQLInsert info = new SQLInsert(this);
info.open();
ArrayList<String> data = info.getDataArrayList(); //It returns Array of "Lastname, Name" which is shown in the List
info.close();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
});
}
One option that has worked for me is to create a custom ArrayAdapter class along with a custom AdapterItem class. We store the id on our AdapterItem, and return it using our custom ArrayAdapter.
MyAdapterItem might look something like ...
public class MyAdapterItem implements Comparable
{
public String name;
public long rowId;
public MyAdapterItem()
{
rowId = -1L;
name = "";
}
public MyAdapterItem(long _rowId, String _name)
{
rowId = _rowId;
name = _name;
}
public int compareTo( Object o )
{
return toString().compareTo(o.toString());
}
public String toString()
{
return name;
}
}
Our custom ArrayAdapter, MyAdapter, then overrides getItemId(). It reads and returns the stored row id (making the assumption it is working with elements of MyAdapterItem). The other methods on ArrayAdapter will continue to work with our custom class - the toString method is used by the list for display purposes, and by providing a compareTo method the list knows how to sort the values.
public class MyAdapter<MyAdapterItem> extends ArrayAdapter
{
public MyAdapter(Context context, int resourceId)
{
super(context, resourceId);
}
#Override
public long getItemId( int position )
{
MyAdapterItem item = (MyAdapterItem)this.getItem(position);
return item.rowId;
}
}
Back in your Activity's onCreate the OnItemClickListener now provides the correct row id in the "id" parameter.
What is not shown is the new implementation of info.getDataArrayList() - it must be modified to create new MyAdapterItem objects instead of simple Strings.
ArrayList<MyAdapterItem> data = info.getDataArrayList();
ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter( new MyAdapter<MyAdapterItem>(this, android.R.layout.simple_list_item_1, data) );
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
// do whatever - the value in "id" is supplied by getRowId on our adapter
}
});
Also, if you attach a context menu to your ListView, the MenuItem objects passed into your Activity's onContextItemSelected method will also return the correct row id.
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long rowId = info.id;
// do something with the id
}
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
startActivity(new Intent("net.johnyho.cz.EDITOVATKONTAKT"));
}
hi i dont know what are the column names of your application.but for example id is your primary key identifier then move cursor to arg2 postion and get the value of _id and then pass it to startActivity and it will work.first thing apply SQLiteOpenHelper class its easy for use then apply this.

Categories

Resources