Spinner is not populated in a fragment - android

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

Related

Android - Two spinners in one Activity - Saving Data is not working

my problem is the following. I have 2 Spinners in one activity. I want that both spinner items should be saved in the DB. But there is a slight difference between both spinners:
Spinner 1: Is populated by data from other db-table - when it is the only spinner in the mentioned activity, it works.
Spinner 2: Has default values. I am not sure if added it correctly to my activity. Anyway, after i added it to my saving the data is not working anymore.
Please help me what am I doing wrong??
My Activity Code:
public class activity_transport extends AppCompatActivity {
private BottomNavigationViewEx bottomNavigationViewEx;
DatabaseHelper myDb;
Button btn_save;
Spinner ChooseProject,ChooseTransport;
EditText Entfernung,Price,MWST;
String selectedspinner, selectedTransport;
ImageView imageView2;
private static int PICK_IMAGE = 100;
Uri imageUri;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transport);
myDb = new DatabaseHelper(this);
ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
ChooseTransport = (Spinner) findViewById(R.id.ChooseTransport);
Entfernung = (EditText) findViewById(R.id.Entfernung);
Price = (EditText) findViewById(R.id.Preis);
MWST = (EditText) findViewById(R.id.MwSt);
btn_save=(Button) findViewById(R.id.btn_save);
//bildanzeigebereich im layout
imageView2=(ImageView) findViewById(R.id.imageView2);
loadProjectSpinnerData();
//loadTransportSpinnerData();
SaveData();
//+++++++++++++++Function to load the spinner data from SQLite database++++++++++//
private void loadProjectSpinnerData() {
// database handler
DatabaseHelper db = new DatabaseHelper (getApplicationContext());
// Spinner Drop down elements
List<String> projects = db.getAllProjects();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseProject.setPrompt("Projekt auswählen");
// attaching data adapter to spinner
ChooseProject.setAdapter(dataAdapter);
//Choose Transport Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {
new String("Auto"),
new String("Flugzeug"),
new String("Taxi"),
new String("Bahn")});
ChooseTransport.setAdapter(spinnerArrayAdapter);
// Drop down layout style - list view with radio button
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseTransport.setPrompt("Transport auswählen");
// attaching data adapter to spinner
ChooseTransport.setAdapter(spinnerArrayAdapter);
//Listener für den Projekt Spinner damit ich den Wert abspeichern kann
ChooseProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Spinner spinner = (Spinner) parent;
if(spinner.getId() == R.id.ChooseProject)
{
selectedspinner = (String) ChooseProject.getSelectedItem();
}
else if(spinner.getId() == R.id.ChooseTransport)
{
selectedTransport = (String) ChooseTransport.getSelectedItem();
}
//selectedspinner =String.ValueOf(parent.getItemAtPosition(pos));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/*private void loadTransportSpinnerData() {
// Spinner method to read the on selected value
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, new String[] {
new String("Auto"),
new String("Flugzeug"),
new String("Taxi"),
new String("Bahn")});
ChooseTransport.setAdapter(spinnerArrayAdapter);
// Creating adapter for spinner
//ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseTransport.setPrompt("Transport auswählen");
// attaching data adapter to spinner
ChooseTransport.setAdapter(spinnerArrayAdapter);
//Listener für den Projekt Spinner damit ich den Wert abspeichern kann
ChooseTransport.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//selectedspinner =String.ValueOf(parent.getItemAtPosition(pos));
selectedTransport = (String) ChooseTransport.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}*/
//++++++++++++Save Data++++++//
public void SaveData(){
btn_save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.createTransport(
selectedspinner,
selectedTransport,
Integer.valueOf(Price.getText().toString()),
Integer.valueOf(MWST.getText().toString()),
Integer.valueOf(Entfernung.getText().toString()),
imageViewToByte(imageView2)
);
if(isInserted=true)
Toast.makeText(activity_transport.this, "Daten gespeichert", Toast.LENGTH_LONG).show();
else
Toast.makeText(activity_transport.this, "Daten nicht gespeichert", Toast.LENGTH_LONG).show();
}
}
);
}
}
EDIT:
I tried to run the app by setting a few breakpoints.
When trying to run this line selectedTransport = (String) ChooseTransport.getSelectedItem(); the debugger posts Cannot find local variable 'ChooseTransport'
I solved the problem:
I implemented an own method for ChooseTransport- Spinner and now it works. I also figured out that the order how I add the data to the DB was not right. I changed this too.
See here my method for my second spinner:
private void loadTransportSpinnerData(){
ArrayAdapter<CharSequence> spinnerArrayAdapter = ArrayAdapter.createFromResource(this, R.array.transport, android.R.layout.simple_spinner_dropdown_item);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseTransport.setPrompt("Transport auswählen");
ChooseTransport.setAdapter(spinnerArrayAdapter);
ChooseTransport.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
selectedTransport = (String) ChooseTransport.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}

Spinner is not working in Fragment

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

multiple spinner android depend on each other

