I have developed an application in which i have one edit text value of edit text is entered in spinner on button clicked an the item i select to delete gets deleted but the problem is that when i delete the last item of spinner whole spinner list flushes . i want to delete only selected item(only last item)
My code is as follows :
#Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
///////////////////////////////////////////////////////////////
// grab our UI elements so we can manipulate them (in the case of the
// Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner) findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText) findViewById(R.id.newSpinnerItemText);
Button addButton = (Button) findViewById(R.id.AddBtn);
Button clearButton = (Button) findViewById(R.id.ClearBtn);
// //////////////////////////////////////////////////////////////
// create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this,
android.R.layout.simple_spinner_item);
((ArrayAdapter) m_adapterForSpinner)
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
// m_adapterForSpinner.add("dummy item");
// //////////////////////////////////////////////////////////////
// add listener for addButton
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
clearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
// //////////////////////////////////////////////////////////////
// add listener for addButton
private void addNewSpinnerItem() {
Log.v("TAG", "addNewSpinnerItems called");
if (m_addItemText.getText().length() == 0) {// ||(m_addItemText.getText().toString()==
// " ")){
Log.v("In if cndtn", "textHolder is of length 0");
Toast.makeText(getApplicationContext(), "The textView is empty",
Toast.LENGTH_LONG).show();
//m_myDynamicSpinner.clearFocus();
//m_myDynamicSpinner.setFocusable(false);
//m_addItemText.setFocusable(true);
} else {
CharSequence textHolder = "" + m_addItemText.getText();
// else{
Log.v("else", textHolder + "");
// m_adapterForSpinner.add(textHolder);
// }
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
// m_adapterForSpinner.clear();
Log.v("TAG", "clearSpinnerItems called");
m_myDynamicSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// TODO Auto-generated method stub
Log.v("TAG", "Itemseleted to be removed is "
+ m_adapterForSpinner.getItem(pos).toString());
Log.v("Position of item", pos + "");
Object t = m_adapterForSpinner.getItem(pos);
Log.v("Object t ", (String) t);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.v("Item removed", t + "");
// m_myDynamicSpinner.setSelected(false);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// m_adapterForSpinner.add("dummy item");
}
for delete all items use:
mySpinner.setAdapter(null);
if you want to delete a particular item, remove this from m_adapterForSpinner and then:
mySpinner.setAdapter(m_adapterForSpinner);
Remember: methods "remove" and "clear" do not work with ArrayAdapter for Android 2.3.3 and lower. You'll receive error message "Unsupported operation.... bla bla bla". May be they work with Android 4.0 and up, I don't know.
Here is my solution which works even with minSdkVersion="5".
Create Spinner and fill it with test data
This code is in an activity form. Use ArrayList as data source for ArrayAdapter instead of array. It's important because you'll use its "remove" method later
List<String> reportFiles = new ArrayList<String>();
//fill some test data
reportFiles.add("aaaaaaaaaaaaa");
reportFiles.add("bbbbbbbbbbbbb");
reportFiles.add("ccccccccccccc");
//create spinner from corresponding layout xml file
Spinner spnReport = (Spinner) findViewById(R.id.spinner_report);
//create ArrayAdapter
ArrayAdapter reportAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item, reportFiles);
//set adapter to spinner
spnReport.setAdapter(reportAdapter);
//select first item in adapter - is not obligatory
spnReport.setSelection(0);
Remove selected item from Spinner
reportFiles.remove((String)spnReport.getSelectedItem());
//create new ArrayAdapter with modified ArrayList
reportAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,reportFiles);
//set new array adapter to spinner
spnReport.setAdapter(reportAdapter);
//select first item
spnReport.setSelection(0);
For me the accepted answer throwed an exception so what I did was this.
ArrayAdapter adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, Collections.emptyList());
spinner.setAdapter(adapter);
I had the same problem. Doing this did solve the problem, by emptying the spinner:
mySpinner.setSelection(Adapter.NO_SELECTION);
Related
how can get spinner values when I used if else then pass value to setonClick?
in my code, I used this methods to set spinner values
DatabaseReference chk_sub = FirebaseDatabase.getInstance()......
chk_sub.addValueEventListener(new ValueEventListener() {
if(xxxxxx){
List<String> sub = new ArrayList<>();
sub.add(0, getApplicationContext().getResources().getString(R.string.choose_sub));
sub.add("USA");
sub.add("CA");
ArrayAdapter<String> dataSpinnerAdapter;
dataSpinnerAdapter = new ArrayAdapter(getApplication(), android.R.layout.simple_spinner_item, sub);
dataSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataSpinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).equals(getApplicationContext().getResources().getString(R.string.choose_sub))){
//do nothing
} else {
spinner_item = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(),"Selected : "+item, Toast.LENGTH_SHORT).show();
}
}
}
and I hope I can get spinner sub value because I need to judge
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( -- how can get spinner value in here? --){
//
}else {
Toast.makeText(getApplication(), getApplicationContext().getResources().getString(R.string.must_upload), Toast.LENGTH_SHORT).show();
}
}
});
If you just want selected spinner item to be used in if(condition=spinner value) on click event of post i.e., post.onClick(), just get the spinner selected item
your code will look like this
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItem().equals("your compare value")){
// do whatever you want
}else {
Toast.makeText(getApplication(), getApplicationContext().getResources().getString(R.string.must_upload), Toast.LENGTH_SHORT).show();
}
}
});
I am new to android , I have an activity with 3 multiple spinners as bellow
Spinner 1:department
Spinner2:semester
Spinner3:subjects
and one button
spinner1 shows the department on select of department it has to display the semester on select of semester it has to display the subject spinner
NOTE:-SUBJECT SPINNER DEPENDS ON THE SELECTION OF SEMESTER SPINNER AS WELL AS DEPARTMENT SPINNER.
something like country, state, city spinners but suggest me some other ideas to do it because i am using string resources to list the items of spinners
Please help me
Try something like this in your activity.
Firstly, make your activity implement AdapterView.OnItemSelectedListener & View.OnClickListener.
private Spinner mDepartmentSpinner;
private Spinner mSemesterSpinner;
private Spinner mSubjectSpinner;
private Button mButton;
// Values to fill first spinner with.
private String[] mDepartments = {
"Department 1",
"Department 2",
"Department 3",
"Department 4",
};
private String[] mSemesters;
private String[] mSubjects;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
// Find the spinners and button, declared in the activity's resource file
mDepartmentSpinner = (Spinner) findViewById(R.id.department_spinner);
mSemesterSpinner = (Spinner) findViewById(R.id.semester_spinner);
mSubjectSpinner = (Spinner) findViewById(R.id.subject_spinner);
mButton = (Button) findViewById(R.id.button);
// Initialise spinner with values, placing them into a textview
mDepartmentSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mDepartments));
// Attach a listener for item selection
departmentSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Work out which spinner was selected
switch (view.getId()) {
case R.id.department_spinner:
// Get the selected item
String selectedDepartment = mDepartments[position];
// Get values to fill the semester spinner with, based on initial selection.
mSemesters = getSemestersFor(selectedDepartment);
// Initialise spinner with values, placing them into a textview
mSemesterSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mSemesters));
// Attach a listener for item selection
mSemesterSpinner.setOnItemSelectedListener(this);
break;
case R.id.semester_spinner:
// Get the selected item
String selectedSemester = mSemesters[position];
// Get values to fill the subject spinner with, based on second spinner selection.
mSubjects = getSubjectsFor(selectedSemester);
// Initialise spinner with values, placing them into a textview
mSubjectSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, subjects));
// Attach a listener for item selection
mSubjectSpinner.setOnItemSelectedListener(this);
break;
case R.id.subject_spinner:
mButton.setOnClickListener(this);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please select an option from each spinner.", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
// Go to your new activity, passing the selected subject
Intent intent = new Intent(this, SubjectActivity.class);
intent.putExtra("KEY_SUBJECT", (String) mSubjectSpinner.getSelectedItem());
startActivity(intent);
}
You can get the selected subject in the SubjectActivity like so...
#Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().getExtras().containsKey("KEY_SUBJECT") {
String subject = getIntent().getExtras().getString("KEY_SUBJECT");
}
}
Code for R.layout.text_view
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
You will need to implement the following methods yourself, I don't know your logic!
private String[] getSemestersFor(String department) {
// your code here
}
private String[] getSubjectsFor(String semester) {
// your code here
}
i've searched for a solution on google ,and on stack overflow.Yes i also know this could be a duplicate of another question asked in stack overflow but i tried the code snippets offered but none of them worked.Like: Taking user selection in a spinner, storing it in sharedPrefences, and using it in another activity and not getting integer value from SharedPreference and http://www.acnenomor.com/4379973p1/how-to-save-spinner-selecteditem-to-sharedpreferences
Here is my problem.I have the first activity,with two spinners from this tutorial http://www.mkyong.com/android/android-spinner-drop-down-list-example/ .On pressing the submit button,id like to save the selected values on SharesPreferences.On going to the second activity,i retrieve the selected values and display them on a text view.So that on the next app launch i go to the second activity to find the displayed saved values.I've been really stranded on this.Please point me in the right direction.Any help will be very much appreciated.
main activity
public class MyAndroidAppActivity extends Activity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
}
CustomOnItemSelectedListener.java
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I was finally able to do it. I used this tutorial (http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/)
I modified this code to fit what I wanted
public void onClick(View v) {
text = String.valueOf(spinner1.getSelectedItem()) + String.valueOf(spinner2.getSelectedItem());
sharedPreference.save(context, text);
I'm wondering if there is some trick to get the spinner updated from an edittext and onClick, before it gets committed to the database and retrieve from there? The list and the spinnerAdapter are set for retrieving values from database, so I'm aware that this question might be stupid.
I was thinking of this logic: enter some text to edittext, click ok, then temporary update the spinner with this text, before it goes to database, then do some other stuff in the activity and last commit everything to database. When you then close and open your activity again, the temporary value is lost, but the spinner gets populatet with the same value, but this time from database.
here is some code:
public class Vnos extends Activity {
//... some values
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
final List<VnosiDB> spinerItems = datasource.getAllNiz();
final ArrayAdapter<VnosiDB> spinnerAdapter = new ArrayAdapter<VnosiDB>(
this, android.R.layout.simple_spinner_item, spinerItems);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
String nizIzSpinerja = spinner.getItemAtPosition(
spinner.getSelectedItemPosition()).toString();
nizDB = nizIzSpinerja;
// nov niz
novNiz = (TextView) findViewById(R.id.dodaj);
novNiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(Vnos.this,
android.R.style.Theme_Holo_Dialog);
dialog.setContentView(R.layout.nov_niz);
TextView okNov = (TextView) dialog.findViewById(R.id.okNovNiz);
okNov.setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText inputNiz = (EditText) dialog
.findViewById(R.id.niz);
dialog.dismiss();
nizDB = inputNiz.getText().toString();
spinnerAdapter.notifyDataSetChanged();
}
});
dialog.show();
}
});
// ...some other code...
//...
//.. then, here I commit everything to database...
shrani = (TextView) findViewById(R.id.shrani);
shrani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vnosDB = (int) System.currentTimeMillis();
datasource.createVnos(zacetekDB, razlikaDB, nizDB, deloDB,
postavkaDB, dodatekDB, opisDB, vnosDB);
datasource.close();
Toast test = Toast.makeText(Vnos.this, "Vnos " + deloDB
+ " uspešen!", Toast.LENGTH_LONG);
test.show();
startActivity(new Intent("com.sandpit.jazstudent.URE"));
finish();
}
});
}
}
you are using ArrayAdapter, which is loaded by List<VnosiDB>. I assume that VnosiDB represents a record from the database. Why don't you just put a temporary record in this list when you need it?
List<VnosiDB> spinerItems = new ArrayList<VnosiDB>();
VnosiDB tempRec = new VnosiDB();
//set some values to the properties if you need to
spinnerItems.add(tempRec);
//populate the spinner with the temp record
I am trying to use a spinner control that will enable the user to delete any list element.
I have an 'add' button to add elements to the list, and a 'delete' button that removes the currently-displayed item from the list.
It works as expected except when the user deletes the last item in the list. At that point, all of the list's items are deleted.
My code is as follows:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// grab our UI elements so we can manipulate them (for the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
// create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
((ArrayAdapter)m_adapterForSpinner).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
// add listener for addButton
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
clearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
// add listener for addButton
private void addNewSpinnerItem() {
if (m_addItemText.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "The textView is empty", Toast.LENGTH_LONG).show();
} else {
CharSequence textHolder = "" + m_addItemText.getText();
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO
}
});
}
Does anyone have any ideas or suggestions on how to make this work?
The problem with your code is that the deletion is inside the onItemSelected callback, which gets called every time you are deleting an entry, thus deleting recursively until you effectively do not have any more entries to select. If you add a log inside that method:
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
you will see what I mean. I'm sure you can come up with more elegant code, but a quick and dirty hack is to set up a boolean flag to stop the recursion after the first deletion. See the snippet below and add the commented lines to your own code:
public class SpinnerTest extends Activity {
Spinner m_myDynamicSpinner;
EditText m_addItemText;
ArrayAdapter m_adapterForSpinner;
public static boolean cleared = false; // <--- set up a static boolean here
#Override
public void onCreate(Bundle savedInstanceState) {
// all your code unchanged
clearButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
cleared=false; // <--- nope, we did not clear the value yet
clearSpinnerItems();
}
});
}
// code unchanged
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
if (!cleared) // <--- did I do it already?
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
cleared=true; // I did it!
}
// code unchanged
i cann't understand your question.any way you can get the position of the selected item by using getSelectedItemPosition() method.