Spinner is not working in Fragment - android

My application crashes when I am using Spinner in Fragment.
public class TestRideFragment extends Fragment implements AdapterView.OnItemSelectedListener {
String[] country = { "India", "USA", "China", "Japan", "Other", };
public TestRideFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_test_ride, container, false);
View v = inflater.inflate(R.layout.fragment_test_ride, container, false);
Spinner spin = (Spinner) getView().findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the country list
ArrayAdapter aa = new ArrayAdapter(getContext(),android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
return v;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { }
#Override
public void onNothingSelected(AdapterView<?> adapterView) { }
}
Could anyone help me spot the issues with my code, please?

You are trying to get view before it's being created, so that's why it is returning null.
So, you can do like,
Spinner spin = (Spinner) v.findViewById(R.id.spinner1);
or, you can move your code to onViewCreated where view will be created,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test_ride, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner spin = (Spinner) view.findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the country list
ArrayAdapter aa = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}

Change your code:
Spinner spin = (Spinner) getView().findViewById(R.id.spinner1);
Into this:
Spinner spin = (Spinner) v.findViewById(R.id.spinner1);

Try using v.findViewById(R.id.spinner1) also make sure that spinner1 is declared in the xml layout fragment_test_ride
Try adding array in strings.xml
<array name="countries">
<item>India</item>
<item>USA</item>
<item>China</item>
<item>Japan</item>
<item>Other</item>
</array>
and in your xml
<android.support.v7.widget.AppCompatSpinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/countries"
android:id="#+id/spinner1" />
Remove the ArrayAdapter but do not this one will make your options static based on whats in the array declare on the string xml

Maybe the problem is in your adapter which should be;
ArrayAdapter<CharSequence> aa= ArrayAdapter.createFromResource(this,
country, android.R.layout.simple_spinner_item);
and you have;
ArrayAdapter<CharSequence> aa= ArrayAdapter.createFromResource(this,
android.R.layout.simple_spinner_item, country);

Related

Getting checkable list view into fragment

I am trying to have a checkable list view fragment pop up with a button at the top of the list view. After user clicks an item in the navigation menu, the main activity will be populated with my button and list view fragment. I'm getting 'invoke virtual method' error, even though the element in declared. Here's some code.
My list fragment class:
public class ThingsManager extends Fragment {
ArrayList<String> selectedItems;
ListView checkable_list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(layout.things_manager_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}
public ThingsManager() {
// Required empty public constructor
}
}
List fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ThingsManager">
<TextView
android:id="#+id/things_manager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Things Manager"
android:textSize="25dp"/>
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/checkable_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Should I be controlling the listview in MainActivity or in the FragmentClass ?
Move your all your view initialization and listview setup code from onActivityCreated to onCreateView method.
And your this statement
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
is wrong. You have to find ListView from the view you have inflated in onCreateView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(layout.things_manager_fragment, container, false);
init(rootView);
return rootView;
}
public void init(View rootView){
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list = rootView.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}

"Error : cannot resolve symbol findViewById"

