I have a spinner which contains dynamic data which is displayed over 2 lines. What I require help with is dislaying only part of the spinners value (ItemArrayName[i]) within the spinner text box.
To calrify in the popup when the spinner is clicked, I require the full text, however when the item has been select I only require the item name.
e.g.
Within the App:
Item Name
Within the spinner selection pop out:
Item Name
Atk = 10, Def = 10
Java Code:
ArrayList<String> ItemArrayList = new ArrayList<String>();
for(int i = 0; i < ItemArrayName.length; i++)
{
ItemArrayList.add(ItemArrayName[i] + "\nAtk = " + String.valueOf(ItemArrayAtk[i]) + ", Def = " + String.valueOf(ItemArrayDef[i]));
}
Spinner spnItem = (Spinner) view.findViewById(R.id.UseItem);
ArrayAdapter<String> adpItem = new ArrayAdapter<String> (context, R.layout.spinnerrow, ItemArrayList);
spnItem.setAdapter(adpItem);
spnItem.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
//String city = "The item is " + parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(), city, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
Thanks in advance
How about using a Hashtable to map what you display in the spinner to your more detailed popup string?
EDIT:
Here's a primitive and possibly non compiling modification to your code using a hashtable as described:
// EDIT #1: Create a hashtable to lookup stuff:
final Hashtable<String, String> vals = new Hashtable<String, String>();
for(int i = 0; i < ItemArrayName.length; i++)
{
vals.put(ItemArrayName[i], ItemArrayName[i] + "\nAtk = " + String.valueOf(ItemArrayAtk[i]) + ", Def = " + String.valueOf(ItemArrayDef[i]));
}
Spinner spnItem = (Spinner) view.findViewById(R.id.UseItem);
// EDIT #2: Extract the array of hash keys to show in your list:
ArrayAdapter<String> adpItem = new ArrayAdapter<String> context, R.layout.spinnerrow, vals.keySet().toArray(new String[vals.size()]));
spnItem.setAdapter(adpItem);
spnItem.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
// EDIT #3: retrieve the full string from the hashtable using "get":
String city = "The item is " + vals.get(parent.getItemAtPosition(position).toString());
//Toast.makeText(parent.getContext(), city, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
Try mapping your short text to your long text.
HashMap<String,String> itemValues = new HashMap<String,String>();
itemValues.add("short text","the full long text that pops up when item is selected");
String longTextToDisplay = itemValues.get(currentSelectedShortText);
Of course this is a simplified example and this could be made more flexible, but this is the basic idea. You're just saying "this short text goes with this long text."
Everyone makes this much harder than it has to be. If the data is displayed in the spinner already, you can grab it from there without having to refer to the backing data.
Assuming you have a LinearLayout containing the two textviews (call them tv1 and tv2) as your row layout for the spinner, and you want the value of tv2, you could do this:
public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3)
{
TextView tvResult = (TextView) view.findViewById(r.id.tv2);
String city = tvResult.getText().toString();
}
EDIT
I misunderstood your question... that I know of there is no way to make the closed spinner box display text different from the actual selection within the spinner using an ArrayAdapter. If there is, I'd be interested in seeing/reading about it.
I can think of a way to do it with a CursorAdapter, but as I said above, I can't think of any way to manage it for an ArrayAdapter.
The one option I can think of would be to find the spinner class in the android source, copy it out and modify it to make your own spinner class that is capable of such a function.
Related
I created a Data-Base table student which contains two fields like student_id and student_name. This table contains some data for student.
My actual problem is I want to set ID and name of student in spinner like in html select tag, so when select spinner item I must get this ID to get another data from database.
You can have two arraylist for name and id;
List<String> sIds = new ArrayList<String>();//add ids in this list
List<String> names = new ArrayList<String>();//add names in this list
Then you can retrive here inside spinner select. It will work even if two names are same in the spinner which may be the case:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int id = sIds.get(position);//This will be the student id.
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
To add values into Spinner you can do it something like this Test
public class Test extends Activity
{
ArrayList<String> InfoStudent = new ArrayList<String>();
ArrayList<String> IdStudent = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//Here you'll have to make a query to get ID and Name then with
InfoStudent.add("TheID" + "InfoStudentReturnedByQuery");
//TheID should go in IdStudent ArrayAdapter and InfoStudentReturnedByQuery should go in InfoStudent ArrayAdapter
// Then you create the arrayAdapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Test.this
,android.R.layout.simple_spinner_item,difficultyLevelList);
// Set the Adapter
spinner.setAdapter(arrayAdapter);
If you want to know what spinner is selected you should do something like this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView,
View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"You Selected : "
+ TheMainAdapterOfStudents.get(i)+" Student ",Toast.LENGTH_SHORT).show();
}
This only it's a guide how to, hope it helps :)
1. Declare type Like:
public class Item
{
public long id;
public String name;
}
2. Fill spinner with data (Item[]):
Item[] data = new Item[3];
data[0] = new Item(1, "Item 0");
data[1] = new Item(2, "Item 1");
data[2] = new Item(3, "Item 2");
ArrayAdapter<Item> dataAdapter = new ArrayAdapter<Item>(this,android.R.layout.simple_spinner_item, data);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
3. Get your id where you need it:
Item item = (Item)spinner.getSelectedItem();
return item.id;
Assuming I am reading your list correctly, if you want to set an Id to your Spinner programically just use..
mSpinner.setId(int)
In this code replace mSpinner with the reference to your Spinner and int with the desired Id
The title says it all, I'm trying to do that because I obtain a list from parse and the user must choose one of them from a spinner and based on the user's choice it responds and sets another filter to another spinner. The problem I'm having (really not much of a deal, but it's something that I'd like to do) is that when the list gets obtained from Parse it automatically selects the first one it retrieves and fills all the spinners automatically (of course you can change it and it will work perfectly).
The question is, how do I retrieve a list from parse, add it into a spinner in a way that it doesn't fill everything by itself ?
Here's my piece of code where I obtain the list and add it into a spinner:
groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Group Item Selected Ran");
final String spinI1 = groupSpinner.getSelectedItem().toString();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("grupo", spinI1);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
int size = 0;
size = parseObjects.size();
String[] mod = new String[size];
for (int i = 0; i < parseObjects.size(); i++) {
mod[i] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i]);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(HandsetLocation.this, android.R.layout.simple_spinner_item, mod);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
hospitalSpinner.setAdapter(spinnerArrayAdapter);
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Any help would be appreciated greatly!
At my phone so cannot properly indent the code but here it goes:
String[] mod = new String[size+1];
mod[0] = "select value";
for (int i = 0; i < parseObjects.size(); i++) {
mod[i+1] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i+1]);
}
I have an app that gathers points from checkboxes in a listview. The checkboxes are dynamically added along with the items of the listview. Each time a checkbox is clicked, I add points to a total. The manner in which I do this works fine as long as all the list items fit on the screen. When the list gets long enough to cause it to scroll, I lose the values I had previously checked when I scroll down the list. So, my scrolling the list causes the points to reset. I feel pretty confident it has something to do with losing focus from the checkboxes and/or gaining focus from the click to the listview itself, that causes this reset in points.
IMPORTANT EDIT: Ok, so it doesn't actually take a simple click and SLIGHT scroll of the listview to cause this to happen. I have to actually get the previous CHECKBOX scrolled out of view just enough to make the points reset. WTF?
Here's some code...
Here is my entire custom adaptor that handles the checkbox:
public class ScoreListAdapter extends BaseAdapter {
private ArrayList<ScoringInfo> data;
Context c;
ScoringInfo scr;
ScoreListAdapter (ArrayList<ScoringInfo> data, Context c){
this.data = data;
this.c = c;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int pos) {
// TODO Auto-generated method stub
return data.get(pos);
}
public long getItemId(int pos) {
// TODO Auto-generated method stub
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.score_list_row, null);
}
TextView subtaskView = (TextView)v.findViewById(R.id.subtask);
TextView maxPointsView = (TextView)v.findViewById(R.id.max_points);
scr = data.get(pos);
subtaskView.setText(scr.subtask);
maxPointsView.setText("Points: " + Integer.toString(scr.maxPoints));
final CheckBox checkBox = (CheckBox) v.findViewById(R.id.score_box);
checkBox.setTag(R.string.subtask_num, scr.subtaskNum);
checkBox.setTag(R.string.score, scr.maxPoints);
checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int subNum = Integer.parseInt(checkBox.getTag(R.string.subtask_num).toString());
int score = (Integer) checkBox.getTag(R.string.score);
if (((CheckBox)v).isChecked()) {
score =(Integer) checkBox.getTag(R.string.score);
Challenge.subtaskScores.put(subNum, score);
scr.addToTotalPoints(score);
updatePoints(scr.getTotalPoints());
}
else {
if (Challenge.subtaskScores.containsKey(subNum))
Challenge.subtaskScores.remove(subNum);
scr.addToTotalPoints(-score);
updatePoints(scr.getTotalPoints());
}
}
});
return v;
}
public void updatePoints(int total){
TextView scrUpdate = (TextView) ((Activity)c).findViewById(R.id.curr_score_view);
Challenge.totalPoints1 = total;
int grandTotal = Challenge.totalPoints1 + Challenge.totalPoints2;
scrUpdate.setText("Current Score: " + grandTotal);
}
}
Here is what I feel is the relevant code from Challenge.class:
public void createScoringList() {
// Builds two lists: one for the tasks that do not allow partial points, and
// another for the tasks that DO allow partial points. The lists are stacked
// on top of each other. This was the only way I could come up with to present
// two types of layouts for the two types of point input. This may need to be
// reconsidered.
ListView scoreList = (ListView) findViewById(R.id.score_list);
ListView scoreListPartial = (ListView) findViewById(R.id.score_list_partial);
ArrayList<ScoringInfo> objList = new ArrayList<ScoringInfo>();
ArrayList<ScoringInfo> objListPartial = new ArrayList<ScoringInfo>();
ScoringInfo scrInfo;
// The ScoringInfo object holds the various fields that are associated with each subtask.
infoView = (TextView) findViewById(R.id.chall_team_config_show);
infoView.setText(chall_name + " (id: " + challenge_id + ")\nTeam: " + team_num +
"\nConfiguration: " + randomConfig);
for (int i = 0; i < subTaskList.size(); i++) {
subtask_num = subTaskList.get(i).subtask_num;
max_points = subTaskList.get(i).max_points;
partial_points_allowed = subTaskList.get(i).partial_points_allowed;
task_name = subTaskList.get(i).task_name;
scrInfo = new ScoringInfo();
scrInfo.setMaxPoints(max_points);
scrInfo.setSubtask(task_name);
scrInfo.setSubtaskNum(subtask_num);
if (partial_points_allowed == 1)
objListPartial.add(scrInfo);
else
objList.add(scrInfo);
}
// There is a custom adapter for both possible lists should the challenge need it.
scoreList.setAdapter(new ScoreListAdapter(objList , this));
scoreListPartial.setAdapter(new ScoreListAdapter2(objListPartial, this));
}
No doubt I forgot something. If there's confusion over my question, please ask for clarification. This is driving me nuts, and keeping me up all night.
Your problem is as stated by #Patrick on the first comment that your are not saving the CheckBox state. You will need to save it to somewhere, a boolean array for example.
Then when you recreate the view you will get the saved value from the array and check/uncheck the CheckBox.
I am trying to make a GPA calculator. I have a bunch of spinners in two columns. 7 in each. I have put in an array of strings to be displayed in the drop down list. Now, I want to write code in java for saying if the user selects "four" from the drop down list, then the input should be considered as number 4 later to multiply it with for example if the user chose grade A, then to multiply with 4. How do I do this? I created an array adapter but it's not working. i am getting "Nan" as the answer. I have looked it up and it says Nan is displayed when the number is undefined. Any help would be appreciated. Thank you!
Should I be using some kind of onClickListener like I used for my button? How does the computer know that it has to equate gradepoint to 4 if the user picks grade A?
This is what I did (which obviously is wrong):
if(spinner1.getSelectedItem().equals("A+")) gradepoint1=4.00;
if(spinner1.getSelectedItem().equals("A")) gradepoint1=4.00;
if(spinner1.getSelectedItem().equals("A-")) gradepoint1=3.67;
if(spinner1.getSelectedItem().equals("B+")) gradepoint1=3.33;
if(spinner1.getSelectedItem().equals("B")) gradepoint1=3.00;
if(spinner1.getSelectedItem().equals("B-")) gradepoint1=2.67;
if(spinner1.getSelectedItem().equals("C+")) gradepoint1=2.33;
if(spinner1.getSelectedItem().equals("C")) gradepoint1=2.00;
if(spinner1.getSelectedItem().equals("C-")) gradepoint1=1.67;
if(spinner1.getSelectedItem().equals("D+")) gradepoint1=1.33;
if(spinner1.getSelectedItem().equals("D")) gradepoint1=1.00;
if(spinner1.getSelectedItem().equals("D-")) gradepoint1=0.67;
if(spinner1.getSelectedItem().equals("F")) gradepoint1=0.00;
if(spinner1.getSelectedItem().equals("ABS")) gradepoint1=0.00;
I suggest you do something like this:
Before you're oncreate:
float[] gradeValues = { 4f, 3.67f, 3.33f, 3.00f, 2.67f, 2.33f, 2.00f,1.33f,1.00f,0.67f,0.00f,0.00f};
String [] gradeAlpabetic = {"A+","A","A-","B+","B","B-","C+","C","C-","D+","D","D-","F","ABS"};
Here the first value, 4f, has the position 0, and the next has 1 and so on.
The value "A+" will be at position 0 on the spinner, so this way we know which grade goes with which grade value.
In onViewCreated or OnCreate:
ArrayAdapter<String> gradesArrayAdap = new ArrayAdapter<String>(
getActivity(), R.layout.spinnerlayout, gradeAlphabetic);
gradesSpinner.setAdapter(GradesArrayAdapter);
gradeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
getGrades();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Then you put this outside the onViewCreated/onCreate.
public void getGrades(){
String grade = gradeSpinner.getSelectedItemPosition();
float theGrade = Float.parseFloat(gradeValue(grade);
System.out.println("Your grade in float is: " + theGrade);
}
Hope it helps.
You can have a hashmap of the values and then select the value based on the selected item
HashMap<String, Double> mGrades;
public void test(){
Spinner spinner1 = new Spinner(this);
mGrades = new HashMap<String, Double>();
mGrades.put("A+", 4.00);
mGrades.put("A", 4.00);
//Etc.....
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mGrades.keySet().toArray(new String[0]));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Log.d("TAG", String.valueOf(mGrades.get(mGrades.keySet().toArray()[pos])));
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
It may be a bit slower then using some other method, but hey. Its something simple.
Basically, I want to associate a "selected" option with an id, so instead of doing this (my current way):
Vector spinnerList = new Vector();
spinnerList.addElement("No");
spinnerList.addElement("Yes");
I'd be doing something like this (the Hashtable/Vector is just for Blackberry compatability):
String id = "3";
Hashtable spinnerMap = new Hashtable();
spinnerMap.put(id, "No");
spinnerMap.put(id, "Yes");
Currently, a selected "option" from the spinner prints out 0 or 1 (based on the "No", "Yes"). So, my question is, if I'm setting the spinners programatically from a map whose values I don't know (I just know ids), how do I do this?
Spinner spinner = new Spinner(this);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, spinnerList);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
System.out.println("Selected: " + arg2);
}
public void onNothingSelected(AdapterView<?> arg0) {
System.out.println("Nothing selected: " + arg0);
}
});
Your question is not very clear. What exactly do you want to accomplish?
If you just want to display different data than a simple list of strings I think you should consider creating a custom adapter.
Reverse your map, and you can do an easy lookup of the integer id based on the string returned.
int id = spinnerMap.get(spinner.getSelectedItem());