I'm new to android development, I have some experiences on C# windows programming, but also very little. I'm working on an android application which uses spinners. So far, I found a tutorial which make spinner items, and displays spinner text in text view, as you select spinner item. The code lookes like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner =(Spinner)findViewById(R.id.sp);
text=(TextView)findViewById(R.id.tv);
ArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource(this, R.array.spinnerarray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new function());
}
public class function implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long id) {
// TODO Auto-generated method stub
String str=parent.getItemAtPosition(pos).toString();
text.setText(str);
}
I want to make an application, which will calculate some points, with the grade user would choose. Example: spinner will contain grades, such as Negative(1), Positive(2),Good(3), Very Good(4), Excellent(5). I want to achieve, that when an user chooses one grade, lets say very good, that the application will use the grade for very good which is 4, and it would transform it to some points, determined by me ( 1=20, 2=40,3=60,4=80,5=100). The points will be later used in calculation, but I have no idea how to assign points to certain grade. I hope you understand my question and thank you for your help.
I had the same app for windows, there I just used something like: if(veryGood.IsSelected==true){points = 20}, and i want to achieve same effect here.
You need a simple modifications on your function class:
public class function implements OnItemSelectedListener {
private final static int[] grades = new int[]{20,40,60,80,100}; //change in whatever you want. The length of the array must be the same of the adapter, or an ArrayIndexOutOfBoundException may be throwed.
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long id) {
text.setText(grades[pos] + " points!");
}
}
PS: in Java is a good practice to use upper case initial on class names e.g. Function instead of function.
Related
I found error in findViewById in static function.
my function is--
public static void onYearSelect() {
Spinner yearSelector;
String yearName;
yearSelector = (Spinner) findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
is there any way to solve this error!
can i store value of Spinner in yearName as String
You need to add view inside function as parameter.
public static void onYearSelect(View view) {
Spinner yearSelector;
yearSelector = (Spinner) view.findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
The view which contains your layout data.
When you call that function add onYearSelect(rootView) here rootView have the layout view.
EDIT 1:
What is View here ?
A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.
You can read more here.
Set setOnItemSelectedListener on spinner object and inside onItemSelected() you can set value of yearName. Like below,
yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String yearName = parentView.getItemAtPosition(position).toString()
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}});
I am confused about calling the spinner widget through a custom function. I am create an app in which I use spinner 20-35 times a spinner widget in single layout or activity. So for this i want to avoid the spinner code repetition again and again. i am creating a method for this i add the items to the spinner but i want to pass item value on select to other activity which bind to that class
Here is my code
Spin_tester.class
public class Spin_tester {
public String result;
public Context ctx;
public Spin_tester(Spinner spinner, final ArrayList<String> arraylist, final Context ctx , final String value) {
this.ctx= ctx;
ArrayAdapter<String> adpts =
new ArrayAdapter<String>(ctx, android.R.layout.simple_dropdown_item_1line,arraylist);
spinner.setAdapter(adpts);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
result = arraylist.get(position);
value = result ; // This is not working
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Test_Activity.class
public class Test_Activity extends AppCompatActivity {
ArrayList<String> data_list = new ArrayList<>();
Spinner spins;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
spins = (Spinner)findViewById(R.id.spinner);
data_list.add("1");
data_list.add("2");
data_list.add("3");
data_list.add("4");
Spin_tester asd = new Spin_tester(spins,data_list,this,value);
TextView txt = (TextView)findViewById(R.id.textView17);
}
}
Please help
Thanks in advance
Java is a pass-by-value language, not pass-by-reference. What this means is that setting value in setOnItemSelectedListener will only change value within that method — the result won't be passed back anywhere.
I see that you've place the result in result. That is where the calling program will find the answer.
Remove all instances of value from Spin_tester and Test_Activity and then have your main activity get the result from asd.result
I'm going to get a little meta at this point: I've only answered the question you actually asked, but this code is wrong on so many levels that you're never going to get it to work. I strongly suggest you work your way through the examples and tutorials in the documentation before you try to proceed any further.
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.
I am developing an android which has 4 spinners(A,B,C,D).
What I want to achieve is
If Spinner A is set to a value I want the remaining spinners to automatically change their value depending on the value of A
Like if I set Movie(in A)--->Ticket(in B)---->Place(in C)---->Time(D) to automatically fill in.
Thanking you
ChinniKrishna Kothapalli
I think you can set an OnItemSelectedListener to your Movie Spinner. The Spinner tutorial is an adequate example. Your OnItemSelectedListener may be like this:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
if (parent.getItemAtPosition(pos).toString().equals("firstMovieName")) {
// set spinner B/C/D with the corresponding information of first movie
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
The onItemSelected method above may be too simple for your need. You need figure it out how to link the four spinners yourself, but May it helps :)
Like this one, I've seen a few how-to's on this site, but truthfully, I'm not really getting it.
I want one spinner's content to be based upon a previous spinner selection, like in a States and Cities scenario. In general terms, what is the workflow? Are the results of the second spinner filtered based on the first spinner, or is the second spinner pointing to a completely different list based on the first spinner?
For my own simple learning project, I've built several string-arrays in the strings.xml (AL-Cities, AK-Cities, AR-Cities, etc). I'd like the city spinner to populate from the correct array based on a choice from the state spinner. But I'm wondering if instead I should just have one large multidimensional array of "Cities" that have a state abbreviation as an additional identifier, and then point the second spinner at that using the state abbreviation as a filter. It would seem like the former would provide better performance.
Any help (and code examples) would be greatly appreciated. I'm not new to programming (php mostly, so I guess scripting is more accurate), but I am new to java. My code so far with the spinners not linked is below with the second spinner pointing to an undifferentiated city_array.
Thank you!
public class Example1 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example1);
Spinner spinState = (Spinner) findViewById(R.id.spin_state);
ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(
this, R.array.state_array, android.R.layout.simple_spinner_item);
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinState.setAdapter(adapter3);
Spinner spinCity = (Spinner) findViewById(R.id.spin_city);
ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(
this, R.array.city_array, android.R.layout.simple_spinner_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCity.setAdapter(adapter4);
}
}
You could try and get the position from your first spinner, the one you've selected and then populate your second spinner after retrieving the proper array based on that position.
You have to listen for your first adapter being changed:
spinner. setOnItemSelectedListener(new MyOnItemSelectedListener());
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String choice = parent.getItemAtPosition(pos).toString();
populateSecondSpinnerMethod(choice)
}
}
public void onNothingSelected(AdapterView parent) { // Do nothing.
}
}