I have code to load spinner with class extends Activity. It is work successfully. This is the code ...
package nielpoenya.blogspot.com;
import....
public class MySQLite extends Activity implements OnItemSelectedListener {
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected.....
Now i want to try in class with extends Fragment, but it make it stop working..
package com.tugasbesar.medantrain;
import....
public class InfoJadwal extends Fragment implements OnItemSelectedListener {
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.info_jadwal, container, false);
spinner = (Spinner) getActivity().findViewById(R.id.spin_tujuan);
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
return rootView;
}
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(this.getActivity());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this.getActivity(), android.R.layout.simple_spinner_item,
lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected....
What was lacking with my fragment class ? Thanks
The error is in your onCreateView, you need to replace :
spinner = (Spinner) getActivity().findViewById(R.id.spin_tujuan);
by :
spinner = (Spinner) rootView.findViewById(R.id.spin_tujuan);
because with getActivity().findViewById() it will try to search a view in the contentview of your Activity, not in your Fragment.
Related
I am a beginner in Android. I have a spinner in my android code. It takes values from room database and once selected the value will be added to the listview. I have two issues
a) I am seeing values in my Spinner. But I am not able to select it and also onItemSelected for this spinner is not working
b) I would like to add a delete icon in my list view along with these values so that if the user is not interested in the value he can delete it.
Please can someone help me to resolve this?
Code is provided below:
public class MainActivity extends AppCompatActivity
{
private List<String> tasks = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private ListView consultantsList;
private Spinner spinner;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consultantsRepository consrepo =
new consultantsRepository (getApplicationContext());
ArrayList<String> oncons = consrepo.getConsultants();
ArrayAdapter<String> consarrayadapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
oncons);
adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,tasks);
ListView consultantsList = (ListView) findViewById(R.id.ListToSend);
consultantsList.setAdapter(adapter);
spinner = (Spinner) findViewById(R.id.consSpinner);
spinner.setAdapter(consarrayadapter);
consarrayadapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener
(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected
(AdapterView<?> parent, View view, int position, long id)
{
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), item,
Toast.LENGTH_LONG).show();
tasks.add(item);
adapter.notifyDataSetChanged();
}
});
}
}
try-
String item=spinner.getSelectedItem().toString();
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) {
}
});
}
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
I need to constantly update my Spinner after adding data which it shows.
Part of my code:
public class MainActivity extends AppCompatActivity {
ArrayAdapter<String> adapter;
Spinner spinner;
protected void onCreate(Bundle savedInstanceState) {
ArrayList<String> categories = databaseHelper.getAllCategories();
spinner = (Spinner) findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
In DatabaseHelper class, I make simple query which selects one column.
public class MainActivity extends AppCompatActivity {
ArrayAdapter<String> adapter;
Spinner spinner;
ArrayList<String> categories;
protected void onCreate(Bundle savedInstanceState) {
categories = databaseHelper.getAllCategories();
spinner = (Spinner) findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
private function updateSpinner(){
categories.clear();
categories.addAll(databaseHelper.getAllCategories());
adapter.notifyDataSetChanged();
}
I am trying to insert an item into an Adapter that multiple Spinners are using. However when I insert into the adapter, I would like the Spinners to retain their original selection based off the object and not the position.
In the case below, the Spinner is originally selecting "four", but when I click the button to insert "three", the spinner is now set to "three" instead of updating to the new position of "four". How can I achieve this?
public class MyActivity extends Activity {
List list;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("four");
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, list);
spinner.setAdapter(adapter);
// set selection to "four"
spinner.setSelection(2);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//list.add(2, "three") causes the same problem
adapter.insert("three", 2);
adapter.notifyDataSetChanged();
}
});
}
Should you call spinner.setAdapter(adapter); or a similar method after inserting a new value into the adaptor?
spinner.setSelection(list.indexOf("four"));
This will set the selection to "four" no matter on what position it is.