I have a button submit_house inside a navdraw that gets a onclick listener inside a different button's (add_house) onclick listener. submit_house is the button that ends the onclick of add_house and after that it gets a new onclick. yet for some reason the first submit_house onclick does not work ( the log command there really doesn't register). why is that?
code in main.java:
building_onclick = new View.OnClickListener() {
#Override
public void onClick(final View v) {
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
mMap.setOnMapClickListener(null);
// this line clears the arraylist
arrayList.clear();
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
building.emptyBuilding();
//the navdraw
buildingViewNavdraw(add_house, houseList);
//launches drawer
// locks drawer from opening from swipes
navDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// If the navigation drawer is not open then open it, if its already open then close it.
if(!navDrawer.isDrawerOpen(Gravity.RIGHT)) navDrawer.openDrawer(Gravity.RIGHT);
else navDrawer.closeDrawer(Gravity.LEFT);
//sets building latlng
building.setLat(point.latitude);
building.setLng(point.longitude);
building.setMarkerId(Double.toString(building.getLat()).replace(".","") + Double.toString(building.getLng()).replace(".",""));
View.OnClickListener add_houseOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: create alert dialog to get apartment number
house.setApartment("1");
houseEditNavdraw(status, activists, familyNameEdit, addressEdit, descriptionEdit, currentStatusEdit, submit_house, add_report);
isHouseUploaded = false;
isInBuilding = true;
house.setType("House");
//copies over content from building to house
house.setLat(building.getLat());
house.setLng(building.getLng());
house.setMarkerId("A" + house.getApartment() + building.getMarkerId());
house.setLocation(building.getLocation());
currentStatusEdit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (currentStatusEdit.getSelectedItem().toString().equals("קשר המשך")){
currentActivistsEdit.setVisibility(View.VISIBLE);
activists.setVisibility(View.VISIBLE);
currentActivists.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.VISIBLE);
} else if (currentStatusEdit.getSelectedItem().toString().equals("לא מעוניינים") || currentStatusEdit.getSelectedItem().toString().equals("מעוניינים")){
currentActivists.setVisibility(View.INVISIBLE);
activists.setVisibility(View.INVISIBLE);
currentActivistsEdit.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.VISIBLE);
} else if (currentStatusEdit.getSelectedItem().toString().equals("לא עונים")) {
currentActivists.setVisibility(View.INVISIBLE);
activists.setVisibility(View.INVISIBLE);
currentActivistsEdit.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.INVISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
// this line adds the data of the apartmnet and puts in your array
arrayList.add(house.getApartment() + ": " + "משפחת " + house.getName());
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
//sets the report onClicks
add_report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reportEditNavdraw(reportEdit, reportDateEdit, reportActivistsEdit, submit_report);
submit_report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
houseEditNavdraw(status, activists, familyNameEdit, addressEdit, descriptionEdit, currentStatusEdit, submit_house, add_report);
if (currentStatusEdit.getSelectedItem().toString() == "קשר המשך"){
activists.setVisibility(View.VISIBLE);
currentActivistsEdit.setVisibility(View.VISIBLE);
}
Date date = new Date();
Report rpt = new Report(reportActivistsEdit.getText().toString(), reportEdit.getText().toString(), reportDateEdit.getText().toString());
reportNameList.add(house.getMarkerId() + date.toString().replace(" ", "").replace(":", "").replace("GMT+", "").replace(".",""));
reportList.add(rpt);
lastReport.setVisibility(View.VISIBLE);
lastReport.setText(reportEdit.getText());
reportActivistsTitle.setVisibility(View.VISIBLE);
reportActivists.setVisibility(View.VISIBLE);
reportActivists.setText(reportActivistsEdit.getText());
reportDateTitle.setVisibility(View.VISIBLE);
reportDate.setVisibility(View.VISIBLE);
reportDate.setText(reportDateEdit.getText());
reportEdit.setVisibility(View.INVISIBLE);
reportDateEdit.setVisibility(View.INVISIBLE);
reportActivistsEdit.setVisibility(View.INVISIBLE);
submit_report.setVisibility(View.INVISIBLE);
reportDateEdit.setText("");
reportActivistsEdit.setText("");
reportEdit.setText("");
}
});
}
});
submit_house.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO: add safeguards against partial input
//sets data for "blank" drawer
familyName.setText(familyNameEdit.getText());
familyNameEdit.setVisibility(View.INVISIBLE);
familyName.setVisibility(View.VISIBLE);
address.setText(addressEdit.getText());
addressEdit.setVisibility(View.INVISIBLE);
address.setVisibility(View.VISIBLE);
description.setText(descriptionEdit.getText());
descriptionEdit.setVisibility(View.INVISIBLE);
description.setVisibility(View.VISIBLE);
currentStatusEdit.setVisibility(View.INVISIBLE);
currentStatus.setText(currentStatusEdit.getSelectedItem().toString());
currentStatus.setVisibility(View.VISIBLE);
if (currentStatusEdit.getSelectedItem().toString() == "קשר המשך"){
currentActivists.setText(currentActivistsEdit.getText());
currentActivistsEdit.setVisibility(View.INVISIBLE);
currentActivists.setVisibility(View.VISIBLE);
activists.setVisibility(View.VISIBLE);
house.setActivists(currentActivists.getText().toString());
}
submit_report.setVisibility(View.INVISIBLE);
add_report.setVisibility(View.INVISIBLE);
currentStatusEdit.setSelection(0, false);
//setting all the values to house
house.setName(familyName.getText().toString());
house.setAddress(address.getText().toString());
house.setDescription(description.getText().toString());
house.setStatus(currentStatus.getText().toString());
//upload reports to db
if (reportNameList.size() != 0){
for (int i = 0; i < reportNameList.size(); i++){
mDatabase.child("reports").child(reportNameList.get(i)).setValue(reportList.get(i));
}
//sets the report list to the house
house.setReport(reportNameList);
house.setLatestReport(reportNameList.get(reportNameList.size() - 1));
//clears the lists for next use
reportNameList.clear();
reportList.clear();
}
mDatabase.child("houses").child(house.getLocation()).child(house.getMarkerId()).setValue(house);
house.emptyHouse();
isHouseUploaded = true;
building.addHouse(house.getMarkerId());
Log.d("here", building.getHouses().toString());
emptyNavdraw();
buildingViewNavdraw(add_house, houseList);
}
});
}
};
add_house.setOnClickListener(add_houseOnClick);
add_houseOnClick.onClick(v);
submit_house.setVisibility(View.VISIBLE);
add_house.setVisibility(View.INVISIBLE);
submit_house.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.child("houses").child(building.getLocation()).child("B" + building.getMarkerId()).setValue(building);
LatLng latLng = new LatLng(building.getLat(), building.getLng());
Marker marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.building15x15)));
marker.setTag(building.getMarkerId());
building.emptyBuilding();
submit_house.setVisibility(View.INVISIBLE);
add_house.setVisibility(View.VISIBLE);
submit_house.setOnClickListener(null);
}
});
}
});
}
};
Implement your activity with View.OnClickListener interface.
It will implement a method with name onClick().
Now add this line in onCreate() method : submit_house.setOnClickListener(this);
And you can perform your work in onClick() as
public void onClick(View v)
{
if(v.id==R.id.submit_house)
{
//
}
}
But you cannot perform two different functions on a single button. For that
you have to use internal variable to identify the case.
Related
I have one EditText (edModelColor). when user click on edModelColor(EditText) then the custom dialog will be called.Custom dialog consist of RecylerView and searchview and one custom row for each item. Custom row contains ImageView(icon), TextView (colorNames) and checkbox for selection. When user click on any checkbox I passed the colorName and its position in adapter into method checkAndRemove. this method will add or remove the color name according to its adapter position and the colorNames will added into edModelColor(EditText). its working fine but the problem is that once the user click on edModelColor(EditText) again, I want to checked those checkboxes which are already checked inside CustomDialogbox.I have seen some articles online but I could not understand what they meant.
bodyColorDialog:
private void bodyColorDialog() {
TextView txtClose;
TextView tvCancel;
Button btnOk;
bodyColorDialog.setContentView(R.layout.ed_body_color_dialog);
bodyColorDialog.setCancelable(false);
txtClose = bodyColorDialog.findViewById(R.id.txtModelClose);
tvCancel = bodyColorDialog.findViewById(R.id.tvCancel);
btnOk = bodyColorDialog.findViewById(R.id.btnOk);
edBodyColorSearchView = bodyColorDialog.findViewById(R.id.edBodyColorSearchViewColor);
edBodyColorRecylerView = bodyColorDialog.findViewById(R.id.edBodyColorRecylerView);
edBodyColorRecylerView.setLayoutManager(new LinearLayoutManager(getContext()));
bodyColorArrayList.clear();
setUpBodyColorArrayList();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectionCMap = new HashMap<>();
selectionCMap = edBodyColorAdapter.selectionColorsMap;
for(String value : selectionCMap.values()){
/* tv.setText(tv.getText() + "\n" + value);*/
edBodyColor.append(value + ",");
}
bodyColorDialog.dismiss();
}
});
txtClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bodyColorDialog.dismiss();
}
});
tvCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bodyColorDialog.dismiss();
}
});
bodyColorDialog.show();
}
private void setUpBodyColorArrayList() {
bodyColorArrayList.clear();
String bodyColorName[] = getResources().getStringArray(R.array.body_color_array);
int bodyColorIcons[] = {R.drawable.red, R.drawable.black, R.drawable.violet, R.drawable.white,
R.drawable.orange, R.drawable.blue, R.drawable.green, R.drawable.yello};
for(int i =0; i < bodyColorIcons.length; i++)
{
bodyColorArrayList.add(new edModelBodyColor(bodyColorName[i], bodyColorIcons[i]));
}
edBodyColorAdapter = new edBodyColorAdapter(getContext(), bodyColorArrayList);
edBodyColorRecylerView.setAdapter(edBodyColorAdapter);
edBodyColorSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryString) {
edBodyColorAdapter.getFilter().filter(queryString);
return false;
}
#Override
public boolean onQueryTextChange(String queryString) {
edBodyColorAdapter.getFilter().filter(queryString);
return false;
}
});
}
edBodyColorAdapter.java
holder.checkBoxColor.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
int position = holder.getAdapterPosition();
clickedColorNamePosition = edBodyColorArrayList.indexOf(filteredArrayList.get(position));
String name = edBodyColorArrayList.get(clickedColorNamePosition).getBodyColorName();
Toast.makeText(context, "name = " + name, Toast.LENGTH_SHORT).show();
//this mthod will check if selected checkbox value is already present or not.
// It present then remove ( means user unchecked box) and if value is not there means user has selected checkbox
checkAndRemove(position,name);
}
});
checkAndRemove:
private void checkAndRemove(int position, String name) {
if(selectionColorsMap.containsKey(position)){
selectionColorsMap.remove(position);
Toast.makeText(context, "removed", Toast.LENGTH_SHORT).show();
}else {
selectionColorsMap.put(position, name);
Toast.makeText(context, "added", Toast.LENGTH_SHORT).show();
}
}
preview:
Conculusion: I want to check these checkboxes values when user click again on edBodyColor dialog..
I as can see, you are initializing the ArrayList of colors every time you are showing the dialog, that's why, you start always at initial state.
Instead, you should initialized the ArrayList inside onCreate() and reuse it every time to maintain the previous state.
I have created a Custom Listener interface for Button click in Adapter class, i followed this tutorial: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
Adapter:
holder.btnQtyIncrease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position);
}
cart = cartArrayList.get(position);
holder.textViewQuantity.setTag(cart);
if(cart.getQuantity() == 9) {
Toast.makeText(context, "Already reached", Toast.LENGTH_LONG).show();
return ;
}
else
{
cart.setQuantity(cart.getQuantity() + 1);
holder.textViewQuantity.setText(String.valueOf(cart.getQuantity()));
totalPrice = cart.getQuantity() * cart.getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
holder.textViewTotal.setText(cart.getTotal());
}
}
});
.....
return convertView;
}
And I have implemented Listener in Activity like this:
public class CartActivity extends Activity implements customButtonListener {
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CartActivity-onCreate", "onCreate");
setContentView(R.layout.activity_cart);
......
}
#Override
public void onResume()
{
super.onResume();
Log.d("CartActivity-onResume", "onResume");
}
#Override
public void onButtonClickListner(int position) {
totalPrice = CartArrayList.cartArraylist.get(position).getQuantity() * CartArrayList.cartArraylist.get(position).getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
subTotal = subTotal + totalPrice;
}
}
As you can see inside for loop i am setting and getting total of each and every list item, and then calculating subTotal of ArrayList items...
But whenever i do tap on btnQtyIncrease it makes change in total of list item price, but it would not effect on subTotal amount
You should change you logic in some way that it calculates the subTotal in adapter only and then just pass the final value to interface which will simply set it in then textview
So your code should look like:
holder.btnQtyIncrease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cart = cartArrayList.get(position);
holder.textViewQuantity.setTag(cart);
if(cart.getQuantity() == 9) {
Toast.makeText(context, "Already reached", Toast.LENGTH_LONG).show();
return ;
}
else
{
cart.setQuantity(cart.getQuantity() + 1);
holder.textViewQuantity.setText(String.valueOf(cart.getQuantity()));
totalPrice = cart.getQuantity() * cart.getPrice();
CartArrayList.cartArraylist.get(position).setTotal(totalPrice);
holder.textViewTotal.setText(cart.getTotal());
}
}
// calculate total here
if (customListner != null) {
customListner.onButtonClickListner(getTotalValue());
}
});
Define a method getTotalValue in adapter which will iterate through the array and find the subTotal value.
And then simply set it in the textView
#Override
public void onButtonClickListner(float subTotal ) {
txtView.setText(String.valueOf(subTotal));
}
Accordingly, change the interface signature as :
public void onButtonClickListner(float total);
How to update value in Activity when do change in Adapter class
To update data in Activity on btnQtyIncrease Button click. create custom event listener using interface which will trigger in Activity when any change made in Quantity.
See following example for creating custom Listener :
How to create our own Listener interface in android?
how to get the position from list on click of data.
i want access button in android.on the click of button of the adapter class it should give the position.
holder.beginDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
you can set the position as the tag
holder.beginDate.setTag(position); // set every time getting the View
and retrieve it using
// put this code where creating a new instance of holder
holder.beginDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (Integer) view.getTag();
// do anything using the position
}
});
After initialization of your button in getView() method write:
holder.beginDate.setTag(position);
and in your onClick() use:
holder.beginDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int position=Integer.parseInt(((Button)v).getTag().toString());
}
});
I have a listview populated with relativelayouts which have controls themselves. The problem is that I can't access these items before the activity UI is fully loaded (I get a null pointer exception. There's no OnActivityLoaded() method and here is what I tried to do:
Trying to access from OnStart() and OnResume();
I have a Custom Adapter but some of the functions I need to use
are in the main activity, so it's a no-go;
Using a Handler.postDelayed to access the elements after a given amount of
time. This works on high-end devices but on low-end ones the delay
time is not enough for loading (Even if I set it as high as 1000
ms) so I still get the null pointer exception.
So I need a better and proper way to access those widgets from the main activity.
Any thoughts? Is there a way to know when the UI is fully displayed?
Edit: here's my code that I need to access after the activity is loaded.
// These 4 widgets are ones from the relativelayout which is an item in the listview
homeSemester = (Spinner) findViewById(R.id.home_profile_semester);
homeSpecialty = (Spinner) findViewById(R.id.home_profile_specialty);
homefbPP = (ProfilePictureView) findViewById(R.id.home_profile_fbPP);
homefbName = (TextView) findViewById(R.id.home_profile_fbName);
// On click listeners
homeSemester.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
// These functions need to be in the main activity (have access to widgets, savedInstance bundles and shared preferences
// Configure specialty
configSpecialty();
// Load Schedule
loadSchedule();
// Refresh contact list
loadContacts();
configurePush();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getApplication(), "Please select your Semester!", Toast.LENGTH_SHORT).show();
Log.e("Initialization", "No semester selected! This should not happen!");
}
});
homeSpecialty.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
// Load schedule
loadSchedule();
// Refresh contact list
loadContacts();
// Save Data
saveData();
configurePush();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
Log.e("Initialization", "No specialty selected! This should not happen!");
}
});
// All of these depend on homesemester and homespecialty
// Read data
readSemester();
readSpecialty();
// Show all button
contactAll.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
if(contactAll.isChecked())
loadAll();
else
loadContacts();
}
});
if(contactAll.isChecked())
loadAll();
else
loadContacts();
loadSchedule();
if (sharedPref.getInt("LoggedIn", 0) == 0)
{
// Actions taken on buttons click
fbLogin.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
if (fbLogin.getText().toString().equals("Log in with Facebook"))
{
// Welcome Message
ab.setSubtitle("Logging in...");
// Login to Facebook
NetAvailable = isNetworkAvailable();
if (NetAvailable)
{
logIn();
}
else
{
ab.setSubtitle("No Internet Connection!");
}
editor.putInt("LoggedIn", 1);
editor.commit();
}
else
{
// Log Out
AlertDialog.Builder builderfb = new AlertDialog.Builder(Launch.this);
builderfb.setTitle("Log Out")
.setMessage("Are you sure do you want to Log Out?\n\nNote: Logging out from Facebook will close the application. Next time you start ULFG2 App2Date, you will be prompted to Log in manually.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
editor.putInt("LoggedIn", 0);
editor.commit();
finish();
}
});
AlertDialog welcomeMsg = builderfb.create();
welcomeMsg.show();
}
}
});
}
else
{
fbLogin.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// Log Out only is needed
AlertDialog.Builder builderfb = new AlertDialog.Builder(Launch.this);
builderfb.setTitle("Log Out")
.setMessage("Are you sure do you want to Log Out?\n\nNote: Logging out from Facebook will close the application. Next time you start ULFG2 App2Date, you will be prompted to Log in manually.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
editor.putInt("LoggedIn", 0);
editor.commit();
finish();
}
});
AlertDialog welcomeMsg = builderfb.create();
welcomeMsg.show();
}
});
}
homefbName.setText(sharedPref.getString("student_name", "Student"));
homefbPP.setProfileId(sharedPref.getString("student_id", ""));
}
In the onCreate():
ab = getSupportActionBar();
ab.setTitle("App2Date");
abDL = (DrawerLayout) findViewById(R.id.MainLayout);
abLV = (ListView) findViewById(R.id.list_slidermenu);
LayoutInflater mInflater = (LayoutInflater) getApplicationContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
navDrawerItems = new ArrayList<View>();
navDrawerItems.add(mInflater.inflate(R.layout.drawer_profile, null));
adapter = new NDListAdapter(getApplicationContext(), navDrawerItems);
abLV.setAdapter(adapter);
abLV.setDivider(null);
abLV.setDividerHeight(0);
// setting the nav drawer list adapter
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
abDT = new ActionBarDrawerToggle(this, abDL,
R.drawable.ic_navigation_drawer,
R.string.drawer_open,
R.string.drawer_close)
{
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(R.string.drawer_close);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(R.string.drawer_open);
}
};
abDL.setDrawerListener(abDT);
abDT.setDrawerIndicatorEnabled(true);
And I'm getting the null pointer exception in the onCreate() if I call the first lines of code (Under Edit:)
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.