How to clear elements from SimpleAdapter? - android

I am trying to fill the listview on a SET button.As i select the values spinner and according to list will fill. Problem i am facing is at many times i click on SET button it will add items to listview .
setButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
for (int i = 0; i < DeviceID.size(); i++)
{
//initialize row data
for (int j = 0; j < 5; j++) {
if (j == 0)
str = DATE.get(i);
else if (j == 1)
str = TIME.get(i);
else if (j == 2)
str = DeviceID.get(i);
else if (j == 3)
str = SMSTEXT.get(i);
map.put(columnTags[j], str);
}
mylistData.add(map);
}
final String[] columnTags = new String[]{"one", "two", "three", "four", "five", "six", "lat", "log"};
final int[] columnIds = new int[]{R.id.textView5, R.id.textView8, R.id.textView9,R.id.checkbox, R.id.textView10};
arrayAdapter = new SimpleAdapter(this, mylistData, R.layout.location_locator_textview, columnTags, columnIds);
listview.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
});

It looks like your list mylistData is a global variable. So, the old items are still in the list.
Either make it local inside the onClick method, or clear it in the first line of the onClick method. (Also the same case for map)
public void onClick(View view){
mylistData.clear();
map.clear();
//your code
}

You can call listview.setAdapter(null); before you set your items into listview

Try to modify the list of an element in your adapter and then call notifyDataSetChanged().
It would be easier if you post the code

Related

Update checkbox in CheckedTextView which is inside a ListView

I am a noob android studio and this is my first app I am developing.
Context: I have a ListView lv which is populated with CheckedTextViews using a ListAdapter.
ListAdapter adapter = new SimpleAdapter(
c, manageTrackers.trackers,
R.layout.list_item, new String[]{"id", "mobile", "status"},
new int[]{R.id.trackerID, R.id.trackerMobile, R.id.trackerStatus});
lv.setAdapter(adapter);
I have set up the OnItemClickListener for lv as shown below which checks and unchecks the check boxes as expected. I want the checks to remain persistent when I navigate between activities, so I am storing a key in the selectedTrackers array list.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.trackerID);
HashMap s = (HashMap)lv.getItemAtPosition(i);
String mob = (String)s.get("mobile");
//checked and pressed
if (ctv.isChecked())
{
ctv.setChecked(false);
for (int j = 0; j < selectedTrackers.size(); j++)
{
if (selectedTrackers.get(j) == mob)
{
selectedTrackers.remove(j);
break;
}
}
}
//not checked
else
{
ctv.setChecked(true);
selectedTrackers.add(mob);
}
}
});
When I navigate back to the activity with the list view, I call a function getSelectedTrackers which I want to select the saved checkboxes based on the key in selectedTrackers
public static void getSelectedTrackers()
{
if (basicSettings.selectedTrackers.size() == 0) return;
for (int i = 0; i < trackers.size(); i++)
{
HashMap s = trackers.get(i);
String mob = (String)s.get("mobile");
for (int j = 0; j < basicSettings.selectedTrackers.size(); j++)
{
if (basicSettings.selectedTrackers.get(j).equals(mob))
{
View v = getViewByPosition(i, lv);
CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.trackerID);
ctv.setChecked(true);
//******************************
//some call to update the view HERE
//******************************
break;
}
}
}
}
Question: I have confirmed that the function finds the correct checkbox, but none of the check boxes are displayed as being selected after calling setChecked(). I have scoured SO and tried invalidating, refreshing drawable state, notifyDataSetChanged, and I can't seem to figure it out how to get it to work. What's the best way to do this? Any help is appreciated!

Converting ArrayList to HashSet

