Using values from outside onItemSelected - android

I have an array of Spinners, hours[]. I am setting it up in a loop. When an item is selected, I need to take it and insert it into a database table, so I need the value of the loop counter in the onItemSelected() function. How do I do this? Here is the code:
for(int i=0; i<36; i++)
{
hours[i].setAdapter(adapter);
hours[i].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapterView, View view, int x, long l)
{
String in=String.valueOf(adapterView.getSelectedItem());
DBHelper db=new DBHelper(AcceptTimetable.this, null, null, 1);
db.changeHour((int)Math.ceil(i/6), (i+1)%6, new Subject(in));
//need to use i here, but it's giving an error
db.close();
}
public void onNothingSelected(AdapterView<?> arg)
{
//do nothing
}
});
}
Also, I'm not sure String in=String.valueOf(adapterView.getSelectedItem()); is correct. Can anyone tell me how to get the selected value from the Spinner? Thanks a lot.

Try this..
for(int i=0; i<36; i++)
{
Log.v("Select Items in Spinner",hours[i].getSelectedItem().toString().trim());
}
From that log you can see the results.

There are two ways to do this.
Easier, but less efficient is to include hours[i].setPrompt(String.valueOf(i)) and then retrieve that value inside the listener via int index = Int.parse(((Spinner) adapterView).getPrompt()).
The more efficient way is to extend the Spinner in a separate class and add an index attribute and keep the index in it.
EDIT: the getSelectedItem() method returns an object whose type matches the one you specified when initializing the adapter you've bound to your AdapterView

Related

Get element from the selected item in the listView

Stackoverflow has really helped me get to this level. Thank you all.
Basically, I want to get an element (sub-part not the whole data) from the selected item in a ListView. I've read here that it could be done using Cursors but no success. This is the associated snippet:
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor member = (Cursor)parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Click ListItem Number "+member.getString(2), Toast.LENGTH_LONG)
.show();
}
});
parent.getItemAtPosition(position) gives me the (Array, I suppose):
{name="xyz_name", uname="xyz_user", desig="xyz_desig"} correctly.
I want to, suppose, fetch unamefrom this, so, have used Cursor to fetch it but the above snippet is giving the error,
java.lang.ClassCastException: java.util.HashMap cannot be cast to android.database.Cursor
Adding detail: I'm getting the text associated with the listView item correctly. What I actually want a sub-part of the data retrieved. For example the data retrieved is obviously an array containing a name and his role. Now, I just want to fetch the 'role' element in the array. Since, the data is retrieved as an array, what I've searched on net is that I can use Cursors to retrieve different elements. Hope you got me now.
There's seem to be a silly syntax error by my side. If you have any alternatives, please tell.
Thanks :)
go with the simple way
ListView list = (ListView) findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object listItem = list.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Click ListItem Number"+listItem.getString(), Toast.LENGTH_LONG).show();
}
});
Understanding your case, getItemAtPosition(position) is returning you an Object.
The answer posted by #Charuka Silva might not be working for you as you may have used hashmap object something like HashMap<String,String> obj = new HashMap<String,String>();
So, the solution is to use HashMap again for getting the returned object and using get("key") function to retrieve the value associated with it. I think this is what you want:
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Use HashMap here
HashMap<String, Object> member = (HashMap<String, Object>) parent.getItemAtPosition(position);
//Use obj.get("key") here to retrieve the value associated with the "key"
Toast.makeText(getApplicationContext(),"member.get("uname"), Toast.LENGTH_LONG)
.show();
}
});
I had a similar problem in my Minor Project and an answer by #user1068963 helped me. Adding Link.
Hope this helps.

Spinner first item default set empty value?

