Generate Plain Text Fields Based on Chosen Spinner Value? - java

I'm currently working on creating an app in android studio. The problem I am facing is generating a number of "plain text" objects based on the number chosen in a spinner. I have included layout of the activity below.
layout of activity can be seen here
Once the "number of people" are picked, then the area to enter the peoples names will be generated based on that. Max number of people will be 4.
Any help on how to do this would be much appreciated!

I would suggest using an OnItemSelectedListener() on your spinner along with setting the setVisibility() of your 'person' fields.
This code will assume your minimum people to be 1. Each time a new value is selected from the spinner the fields will appear or disappear. Using GONE for visibility will hide the field but also remove the space used by it. Use INVISIBLE if you want to keep the space.
Also don't bother setting the visibility in the xml layout code as this can cause issues.
person1 = (EditText)findViewById(R.id.person1);
person2 = (EditText)findViewById(R.id.person2);
person3 = (EditText)findViewById(R.id.person3);
person4 = (EditText)findViewById(R.id.person4);
list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
spinnerValue = parent.getItemAtPosition(position).toString();
int value = Integer.parseInt(spinnerValue);
// Simpler logic for the visibility of the 'people' - kudos to RobCo for pointing this out//
person1.setVisibility(value>=1? view.VISIBLE:View.GONE);
person2.setVisibility(value>=2? view.VISIBLE:View.GONE);
person3.setVisibility(value>=3? view.VISIBLE:View.GONE);
person4.setVisibility(value>=4? view.VISIBLE:View.GONE);
/*
if (value == 1)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.GONE);
person3.setVisibility(View.GONE);
person4.setVisibility(View.GONE);
}
else if (value == 2)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.GONE);
person4.setVisibility(View.GONE);
}
else if (value == 3)
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.VISIBLE);
person4.setVisibility(View.GONE);
}
else
{
person1.setVisibility(View.VISIBLE);
person2.setVisibility(View.VISIBLE);
person3.setVisibility(View.VISIBLE);
person4.setVisibility(View.VISIBLE);
}
*/
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
Good luck.

You simply do it by setting the visibility of all the 4 EditTexts as false and set a listener to the spinner. And inside the listener add if else statement and depending upon the selection you can set the visibility on for the EditText fields.

Related

Get spinner selected item and passing data

What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.
UPDATE:
I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.
So this is my code for 1st activity, I will just put only one first :
btnAsia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("continent", "asia");
startActivity(intent);
}
});
This is the string array in strings.xml:
<string-array name="asia">
<item>Japan</item>
<item>Thailand</item>
<item>Vietnam</item>
<item>South Korea</item>
</string-array>
and this is the code in 2nd activity:
private void DestinationSpinner()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String continent = bundle.getString("continent");
switch (continent) {
case "asia":
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
break; }
and lastly this is the code for retrieve selected item from spinner:
public void AvailableAirlines()
{
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected=spinnerDestination.getItemAtPosition(position).toString();
if (continent.equals("asia") && selected.equals("Japan"))
{
availableAirlines.setText("Available airports");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.
I think the issue is this line if(selected=="Japan")
In Java you will need to use equals instead of the == operator.
The == checks if the two pointers are pointing to the same memory location.
Equals will compare their content.

how to get the items changed in spinner android studio

I want to change the value of the second spinner when the value of the first spinner is changed I tried the solutions but did not get an exact solution so anyone have a solution for that so please suggest or any question then please ask
ArrayAdapter<String> deptArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Province));
deptArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProvinceEyeTest.setAdapter(deptArrayAdapter);
deptArrayAdapter.notifyDataSetChanged();
Set a OnItemSelectedListener() first.
spinnerProvinceEyeTest.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString(); //this is your selected item
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
In onItemSelected() of above Listener, place your condition and set resource for second Spinner as:
If(selectedItem == "YourText"){
//Here, you're initalizing the second `Spinner`
ArrayAdapter<String> secondArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.YourList));
secondArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
secondSpinner.setAdapter(secondArrayAdapter);
}
else{
//Use any other list with arrayAdapter in case of other item selected.
//Use can use If-else-if or Switch to select different resource for different item of first spinner
}
Reference - Official Documentations.

Can't unselect ListView item when deleting it

Trudging my way through my introduction to Java and Android on a simple app and have run into an issue with ListView item selection. For one of my activities, I have a layout with two buttons, one of which is a "Delete" button, and a ListView of "passages" which are essentially timestamps for when a device has passed a sensor.
I have implemented the ability to click on an item to select it, which then enables the "Delete" button. A click of the "Delete" button removes the "passage" but I still end up with a selected item, which I don't want.
To implement selection, I added the following property to the ListView:
android:id="#+id/passagesListView"
android:choiceMode="singleChoice"
android:listSelector="#666666"
Selection is supported in OnCreate via a an OnItemClickListener:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_passages);
passagesViewAdapter = new PassagesViewAdapter(this, R.layout.passages_row_layout, passages);
final ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
assert passagesListView != null;
final Button deleteButton = (Button) findViewById(R.id.deleteButton);
deleteButton.setEnabled(false);
buildPassageList();
passagesListView.setAdapter(passagesViewAdapter);
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(ViewPassagesActivity.this, "position is " + position,
Toast.LENGTH_LONG).show();
view.setSelected(true);
passagesViewAdapter.notifyDataSetChanged();
selectedItemPos = position;
deleteButton.setEnabled(true);
}
});
}
This part works. However, there is some issue with deletion. As you can see in the comments, I have tried several methods that I found on StackOverflow that seemed to apply but, although I am able to delete the correct item from the list, I am still ending up with a selected item after the call to delete().
public void delete (View view)
{
final Button deleteButton = (Button) findViewById(R.id.deleteButton);
ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
if(selectedItemPos != -1)
{
Toast.makeText(ViewPassagesActivity.this, "remove " + selectedItemPos,
Toast.LENGTH_LONG).show();
// This did not work, which is strange since it worked similarly for selection when clicked
// View itemView = passagesListView.getChildAt(selectedItemPos);
View itemView = passagesViewAdapter.getView(selectedItemPos, null, passagesListView);
itemView.setSelected(false);
// This was also recommended in various posts on StackOverflow.
// Not clear whether clearChoices applies only to checkBoxes?
// passagesListView.clearChoices();
// passagesListView.requestLayout();
passages.remove(selectedItemPos);
deleteButton.setEnabled(false);
selectedItemPos = -1;
passagesViewAdapter.notifyDataSetChanged();
}}
}
I also ran into some issues trying to track which item is selected via setSelected() and getSelectedItemPosition() and punted by just tracking the index myself. So, as I am new to this, I'm sure there is something I am not understanding about Views or maybe something else such as a misunderstanding of how selection works?
How can I clear the selection?
Thanks!
I don't know what your PassagesViewAdapter class looks like. Maybe you can try
passagesViewAdapter.remove(passages.get(selectedItemPos));
passages.remove(selectedItemPos);
deleteButton.setEnabled(false);
selectedItemPos = -1;
passagesViewAdapter.notifyDataSetChanged();

Android spinners: How to write java code for them?

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.

Android 2.2 SDK - Create Spinner from Map?

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());

Categories

Resources