I'm having a trouble with findViewById but I can't find where the problem is.
Here's my FirstFragment class code:
public class VehicleInformation extends Fragment implements AdapterView.OnItemSelectedListener {
private TextView text_vehicle_no, text_chassis_no;
private TextView text_company_name,text_insurance_id;
RadioGroup radioGroup;
RadioButton radioButton;
private SpinnerAdapter text_vehicle_class;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_vehicle_information, container, false);
return rootView;
radioGroup = (RadioGroup) rootView.findViewById(R.id.insuranceYesNo);
text_vehicle_no = (TextView) rootView.findViewById(R.id.vehicle_no);
text_chassis_no = (TextView) rootView.findViewById(R.id.chassis_no);
Spinner spinner_vehicle_class = (Spinner) rootView.findViewById(R.id.vehicle_class);
Spinner spinner_vehicle_company = (Spinner) rootView.findViewById(R.id.vehicle_company);
Spinner spinner_vehicle_model = (Spinner) rootView.findViewById(R.id.vehicle_model);
Spinner spinner_vehicle_fuel = (Spinner) rootView.findViewById(R.id.vehicle_fuel);
Spinner spinner_vehicle_color = (Spinner) rootView.findViewById(R.id.vehicle_color);
Spinner spinner_vehicle_types = (Spinner) rootView.findViewById(R.id.vehicle_types);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.vehicle_class_array, android.R.layout.simple_spinner_item);
ArrayAdapter adapter1 = ArrayAdapter.createFromResource(this,R.array.vehicle_company_array, android.R.layout.simple_spinner_item);
ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this,R.array.vehicle_model_array, android.R.layout.simple_spinner_item);
ArrayAdapter adapter3 = ArrayAdapter.createFromResource(this,R.array.vehicle_fuel_array, android.R.layout.simple_spinner_item);
ArrayAdapter adapter4 = ArrayAdapter.createFromResource(this,R.array.vehicle_color_array, android.R.layout.simple_spinner_item);
ArrayAdapter adapter7 = ArrayAdapter.createFromResource(this,R.array.vehicle_type_array, android.R.layout.simple_spinner_item);
//specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter7.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//aaply the adapter to the spinner
spinner_vehicle_class.setAdapter(adapter);
spinner_vehicle_company.setAdapter(adapter1);
spinner_vehicle_model.setAdapter(adapter2);
spinner_vehicle_fuel.setAdapter(adapter3);
spinner_vehicle_color.setAdapter(adapter4);
spinner_vehicle_types.setAdapter(adapter7);
spinner_vehicle_class.setOnItemSelectedListener(this);
spinner_vehicle_company.setOnItemSelectedListener(this);
spinner_vehicle_model.setOnItemSelectedListener(this);
spinner_vehicle_fuel.setOnItemSelectedListener(this);
spinner_vehicle_color.setOnItemSelectedListener(this);
spinner_vehicle_types.setOnItemSelectedListener(this);
}
public void onStart(){
super.onStart();
EditText datePicker=(EditText) findViewById(R.id.datePicker);
datePicker.setOnFocusChangeListener(new View.OnFocusChangeListener(){
public void onFocusChange(View view, boolean hasfocus){
if(hasfocus){
DateDialog dialog=new DateDialog(view);
android.support.v4.app.FragmentTransaction ft =getFragmentManager().beginTransaction();
dialog.show(ft, "DatePicker");
}
}
});
}
public void radiobtn(View view) {
int radiobtnselect = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) view.findViewById(radiobtnselect);
Toast.makeText(VehicleInformation.this, radioButton.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String sSelected=adapterView.getItemAtPosition(i).toString();
Toast.makeText(VehicleInformation.this,sSelected,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Also showing error on line
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.vehicle_class_array, android.R.layout.simple_spinner_item);"
saying wrong 1st argument type
Also showing error on line Toast messsage saying cannot resolve method maketext
Unlike the Activity class, Fragment doesn't have a built-in findViewById() method. This means you need to use View.findViewById(), which you already are doing everywhere except in your onStart() method. Here, you can just change this line:
EditText datePicker=(EditText) findViewById(R.id.datePicker);
to this:
EditText datePicker=(EditText) getView().findViewById(R.id.datePicker);
As for your adapter and toast issues, the problem is that (again, unlike Activity), the Fragment class is not a subclass of Context, so you need to pass a different first argument. Try passing getContext() instead of VehicleInformation.this.

Spinner is not populated in a fragment

I am trying to add 2 spinner in a fragment.These spinners are interconnected.When user select a value,2nd spinner will be populated with value.
Example:1st spinner have 2 values as "Car" & "Bus".
When users select "car",2nd spinner will be populated by color of the car as "Red","Blue".Again,if user select Bus,2nd spinner will be populated by color of bus as "Green","White".
I have made this in mainactivity successfully.But when I try to implement in a fragment ,2nd spinner is not populated and also there is no error showing.
I am providing the code that I have tried to implement in fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_info_form, container, false);
//spCountries = (Spinner) v.findViewById(R.id.idCrimePlace);
//set the spinners
crimePlace = (Spinner) rootView.findViewById(R.id.idCrimePlace);
metro = (Spinner) rootView.findViewById(R.id.idMetro);
crimePlace.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
crimePlace.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spCrimePlace= String.valueOf(crimePlace.getSelectedItem());
//Toast.makeText(this, crimePlace, Toast.LENGTH_SHORT).show();
if(spCrimePlace.contentEquals("Car")) {
List<String> list = new ArrayList<String>();
list.add("Red");
list.add("Blue");
list.add("Others");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
metro.setAdapter(dataAdapter);
}
if(spCrimePlace.contentEquals("Bus")) {
List<String> list = new ArrayList<String>();
list.add("Green");
list.add("White");
list.add("Other");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item, list);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter2.notifyDataSetChanged();
metro.setAdapter(dataAdapter2);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
Try calling your adapter like:
ArrayAdapter dataAdapter = new ArrayAdapter(this.getActivity(),
android.R.layout.simple_spinner_item, list);
And also use equals() instead of contentEquals