Here in this code i have added pincode numbers from 600000 to 600113 in the spinner but i want the first position to be just empty. When the user clicks only then the item should be shown. Please see my code -
final String[] myarray=new String[114];
for(int i=0;i<114;i++)
{
myarray[i]=String.valueOf(a);
a++;
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,myarray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addnum_spinner.setAdapter(adapter);
lv.setOnItemClickListener(itemClickedListener);
//Spinner click
addnum_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String value = myarray[position];
//
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
add this property to your spinner in xml and try if that works
android:prompt=""
I don't know if this is the right way but what about just adding the empty string before the for loop as the first item and then you just have to handle the user clicking on the empty item in your Listener. Something like
final String[] myarray=new String[115];
myarray[0] = ""
for(int i=1;i<115;i++)
{
myarray[i]=String.valueOf(a);
a++;
}
I know this question is old, but I'm adding a solution. I found this out on accident, as I DIDN'T want a blank default value, but there was one.
If using an ArrayAdapter, I found that attaching the adapter to an empty ArrayList, and THEN filling it left a blank initial value.
Filling the ArrayList first, then attaching the ArrayAdapter removed the blank default value.
Obviously, if not using an ArrayAdapter, using the prompt, or setting the first Spinner item as <item></item> with nothing in between in the XML should work.

Setting spinner position dynamically in android?

I am developing an app where i need to set spinner values dynamically based on previous screen values. My code...
Main.java.
String[] values = {"All","Only Walk-in","Only Phone","Only Web","Walkin-phone","Walkin-web","phone-web"};
/*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,apttypes);
spinner.setAdapter(adapter);*/
But here what i want is from previous screen i am getting some value (like spinner postion). based on that i need to set spinner value to display...
Means from previous screen if i got values =0 means,
i need to set spinner value to display "All" from values array at top.
If i got value= 5 means,
i want to set spinner value to display as "Walkin-web"
How can i do that. can anyone help me with this...
Pass the value in from the previous Activity using extras in the Intent you use to launch it. Then when you've read the value call
int position = getIntent().getIntExtra( "name", defaultValue );
spinner.setSelection( position );
Which will move the spinner to the index you selected.
Use following array code and create new array adapter each time
String[] str=new String[maxsize-4];
you can implement onItemClick event on Spinner like this and setSelection(position)
//Spinner OnItemClick Event here
payfeeTabStudentNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
payfeeTabStudentNameSpinner.setSelection(position);
spinnerSelectedValue = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Inside your First Activity A.java
public static String Position = YOUR_SPINNER1.getSelectedItem().toString();
Inside your Second Activity B.java
if(A.Position.equals("0")){
//Set your adapter accordingly
}else if(A.Position.equals("1")){
//Set your adapter accordingly
}
You can assign the Spinner's Position using the following code..
Spinner s1;
-----------
-----------
int position=valueFromPrevious;
s1.setSelection(position);
-----------
-----------
pass the values from previous activity using Extras and then when u want use it in your current activity follow this:
If u get String value then typecast it into interger by parseInt method...
String strtext4 = getIntent().getStringExtra("qualification");
then
int position = Integer.parseInt(strtext4);
after this just set it to your spinner
qualificationspinner.setSelection(position);

Get the values from one layout to next layout?

I've listed some items in list that extends Activity and the list are listed using Custom Adapter. My question is, this is my xml File I've added some items to this spinner. How can i get the spinner values to next layout. Anyone knows then please tell me? Advance thanks.
I'm not clear on what you're actually asking here, but as a guess there are two possible things you're asking
How to get the currently selected value out of the Spinner
How to set the same value to a spinner in the next layout
1.
Is simple enough
((Spinner)findViewById(R.id.spinner1)).getSelectedItem()
Will return the object selected by your spinner.
Is slightly more complex, you'll need to determine what index in the data supplied corresponds to the result you get from getSelectedItem(), for example if you had an array of Strings then you could search through until you found the index and then set it on the new spinner.
For example:
String[] options = new String[] {"One","Two","Three","Four"};
String val = (String)((Spinner)findViewById(R.id.spinner1)).getSelectedItem();
//.......pass this to a layout/activity etc.........
for (int i=0; i<options.length; i++)
{
if (options[i].equals(test))
{
((Spinner)findViewById(R.id.spinner2).setSelection(i);
break;
}
}
But your best bet would be to try and explain more clearly what you're asking.
first you have to select data from spinner using
spinnerobject.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id)
{
Spinner spinnerobject = (Spinner) findViewById(R.id.Spinner02);
string value = (String)spinnerobj.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
then u hava to use intent for sending it to next activity..
Use
Intent.putExtra(..):
intent.putExtra("keyName", "somevalue");
This method is overloaded and takes various types as second argument: int, byte, String, various arrays..
To get the data out use appropriate getXYZExtra(). For String this is:
getStringExtra(String keyName)
First thing :: you can pass value from one activity to second activity not one layout to second
second :: if you need to pass value from one activity to second use
first activity::
activity.putExtra("lastpage", lastscore5);
*here lastpage is key which unique for aplication
second activity::
Intent i1 = getIntent();
var = i1.getIntExtra("lastpage", 1);

Storing selected spinner item in database table - Android

So my situation is this. I have two tables. A main table where data is added using a form, this form has a spinner which is powered from the second table (this part is working correctly). I then want the selected item in the spinner to be stored in a foreignkey field in the main table.
I have been using the following code:
private Spinner mSpinner;
mSpinner = (Spinner) findViewById(R.id.spinCat);
and in my populate fields method I have the following:
mSpinner.getSelectedItem();
but this stores something like "android.database.sqlite.SQLiteCursor#43e5be60" in to the database rather than the name.
If anyone can offer some help it would be great, this has been bothering me for some days now and has halted development somewhat. If you need to see more code, then please don't hesitate to ask.
Any help is much appreciated.
EDIT: new code:
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View vw,
int pos, long id) {
LinearLayout rowll = (LinearLayout) vw;
TextView test = (TextView) rowll.getChildAt(0);
Toast t = Toast.makeText(parent.getContext(), test
.getText().toString(), Toast.LENGTH_SHORT);
t.show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing..
}
});
getSelectedItem returns an Object (which is what your output looks a lot like).
Did you try simply calling toString like this?
mSpinner.getSelectedItem().toString();
I personally just set a variable in the onItemSelected listener, but this should work too. What I use is:
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
myIP = parent.getItemAtPosition(position).toString();
}
Variable is then continuously updated and I just add it to the DB when I connect to the IP in question.
Cursor data extraction:
while (cursor.moveToNext()) {
ipList.add(cursor.getString(1));
}
getString(int columnIndex) does: Returns the value of the requested column as a String.
http://developer.android.com/reference/android/database/Cursor.html
Don't use .getChildAt(), use .getItemAtPositon(). See how the code does it at http://developer.android.com/resources/tutorials/views/hello-spinner.html.

Categories

Resources