I have a listview which I want to edit from a dialog box. I've read from googling that I need to notifyDataSetChanged() on the listview, however when I try to do this I get an error:
The method notifyDataSetChanged(View) is undefined for the type ListView
My listview is set originally at the top of my code with just a:
ListView listView;
It's then set in a routine on the onload
public void loadItems(){
//Removed - just getting the data
int rowCount;
rowCount = mCategory.size();
listView = (ListView) findViewById(R.id.lvItems);
int[] colors = {0, 0xFFFF0000, 0};
listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
listView.setDividerHeight(1);
listView.setAdapter(new CustomAdapter());
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
loadPopup(mDescription.get(position).toString(), mCountList.get(position).toString(), mTemplatecode.get(position).toString());
}
});
//Removed - Tidying up
}
The dialog box that is loaded on the onlick has a simple interface, a minus button, a plus button, a text box and a go button. The number in the textbox is changed which does a db call. When the dialog box closes I want it to refresh the listview behind to reflect the new change. I.e. basically re-run the loadItems() routine again.
This is what happens when you click the go button on the dialog. I'm obviously putting the notifyDataSetChanged in the wrong place as it wont even run.
btnGo.setOnClickListener( new View.OnClickListener(){
#Override
public void onClick(View v) {
addAsset(v, AssetDesc, txt.getText().toString(), templateCode);
listView.notifyDataSetChanged();
loadItems();
dialog.dismiss();
}
});
Custom adapter:
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
return mDescription.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
LayoutInflater inf=getLayoutInflater();
View v=inf.inflate(R.layout.noncriticalasset, arg2,false);
TextView tv=(TextView)v.findViewById(R.id.txtOption);
TextView tvCount=(TextView)v.findViewById(R.id.txtCount);
tv.setText(mDescription.get(arg0).toString());
tvCount.setText(mCountList.get(arg0).toString());
return v;
}
}
You need to call notifyDataSetChanged on the adapter, not the ListView itself.
Related
I have a listview in one of my Activities that has a delete button inside of each row. When I click the delete button I want to remove that row value from two different arrays. The first array is the list array that shows the information in the listview and the second is for my sharedPreference array which is the data populating the listview. This works fine the first time I run it but if I try deleting more than one row without recreating the view it won't work.
Here is my code:
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this will delete the row from the list view
list.remove(position);
//this deletes the value from the sharedPreference
favoritesList.remove(position);
notifyDataSetChange();
}
}
This works the fine the first time I click the delete button in a row but if I want to delete another row, I click the delete button on a different row and while the row is removed from the listview it isnt removed from my favoritesList array. Which means the favoritesList.remove(postion) is only working the first time. It's almost like favoritesList isn't being refreshed and its just trying to remove the same value no matter what row I click on. Which is weird because list.remove(position) works fine.
So how do I get favoritesList(position) to run more than once without breaking? I can post more code if need be but I figured this would be enough. Any help is appreciated. Thanks!
Here is the whole custom adapter for my listview:
public class ItemCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
ArrayList<String> favoritesList;
private Context context;
//private final SharedPreferences sharedPrefs;
String[] favorites;
public ItemCustomAdapter(ArrayList<String> list, Context context, String[] favorites) {
this.list = list;
this.context = context;
this.favorites = favorites;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//System.out.println(favoritesList);
favoritesList = new ArrayList<String>(Arrays.asList(favorites));
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_list_view, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
favoritesList.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
As Opiatefuchs said above, all I had to do was move favoritesList = new ArrayList(Arrays.asList(favorites)); outside of getView().
Been making my first app and slow progress is being made. Just wondering how I return a Spinner value to pass it as a string.
Here is my code:
First the event class:
public void event(){
calanderBtn = (Button)findViewById(R.id.eventBtn);
calanderBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(CalendarContract.Events.TITLE, "Home");
intent.putExtra(CalendarContract.Events.DESCRIPTION, "Cleaning : ");
intent.putExtra(CalendarContract.Events.EVENT_LOCATION, "Home");
startActivity(intent);
}
});
}
Second the Spinner Class:
public void selectcleaning() {
spCleaning = (Spinner) findViewById(spinner);
adapterCleaningType = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cleaningType);
adapterCleaningType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCleaning.setAdapter(adapterCleaningType);
}
I'm trying to select the value from selectcleaning (Value is either Yes or No) and pass it in the descrption in the Calendar of the event class and I'm not sure what to do.
you can use this code to get the value
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
or get the value when spinner selected using OnItemSelectedListener (Android Doc)
public class SpinnerActivity extends Activity implements
OnItemSelectedListener {
#Override
protected void onStart() {
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
You should try using the Overrides for the spinner class as so:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}});
For your purposes 'int position' would equal 0 (yes) or 1 (no)
Try setting an on item selected listener. When an item is selected, you can store that value in a global variable. It gets the first item by default too.
spCleaning.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Value is current spinner item
globalStringVariable = (String) parent.getItemAtPosition(position);
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
// This is default, before you've selected anything.
// It gets the first value.
globalStringVariable = parent.getItemAtPositon(0);
}
});
Can anyone help me with code, I am developing an android application and need some help. On a screen called results I need to show the headings of the records in a sqlite database in a view, the heading must be clicked and open a new window to show the full record, A long click must allow the user to delete the record.
This is what I got so far:
import java.util.ArrayList;
public class Main extends Activity {
ListView txtMainList;
// EditText nameTxt,posTxt;
Button saveBtn,retrieveBtn,btnBegin;
ArrayList<String >accidents=new ArrayList<String>();
EditText index;
ArrayAdapter<String> Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
index=(EditText)findViewById(R.id.txtRegistrationNo);
btnBegin = (Button) findViewById(R.id.btnBegin);
txtMainList = (ListView) findViewById(R.id.txtMainList);
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, accidents);
final DBHelper newDb=new DBHelper(this);
accidents.clear();
Cursor c=newDb.getYVAllData();
while (c.moveToNext())
{
accidents.add("Accident Number : "+c.getString(0));
}
txtMainList.setAdapter(Adapter);
newDb.close();
txtMainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View agr1, int index, long id) {
Toast.makeText(getApplicationContext(), accidents.get(index), Toast.LENGTH_SHORT).show();
}
});
}
If you are using listview you can use longClickListener.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
//Delete record
return true;
}
});
and add android:longClickable="true" to your listview item layout.
Onclick:
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//Show full record in pop up
}
});
I have been trying to solve this simple problem for two days now without success. I know a similar question have been asked before (like here:
How do you get the selected value of a Spinner? ), but I haven't been able to solve this yet.
So, I have created a simple app which contains a spinner and a custom ListView. The spinner (containing values 1,2,3,4,5..) creates more spinners (which contain Player names) to the ListView (eg. choosing 4 creates four spinners). Currently, the program works fine except that I don't know how to get the selected values of the spinners in ListView when clicking a button in Action Bar? I tried to use getItemAtPosition and getSelectedXXX() methods but I always tend to the get values from a single spinner I recently selected.
I am not sure do I have to invoke the methods in the Spinner's setOnItemSelectedListener(), or can I call the values from outside the SpinnerAdapter class.
Here is the custom Spinner class
public class PlayerAdapter extends ArrayAdapter<String> {
public PlayerAdapter(ArrayList<String> mPlayers) {
super(getActivity(), 0, mPlayers);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(
R.layout.list_item_players, null);
}
Spinner mSpinnerPlayer = (Spinner) convertView
.findViewById(R.id.spinner_player);
ArrayAdapter<Player> spinnerAdapterPlayer = new ArrayAdapter<Player>(getActivity(), android.R.layout.simple_spinner_item, mPlayers);
spinnerAdapterPlayer.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerPlayer.setAdapter(spinnerAdapterPlayer);
mSpinnerPlayer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
//Should I use getItemAtPosition or getSelectedXXX methods here?
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
return convertView;
}
}
}
Here is the Fragment which inflates the layout creates the first spinner (sorry about the formatting and code style)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
//gets player names from a database, such as "Player 1", "Player 2" etc..
//this is container of the spinners displayed in the listview
mPlayers = PlayerDB
.get(getActivity())
.getPlayers();
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_menu, parent, false);
listView = (ListView) view.findViewById(R.id.listView1);
mSpinnerNumOfPlayers = (Spinner) view.findViewById(R.id.spinner_numOfPlayers);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter
.createFromResource(this.getActivity(),
R.array.numberOfPlayers_array,
android.R.layout.simple_spinner_item);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerNumOfPlayers.setAdapter(spinnerAdapter);
mSpinnerNumOfPlayers.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String position = parent.getItemAtPosition(pos).toString();
mArray = new ArrayList<String>();
posInt = Integer.parseInt(position);
for (int i = 0; i < posInt; i++) {
mArray.add("" + i);
}
PlayerAdapter adapter = new PlayerAdapter(mArray);
listView.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
}
);
return view;
}
// ActionBar
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_start:
//when "start" button is clicked the spinner values are saved into an ArrayList
This method will retuns you the selected ite from the spinner..
spinner.getSelectedItem().toString()
I am struggling with trying to implement an OnLongClick feature - I can't understand where to add a listener and to define the resulting method.
The implementation i have used uses an adapter - and does not have an onClickListener, but works jsut fine. can anyone suggest where/how to implement OnLongClick listener
I don't need every item in the list to perform different actions - just for anywere on the screen to pick up the long press
public class CombChange extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ListEdit(this, symbols));
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
}
public class ListEdit extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ListEdit(Context context, String[] values) {
super(context, R.layout.activity_comb_change, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_comb_change, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
// Change icon based on name
String s = values[position];
if (s.equals("a")) {
imageView.setImageResource(R.drawable.a);
return rowView;
}
}
Try this:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
v.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
return false;
}
});
}
It is unfortunate that a ListActivity does not have a protected onListItemLongClick() method similar to the onListItemClick() function.
Instead, you can add setOnLongClickListener() to the top-level layout item (or any View) in your adapter's getView() function.
Example:
myView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do something here.
return true;
}
});
Warning, the OnLongClickListener you put onto your list item may hide exposure to the onListItemClick() function you already have working for the list. If this is the case, you will also have to add setOnClickListener() to getView() and use it instead.
in your getView you can say
rowview.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
//Do your stuff here
return false;
}
});