i have 3 spinners, first spinner is txt_kategori ;
second txt_kondisi ;
third txt_penanganan ; the second depends on the first and the third depends on the second input, here is my code
txt_kategori.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(view.getContext(), android.R.layout.simple_spinner_item, condition[position]);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
txt_kondisi.setAdapter(spinnerArrayAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
txt_kondisi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(view.getContext(), android.R.layout.simple_spinner_item, handling[position]);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
txt_penanganan.setAdapter(spinnerArrayAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
the problem is java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(view.getContext(), android.R.layout.simple_spinner_item, handling[position]);
Use ActivityName.this instead view.getContext()
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(view.getContext(), android.R.layout.simple_spinner_item, condition[position]);
change to
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(ActivityName.this, android.R.layout.simple_spinner_item, condition[position]);

I want to display selected item with some title in Spinner,Like item is:item6

I am new in android ,I want work like, In Spinner if i select any other items form array,that item should get selected including with some text,For example,if My spinner having 10 items,if i select 6th item that item should display like "Your Item Is: Item6",This should be display in my spinner as first item,After select of items form the array,Please help me ,,Thanks in advance..
String[] categories = {"Select one","Automobile","Computers","Education"};
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
then onItemSelected Listerner Do :-
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
categories[0] = item;
ArrayAdapter<String> newdataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
spinner.setAdapter(newdataAdapter);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
ArrayAdapter arrayAdapter = null;
String[] list=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//you can replace the below list with your list
list = {"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto"};
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner.setPrompt("Your selected item is:"+list[position]);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}

Change content of spinner dynamically to another spinner's item

i have too spinners , spinner and spinner2, first one has a standard menu, the second must change relative to items from spinner.
am trying to get the position of item selected in spinner and then put it as a parametre into my method item2sp to change spinner's 2 items.
but i doesn't change, i keep getting only the first item menu in spinner2, how can i fix it help me please.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner spinner2;
List<String> categories;
List<String> ndp;
List<String> ps;
ArrayAdapter<String> dataAdapter;
ArrayAdapter<String> ndpAdapter;
ArrayAdapter<String> psAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// Spinner Drop down elements
categories = new ArrayList<String>();
categories.add("NDP");
categories.add("PS");
categories.add("PA");
categories.add("PC");
categories.add("PH");
ps = new ArrayList<String>();
ps.add("AA");
ps.add("BB");
ps.add("CC");
ndp = new ArrayList<String>();
ndp.add("RP");
ndp.add("AFF");
ndp.add("RPA");
// Creating adapter for spinner
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
psAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ps);
ndpAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ndp);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
psAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ndpAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public void itemsp2 (int position){
switch (position){
case 0:
spinner2.setAdapter(ndpAdapter);
Toast.makeText(getBaseContext(), ""+position, Toast.LENGTH_LONG).show();
break;
case 1:
spinner2.setAdapter(psAdapter);
Toast.makeText(getBaseContext(), ""+position, Toast.LENGTH_LONG).show();
break;
}
}
// int position = spinner.getSelectedItemPosition();
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
itemsp2(position);
// Showing selected spinner item
// Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
iller is my First List and I set this list my firs spinner then I implements onItemSelected method for this spinner. In this method you can add your second spinner with difrent List.
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
List<String> iller = new ArrayList<String>();
iller.add("İl Seçiniz..");
iller.add("Antalya");
iller.add("Burdur");
iller.add("Bursa");
iller.add("Balıkesir");
iller.add("Giresun");
iller.add("İstanbul");
ArrayAdapter<String> illerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, iller);
illerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(illerAdapter);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner2.setVisibility(View.INVISIBLE);
editText = (EditText) findViewById(R.id.editText);
editText.setVisibility(View.INVISIBLE);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int itemId = (int) id;
if (itemId == 1) {
iller.remove("İl Seçiniz..");
antalyaİlceler = new ArrayList<String>();
antalyaİlceler.add("İlçe Seçiniz..");
antalyaİlceler.add("Konyaaltı");
antalyaİlceler.add("Muratpaşa");
antalyaİlceler.add("Alanya");
antalyaİlceler.add("Manavgat");
ArrayAdapter<String> antalyaİlcelerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, antalyaİlceler);
antalyaİlcelerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(antalyaİlcelerAdapter);
spinner2.setVisibility(View.VISIBLE);
editText.setVisibility(View.VISIBLE);
} else if (itemId == 2) {
burdurİlceler = new ArrayList<String>();
burdurİlceler.add("İlçe Seçiniz..");
burdurİlceler.add("Bucak");
burdurİlceler.add("Tefenni");
burdurİlceler.add("Gölhisar");
burdurİlceler.add("Ağlasun");
ArrayAdapter<String> burdurİlcelerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, burdurİlceler);
burdurİlcelerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(burdurİlcelerAdapter);
spinner2.setVisibility(View.VISIBLE);
editText.setVisibility(View.VISIBLE);
}

Categories

Resources