Android - Access ListView items when Activity is loaded - android

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

Related

how can get spinner values when I used if else then pass value to setonClick?

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

why is my onclick is messing up the code?

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.

Android select spinner item into alert dialog and text button disappear

I have a listview with a series of elements.
The click on an item of listview shows me a custom dialog.
In custom dialog I have a layout with:
A spinner
Two buttons (OK / ANNULLA)
This is the normal situation:
When I select the spinner, he shows a list of items.
When I select an item from the spinner, the text that was present on the buttons disappear in this way:
ps: this does not happen on Android 6.0, but it happens in the lower versions (such as 5.0)
The Code:
public void showDialogTagAssociation (Activity activity, Handler handler,
String msg, final MyOperator elemento, final BluetoothDevice device,
final int position){
mHandler = handler;
//-----------------------------------------------------
// DIALOG
dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
//-----------------------------------------------------
//---------------------------------------------------------------------
// LAYOUT
dialog.setContentView(R.layout.alert_dialog_custom_tag);
**// Spinner element
spinner = (Spinner) dialog.findViewById(R.id.spinner);**
// Spinner click listener
**spinner.setOnItemSelectedListener(new OnSpinnerItemClicked());**
//---------------------------------------------------------------------
//----------------------------------------------------------------------
// BUTTON OK
dialogButtonOK = (Button) dialog.findViewById(R.id.acd_btn_ok);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Devo assegnare il tag al nome....");
Log.d(TAG, "Nome: " +tmpNome+"\n" +
"TAG: "+device.getName()+" - "+device.getAddress());
dialog.dismiss();
}
});
// BUTTON ANNULLA
dialogButtonNO = (Button) dialog.findViewById(R.id.acd_btn_no);
dialogButtonNO.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//----------------------------------------------------------------------
dialog.show();
}
**private class OnSpinnerItemClicked implements android.widget.AdapterView.OnItemSelectedListener {**
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//NOME
tmpNome = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Thanks for the future help
Remove that piece of code:
spinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
and the thing which you want will still work.

Retaining items in a List View

I'm new to android development having some problems. I created a list view that is based on the user input. User has to enter a category in a dialog box and then it's added into the list. Works like a charm. The question is how do I retain those categories once the user exits from an app and starts it again ? When the user starts the app, the list is blank. Do I have to create a preference screen or something to save what the user types ? Here is my code:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
*/
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity
You can save it in SQLite DB, use CursorAdapter for your list view.
If the amount of data you want to save is relatively small you can use SharedPreferences to save the String data in your onClick method.
#Override
public void onClick(DialogInterface dialog, int which) {
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
// Add all string data to List<String> listItem
listItem.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
When the user leaves your activity, use the onStop() callback method to save your List<Strings> and store it through SharedPreferences.
#Override
private void onStop() {
super.onStop();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(getResources().getString(R.string.list_of_strings), new HashSet<String>(listItem));
editor.commit;
}
Using the onStart() callback, initialize your List and SharedPreferences. When the user navigates to your activity, your list will be reinitialized when it was saved via onStop().
Finally, iterate through your list, add your items to your ArrayList', create yourArrayAdapter` and set it to your list.
#Override
private onStart(){
super.onStart();
SharedPreferences mSharedPreferences;
mSharedPreferences = this.getApplicationContext().getSharedPreferences("MyPreferences", 0);
List<String> listItems = new ArrayList<String>(mSharedPreferences.getStringSet("ListOfStrings", null));
ListIterator li = listItem.listIterator(0);
while (li.hasNext()) {
newStatusList.add((String)li.next());
}
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}

Deleting last item from spinner deletes the entire list

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.

Categories

Resources