I am having a difficulty upon converting arraylist to hashSet. I dont have knowledge about HashSet that why I use ArrayList. I've read some about it but understand none. I am here trying to get some help about my problem.
All I wanted is to NOT DUPLICATE the words entered in my app's ListView. Here's my code. Please bear with it. I've seen some questions too here but it got me a lot more confused. Please be nice.
P.S. My first try :)
ArrayAdapter<String> adapter;
//onCreate
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
wordList.setAdapter(adapter);
//SEARCH
public void viewWord(View view) {
s1 = search.getText().toString();
s2 = dbHelper.getData(s1);
if (optionTxtView == 0) {
tv2.setText(s2);
optionTxtView = 1;
} else {
if (optionTxtView == 1) {
tv3.setText(s2);
optionTxtView = 1;
}
}
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
ListView works by returning data based on position. Sets do not have a notion of position; you have to iterate over the Set to find the element you want.
On the other hand, Lists do have a notion of position, this is why they play nicely with ListView and the BaseAdapter class.
Adding ArrayList elements to a HashSet (Note: use LinkedHashSet if the order of elements matters):
ArrayList<String> list = new ArrayList<String>();
HashSet<String> set = new HashSet<String>();
list.add("Hello");
list.add("Hello");
list.add("World!");
System.out.println(list); // [Hello, Hello, World!]
set.addAll(list);
System.out.println(set); // [Hello, World!]
Using your code, maybe you could try something like:
ArrayAdapter<String> adapter;
//onCreate
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
HashSet<String> noDupesSet = new HashSet<String>();
noDupesSet.addAll(wordlist);
wordlist.clear();
wordlist.addAll(noDupesSet);
wordList.setAdapter(adapter);
//SEARCH
public void viewWord(View view) {
s1 = search.getText().toString();
s2 = dbHelper.getData(s1);
if (optionTxtView == 0) {
tv2.setText(s2);
optionTxtView = 1;
} else {
if (optionTxtView == 1) {
tv3.setText(s2);
optionTxtView = 1;
}
}
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();

ListView Pagination with NEXT and PREVIOUS buttons

I have a listview which loads 200 items using webservice. Where all 200 items are displaying in single listview.
I want to load first 1-20 items first and when i click NEXT button i need to load 21-40 items and so on. And vice-verse, when i click PREVIOUS button i need to load 1-20 items.
How to implement Pagination for this?
I tried :
static ArrayList<String> Code = new ArrayList<String>();
//Code is ArrayList where i get 200 items from Service
int rowSize = 20;
// rowSize is number of items i want per page
static ArrayList<String> TempCode = new ArrayList<String>();
//TempCode is temporary ArrayList where iam trying to store items per page
Button NextButton;
NextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int size = Code.size() / rowSize;
for (int j = 0; j < size; j++) {
final int k;
k = j;
addItem(k);
}
}
});
public void addItem(int count) {
TempCode.clear();
count = count * rowSize;
/**
* fill temp array list to set on page change
*/
for (int j = 0; j < rowSize; j++) {
TempCode.add(j, Code.get(count));
count = count + 1;
}
Adapter adapter=new Adapter(getApplicationContext(),TempCode);
listView.setAdapter(adapter);
}
Please help.
Thanks in advance.
int _currentPage = 1;
public int FeedCountPerPage = 20;
//Call the below code in one function on click of your next button
//And do the reverse on click of previous button
_currentPage += 1;
try {
int _feedCount = _currentPage * FeedCountPerPage;
if (_feedCount <= arrPhotoData.size()) {
tmpList = arrPhotoData.subList(_feedCount - FeedCountPerPage, _feedCount);
adderList.addAll(arrPhotoData.subList(0, FeedCountPerPage));
adderList.addAll(tmpList);
}
} catch (Exception e) {
e.printStackTrace();
}
if (adderList == null || adderList.size() == 0)
adapter = new InstagramListAdapter(_myActivity, arrPhotoData);
else
adapter = new InstagramListAdapter(_myActivity, adderList);
I have posted this answer as a context of my project. I hope you'll have some understanding from this.

How to delete multiple selected line items from a listview?

I have implemented a simple method to delete multiple items from a listview following this solution Removing muliple items from listview using Check box in Android, then modified it a small bit to allow for a switch statement for the two button click events, add & delete.But the problem is when I click the delete button the app crashes giving me these errors: http://pastebin.com/2NmCQk2B
I'm not sure why I'm getting the null pointer exception as I believe I have assigned everything correctly.
Can someone better explain why I could be getting this error? Or perhaps a better way of deleting selected line items from a listview?
The complete class is posted below for better understanding:
public class TopRatedFragment extends Fragment implements OnClickListener {
ListView mListView;
EditText mValue;
Button mAdd,mDel;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
SparseBooleanArray mCheckStates ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
mAdd = (Button)rootView.findViewById(R.id.newList);
mDel = (Button)rootView.findViewById(R.id.delBtn);
mAdd.setOnClickListener(this);
mDel.setOnClickListener(this);
mValue = (EditText)rootView.findViewById(R.id.listData);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1, list);
// set the lv variable to your list in the xml
mListView=(ListView)rootView.findViewById(R.id.listView);
mListView.setAdapter(adapter);
return rootView;
}
public void onClick(View v)
{
switch(v.getId()){
case R.id.newList:
//DO something
String input = mValue.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}
break;
case R.id.delBtn:
//DO something
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
list.remove(i);
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
}
}
You need to use valueAt(), the working code should be
SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = mListView.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i(TAG,item + " was selected");
}
}
}
Remove from adapter instead from listview try following:
SparseBooleanArray checked = mListView.getCheckedItemPositions();
if(checked!=null){
for (int i = 0; i < mListView.getCount(); i++){
//line 65
if (checked.get(i)==true)
{
adapter.remove(mListView.getItemAtPosition(i));
}
adapter.notifyDataSetChanged();
}
mListView.clearChoices();
}
getCheckedItemPositions Returns:
A SparseBooleanArray which will return true for each call to get(int position) where position is a checked position in the list and false otherwise, or null if the choice mode is set to CHOICE_MODE_NONE.
I used loop this way, and it worked:
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();

In android am using multiple choice list for contact selection how to select all contact at one button click

Hi am using multiple choice list
can any one tell me how should i select all
item on any button click event
or how unselect all item on button click event
my code is here
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_list);
findViewsById();
PhoneContacts pc = new PhoneContacts(ContactList.this);
pc.readContacts();
for (int i = 0; i < pc.allPhoneNumbers.size(); i++) {
_allNumberAndNameMergeList.add(pc.allContactName.get(i) + "\n"
+ pc.allPhoneNumbers.get(i));
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
_allNumberAndNameMergeList);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
button.setOnClickListener(this);
}
private void findViewsById() {
listView = (ListView) findViewById(R.id.list);
button = (Button) findViewById(R.id.testbutton);
}
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
}
}
Hi am using multiple choice list
can any one tell me how should i select all
item on any button click event
or how unselect all item on button click event
I would create custom adapter that extends ArrayAdapter and ListView item that would contain e.g. CheckBox. Than inside adapter class getView() method handle selected items position to get objects on current position and you can do anything you wish. You can have a look at this tutorial - 12. Selecting multiple items in the ListView
http://www.vogella.com/articles/AndroidListView/article.html

Categories

Resources