Spinner Value is not updated on the List View

I have a spinner that let user choose a meal from a set of string array in xml. After the user selected the item, I put the selection into the database, and display on a Listview.
In my model, I have a toString(),
#Override
public String toString() {
return id + " " + note +"\n meal: " + this.meal;
}
In the controller class for editing the the meal, I have this,
public class EditNoteFragment extends Fragment implements
OnItemSelectedListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_edit,
container, false);
// populating the spinner with string array of time category
spinner = (Spinner) rootView.findViewById(R.id.spinner_meal_category);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity().getApplicationContext(), R.array.meal_array,
android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
meal = parent.getItemAtPosition(pos).toString();
Log.i(LOGTAG, "Got the meal: " + meal);
}
public boolean onOptionsItemSelected(MenuItem item) {
// I added the field variable meal into the datebase in this block of code
//note.setMeal(meal.toString());
}
}
I used log to verified that I got the user choice and stored in the field variable "meal" in my class, but when I run the application and the list displays meal as null.
I am certain that I have successfully added the meal into the database.
Here is the view class
public static class NoteFragment extends ListFragment {
TextView tx_list_note;
NoteDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
datasource = new NotesDataSource(getActivity());
datasource.open();
List<Note> notes = datasource.findAll();
if (notes.size() == 0) {
createData();
notes = datasource.findAll();
}
ArrayAdapter<Note> adapter = new ArrayAdapter<Note>(getActivity(),
android.R.layout.simple_list_item_1, notes);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes,
container, false);
return rootView;
}
}
}
in fragment_notes.xml, I have one single listview in the relative layout
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true"
>
</ListView>
Thank you very much for you help in advance. Any suggestion would be appreciated.

How do I populate spinner with global string array variable?

I am trying to populate a a spinner but I am getting an error with my String array saying "Array constants can only be used in initializers". My code works fine when i employ the string array as a local variable, but as a global variable it doesn't. I really need to be able to use my string array as a global variable. Thank you in advance. Here is my code:
deleteselection = (Spinner)view.findViewById(R.id.deletespinner);
ArrayAdapter<String> adapterdeletetype;
//createdenominationsarray = getResources().getStringArray(R.array.createdenominations); //<--works
//String [] createdenominationsarray = {"Select Portfolio", "Two", "Three"}; //<--works
createdenominationsarray = {"Select Portfolio", "Two", "Three"};// <--doesn'twork
adapterdeletetype = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,createdenominationsarray){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
adapterdeletetype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
denominationselection.setAdapter(adapterdeletetype);
I did the same thing for one of my project and it works for me. Below is the code snippet for your reference..
ArrayList<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("German");
languages.add("French");
ArrayAdapter<String> langAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,languages);
ListView lv =(ListView)findViewById(R.id.listmain);
lv.setAdapter(langAdapter);
lv.setOnItemClickListener(new listclklisten(MainActivity.this));
public class listclklisten implements OnItemClickListener{
private Context parent;
public listclklisten(Context p){
parent=p;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TO DO your code here
}
}
inside string.xml Write:
<string-array name="spinner_array_environtment">
<item>Test</item>
<item>Production</item>
</string-array>
Inside your MainActivity.java :
public class MainActivity extends Activity {
Spinner spinner_environment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner_environment = (Spinner) findViewById(R.id.spinnerview);
adapter =ArrayAdapter.createFromResource(this, R.array.spinner_array_environtment,R.layout.spinner_phone);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner_environment.setAdapter(adapter);
}
Inside spinner_phone.xml :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13dp"
android:textColor="#4C4646" />
try this out. Hope it will help you.

Categories

Resources