I have to fetch the data from the database and populate it into the ListView. But everytime I am running it, it adds the data into the previous data...
for example..
1st run:-
A
B
C
2nd run:-
A
B
C
A
B
C
and so on..
Here is my code I am using where I am using NotifyDatasetChanged()
List<Tag> allTags = db.getAllTags();
for (Tag tag : allTags) {
lv1=(ListView)findViewById(R.id.lv1);
arraylist=new ArrayAdapter<Tag>(this,
android.R.layout.simple_list_item_1, allTags);
lv1.setAdapter(arraylist);
Log.d("Tag Name", tag.getTagName());
lv1.setOnItemClickListener(new OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
arraylist.notifyDataSetChanged();
}
});
}
I have searched many links, applied their answers in my code, But nothing is changed.
You are creating your adapter using allTags, so whenever you are changing the value of allTags by adding or removing more elements and then immediately calling notifyDataSetChange() it will reflect the changes in the adapter. What I can see here in your code is that inside OnItemClickListener you are not modifying your allTags hence calling notifyDataSetChanged is not effective.
Related
I have a list view and I've implemente filtering.
Lets say I have items A, B and C. If I type B in the filter box, only item B will be displayed and it is the position 0 of the list (before it was in position 1). So when I call the onClick item, I get the the id/position 0, which leads to displaying details about A instead of B.
This is the onclick code:
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Poi poi = pois.get((int)id);
goPOIDETAIL(poi);
}
});
id and position have the same value.
is there a way to get the original position, or get some other value indicating the real item that I clicked?
Thanks
flashsearchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Integer temp=flashSearchNameMap.get(adapter.getItem(position));
navigateSearch(temp);
}
});
(adapter.getItem(position) will return you the exact list name and in flashSearchNameMap i have stored names and position at beginning from oncreate before applying filtering.So you can get exact position by this
I think the problem is in the way you manage your filter. You should get the object with selected id not from the original List (or array) but from the filtered one.
I used something like it in this post from my blog. Hope this help you
ID and Index are not the same. Of course, you can return item index in getItemId() method of your adapter, but don't expect your items to be identified correctly by this method if you do.
Try providing unique ID for each of your items. The idea is somewhat similar to ID of each record in the database, which never changes (and lets you reliably identify each record), and it is easily implemented when you get your data from database.
But if your items don't have unique IDs, and you don't want to bother providing them, there's another approach (see this example code for Adapter below):
public MyAdapter extends BaseAdapter {
private List<Item> items;
private List<Item> displayedItems;
public MyAdapter(List<Item> items) {
this.items=items;
this.displayedItems=items;
}
public filter(String query) {
if(query.isEmpty()) {
displayedItems=items;
} else {
displayedItems=new ArrayList<Item>();
for (Item item : items) {
displayedItems.add(...) //add items matching your query
}
}
notifyDataSetChanged();
}
//...
//NOTE: we use displayedItems in getSize(), getView() and other callbacks
}
You can try:
#Override
public boolean hasStableIds() {
return false;
}
in your adapter
if you are using datbase you have the _id key that you can load in a filtered list as invisible field. Once you click on the item you can query data with _id key.
If you aren't using a database you could add a hidden id element in your row element as well.
I have included my ListAdapter in my EMPLOYEE class.And list1 contains the values of Empname,
Eno,Salary fetched from webservices.Now after displaying the 5 records in the employee
screen...when I click on Depatrment Activity and come back to Employee ... the initial
5 records are appended to the list and now 10 records are present and so on .... the process is going on like this...
Please help me so as no duplicates are appended and it has to refresh the list.
Note : clear() or notifydatasetchanged(), invalidate() are not working.
ListAdapter adapter = new SimpleAdapter(this, list1,
R.layout.employee, new String[] { "EmpName","Eno", "Salary" }, new int[]
{R.id.ename, R.id.eno,R.id.sal});
setListAdapter(adapter);
Listview lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
pos = position;
registerForContextMenu(getListView());
}
});
TextView tvdept = (TextView) findViewById(R.id.Department);
tvdept.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Employee.this, Department.class));
}
});
Without seeing more code, it's difficult to be sure, but I'll hazard a guess...
When you leave an activity and come back, the framework tries to restore you to where you were using the savedInstanceState bundle. It uses this to re-create where you last were in that activity. It sounds like you have set up the list in the onCreate method and haven't checked for a savedInstanceState bundle, so when you come back to the activity the framework is restoring your list and then proceeds into your code and re-creates the list (in this case adding the same data again).
Try wrapping your list creation code in an if that checks for the existence of the savedInstanceState bundle.
Like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// do your list setup here
}
}
Using that, if you come back to the activity and the framework saved your state, it will simply restore it and not run through your list creation code.
I know this doesn't answer the actual question, but it should solve the root issue (duplicating list data on return to activity).
In the tablet layout of my app, I have three ListFragments and one regular Fragment, let's call them Make, Model, Size, and Details. Initially the Make list is populated, then based on the Make selection, the Model list is populated; when a Model is selected, the Size list is populated; when a Size is selected, Details are shown. Each of these events (list item selection) is handled through the onListItemClick handler.
On startup, I want to populate the Make list, select the first Make in the list and have it go through the onListItemClick handler to populate the Model list (and so on so that all lists are populated and the details are shown - this should also be the behavior when any selection is made in any of the lists - select the first item in the next list until we get to showing the details). Note that I have control of the DB and for every Make there will always be at least one Model, for each Make/Model at least one Size, for each Make/Model/Size exactly one Detail.
So, I want to select the first item in the list and have it trigger the onListItemClick handler. I've tried the following (with appropriate bounds checking, etc), but it doesn't work.
getListView().setItemChecked(0, true);
The only changes to an "out of the box" ListFragment are to set the CacheColorHint as such
getListView().setCacheColorHint(R.color.GhostWhite);
where GhostWhite is set in the styles.xml as
<color name="GhostWhite">#88FFFFFF</color>
Any ideas?
Thanks in advance.
To select the first item in the list, first get focus from touch, then select the first item, then trigger the onclick handler
int position = 0;
getListView().requestFocusFromTouch();
getListView().setSelection(position);
getListView().performItemClick(getListView().getAdapter().getView(position, null, null), position, position);
Try setSelection(int position)
http://developer.android.com/reference/android/widget/ListView.html#setSelection(int)
1.) In the OnActivityCreated of your list fragment create an interface like so
public interface ListItemSelectedListener {
public void onListItemSelected(int index);
}
2.) Implement the interface in your activity
3.) Create private ListItemSelectedListener selectedListener in your list fragment
4.) Set selectedListener.onListItemSelected(0) in the OnActivityCreated.
This is how it worked for me using the Android Support Package - should be similar on HC
Try adding this,, it works in my project:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Intent intent = new Intent();
intent.setClass(getActivity(), someActivity.class);
startActivity(intent);
}
in The Fragment class in onActivityCreated(Bundle savedInstanceState) method, you can add the following:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//if the parent is in the landscape, make the first item selected
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
try {
if (mItems.size() > 0) {
//notify the activity that an item is selected
mListener.onMasterItemSelected(mItems.get(0));
}
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
}
i hava got the code below. i want to start an activity when i click on a single item on the list. however when i do nothing happens. I alsow want every item to refer to the same intent calld "com.whiskey.app.view" and send a id variable that was given by the sql query. I browsed trough the code several times but i cant seem t get it to work.
public class MainScreen extends Activity implements OnItemClickListener{
public ListView whiskeylist;
public String[] DataArryWhiskey;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start db view of whiskey
DBConfig whiskeyrows = new DBConfig(this);
whiskeyrows.open();
DataArryWhiskey = whiskeyrows.getDataInArray();
whiskeyrows.close();
whiskeylist = (ListView)findViewById(R.id.listofWhiskey);
whiskeylist.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , DataArryWhiskey));
// End db view of whiskey
}// end onCreate
// catch itemclick event from the main list.
public void onItemClick(AdapterView av, View v, int position, long l)
{
// TODO Auto-generated method stub
String[] listitem_data = DataArryWhiskey[position].split(","); // break passed sting into a array comma seperated
Bundle passingitems = new Bundle();
passingitems.putString("whiskey_id", listitem_data[0]);
Intent currentintent = new Intent("com.wiskey.app.view");
currentintent.putExtras(passingitems);
startActivity(currentintent);
}
Although the above answers work, I think that the problem in your current implementation is that you don't call:
whiskeylist.setOnItemClickListener(this);
I think this should do the work!
If your activity only cotains this ListView, you should use a ListActivity.
These are made specifically for activities that only contain lists.
One of the methods for ListActivities is onListItemClick. That one is specifically for clicking on items in lists, as the name says.
The reason your code doesn't work is because onItemClick isn't generally used for clicking in Lists, but for clicking other objects in Activities.
Try changing your code based on the samples here: ListActivity
Derive your class from ListActivity and remove the implements OnItemClickListener
Put below code in onCreate
setListAdapter(whiskeylist);
And then have this as your onItemClick
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String[] listitem_data = DataArryWhiskey[position].split(","); // break passed sting into a array comma seperated
...your code....
startActivity(currentintent);
}
Also refer to:
ListActivity
ListView
You have not added listener for click actions, try adding:
whiskeylist.setOnItemClickListener(this);
at the end of onCreate
You might also write anonymous OnItemClickListener as in here:
http://developer.android.com/resources/tutorials/views/hello-listview.html
What is the best way to add an OnClickListener to a ListActivity that's Endless?
I am using cwac-endless adapter for my endless list.
The problem I am encountering is only my first batch of data that populates the list get's the click listener. The new data that get's fetched doesn't get the onclick listener.
I've tried adding a onclick listener in the following manner.
I used ListActivity onListItemClick
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String url = prodList.get(position).getProdUrl();
Log.i("URL",url);
Intent webViewIntent = new Intent(ProductListActivity.this, ProductWebView.class);
webViewIntent.putExtra("URL", url);
startActivity(webViewIntent);
}
UPDATE Rookie mistake, the above code works fine, the problem was that I was referencing the original list that was passed in instead of referencing the list in my custom ArrayAdapter.