Using Checkbox array in android - android

I am trying to make a listview with checkbox using listview's built in checkbox method. I have gone through a stackoverflow post and i found it is running properly except one problem.
If there are four items in list and assume, i checked the second and third item, onclicking, it is displaying the second and third item as needed..but if i am selecting first and then third and then second item, and then i m unchecking the first, so i must be left with second and third as desired output. But it is providing first second and third item as output.
can anybody guide me on that..?
This is the java code:
public class TailoredtwoActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btn1;
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tailoredtwo);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.listViewcity);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.btn_tailortwo_submit);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Toast.makeText(getApplicationContext(), array[positions.keyAt(index)].toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}

Change your onClick to
Delcare the below as a class variable
StringBuilder builder;
Then
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
builder = new StringBuilder();
for(int index = 0; index <array.length; index++) {
if(positions.get(index)==true)
{
builder.append(array[index]);
builder.append("\n");
}
}
Toast.makeText(getApplicationContext(),builder, Toast.LENGTH_LONG).show();
}

Related

Can't get the position of item of dynamically created spinner

Basically i have a method createList() which creates a Spinner and then i add those spinners to an arrayList myList. After adding them i use setOnItemSelectedListener on each Spinner in the array List to get the position but no matter what i select in a spinner i get the position 0. Interestingly, if i don't add spinners to ArrayList and use only one spinner i get the position easily. The problem arises when i put spinner objects in an arrayList.
Here is the code:
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
Spinner spinner1;
int pos;
ArrayList<Spinner> myList = new ArrayList<>();
int length = 0;
int[] numbers;
int show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.root);
}
public void showPosition(View view) {
numbers = new int[length];
for (int i = 0; i < length; i++) {
myList.get(i).setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
numbers[i] = adapterView.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
public void createList(View view) {
length++;
ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this, R.array.city, android.R.layout.simple_spinner_item);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1 = new Spinner(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(500, 50);
spinner1.setLayoutParams(params);
spinner1.setAdapter(arrayAdapter);
myList.add(spinner1);
linearLayout.addView(spinner1);
}
}
When i print number in the log all the elements of this array are zero no matter what item i have selected in the spinner.
Please help stuck on it for few days :(
Found the answer:
Directly get the position by mySpinner.get(i).getSelectedItemPosition() and use that position with a switch statement to make it workable.

select mutiple contact list by searchview and send to another activity

OK I have a multiple choice ListView that works fine. I check the boxes for the contacts (held in a String[]) and can return the values fine. Because some people have a bunch of contacts I wanted to create a search bar kind of like the stock one for the Android phone book. I created an EditText and aligned it above my list. I found the filtering code here on StackOverflow and it works wonderfully.
My Problem:
When you filter someones name out, and you select the name, when you either backspace from the EditText or continue typing, the correct position of the name you selected is not saved. For example, if I start typing "Adam" and get to "Ada" and select it, if I backspace to type in "Carol", whatever position "Ada" was at is selected. It gathers the place that "Adam" was at from the click (Let's say 2) and when the list is restored checks that position (2) even though Adam is not there anymore. I need a way to gather the name.. then when the list is restored or searched again, the NAME Adam is checked and not the POSITION Adam was previously at. I have absolutely no ideas other than creating tons of Arrays and could really use some help.
public class MainActivity extends Activity {
private static final String[] items={"lorem1", "ipsum1", "dolor1",
"sit1", "amet1","lorem2", "ipsum2", "dolor2",
"sit2", "amet2","lorem3", "ipsum3", "dolor3",
"sit3", "amet3","lorem4", "ipsum4", "dolor4",
"sit4", "amet4","lorem5", "ipsum5", "dolor5",
"sit5", "amet5","lorem6", "ipsum6", "dolor6",
"sit6", "amet6","pigeon","victory"};
ListView list;
Button save;
EditText inputSearch;
SearchView searchview;
ArrayAdapter<String> adapter;
int textlength=0;
// private String my_sel_items;
ArrayList<String> selectedItems1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, items));
list = (ListView) findViewById(R.id.list);
list.setEmptyView(findViewById(R.id.empty));
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
inputSearch = (EditText) findViewById(R.id.inputSearch);
save = (Button) findViewById(R.id.save);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
textlength = inputSearch.getText().length();
selectedItems1.clear();
for (int i = 0; i < items.length; i++) {
if (textlength <= items[i].length()) {
if (inputSearch.getText().toString().equalsIgnoreCase(
(String)
items[i].subSequence(0,
textlength))) {
selectedItems1.add(items[i]);
}
}
}
list.setAdapter(new ArrayAdapter<String>
(MainActivity.this,
android.R.layout.simple_list_item_multiple_choice, selectedItems1));
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = list.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
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);
}
if (selectedItems.size() < 1) {
Toast.makeText(getApplicationContext(), "Select atleast one ", Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
intent.putExtras(b);
startActivity(intent);
}
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
}
});
}
}
Perhaps you can use unique ID's.
In every list item you can have an invisible TextView that will store the ID.
On click assign to some variable the ID and you can use it later.
Hope that helps.
Lets say your list items XML are as so:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Contact name -->
<TextView
android:id="#+id/contactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!-- Contact Unique ID -->
<TextView
android:id="#+id/contactID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>
In your activity class add the following variables:
static int uid;
int selectedId;
Then before initializing the list add:
uid = 0;
In the adapter or whatever way you add views to list do:
TextView id = (TextView)yourListItem.findViewById(R.id.contactID);
id.setText(String.valueOf(uid));
uid++;
And finally in the onClickListener of the list item add:
TextView id = (TextView)yourListItem.findViewById(R.id.contactID);
selectedId = Integer.parseInt(id.getText().toString());
That way you can fetch the selected list item later - by comparing the selected id.

listView item click event not firing

I am having an issue with using a listview that when I click it nothing is happening. I would like for it when I click the listview item to make a toast so I know it is being clicked. I have been trying/researching for a while and nothing. Would anybody mind taking a look to see if I am missing something I just am overlooking? Many thanks in advance!
Here is my class:
public class MyCar extends Activity {
/**
* Called when the activity is first created.
*/
public ListView mylistView;
String carInfo;
private ArrayAdapter<String> mylistAdapter;
ArrayList<String> arrayListCar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycar);
mylistView = (ListView) findViewById(R.id.listView);
arrayListCar = new ArrayList<String>();
//Just had to remove setting this adapter 2 times. Took out line below to fix.
mylistView.setAdapter(mylistAdapter);
mylistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
carInfo = trySomethin();
fillList();
}
public void fillList() {
String make = "";
String model = "";
String[] pieces = carInfo.split("\"");
make = pieces[3];
model = pieces[7];
ArrayList<String> carList = new ArrayList<String>();
carList.add(make + " " + model);
// Create ArrayAdapter using the car list.
mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList);
mylistView.setAdapter(mylistAdapter);
mylistAdapter.notifyDataSetChanged();
}
}
if you have any elements on listview item change this for them
android:focusable="false"
and if you are changing any elements visibility on runtime you have to handle focus programatically each time you change its visibility.
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});

Select all items using a button in a custom listview

I would like to select and deselect all the items in the listview using "SelectAll" and "DeselectAll" buttons. I wrote the code for SelectAll but it throws a NullPointException. I couldn't find the bug in my code. Can someone point out the error in my code.
final ListView list;
String[] listItems = { "Enabled" };
list = (ListView)findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.facilities)));
list.setItemsCanFocus(false);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
CheckedTextView ctv = (CheckedTextView)arg1;
//other functionality!
}
});
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View view) {
int itemCount = getListView().getCount();
System.out.print(itemCount);
for (int i = 0; i < itemCount; i++){
list.setItemChecked(i, true);
//getListView().setItemChecked(i, chk.isChecked());
}
}
};
Button button = (Button) findViewById(R.id.selectAll);
button.setOnClickListener(clickListener);
try to use below code...
private OnClickListener checkAllCheckboxes = new OnClickListener()
{
public void onClick(View v)
{
ListView lv = getListView();
int size = getListAdapter().getCount();
if(lv.isItemChecked(0))
{
for(int i = 0; i<=size; i++)
{
lv.setItemChecked(i, false);
}
}
}
}
};
You Can create One ArrayList of data class
class data
{
boolean chekced=false
create setter and getter of this
}
Create ArrayList of Data Class intially Chekced is false in all arraylist items
When select is called set all items to true
Then moify adpater and call notifyDatasetChanged on listView
This is how you can do this

Retrieving the selected items from a multi-select ListView

I am currently implementing a multi-select ListView for my android app. My aim is to retrieve the selected items from the ArrayAdapter associated with the ListView when clicking the search button.
I am currently stumped on how to do this, I have found stuff online such as trying to set a MultiChoiceModeListener, but this does not seem to come up as an option in Eclipse. I am using Google APIs(level 10), Android 2.3.3 equivalent. Here is the code I have so far:
public class FindPlace extends Activity {
public FindPlace() {}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_places);
Button search = (Button) findViewById(R.id.search);
String[] categories = getResources().getStringArray(R.array.Categories);
ArrayAdapter ad = new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,categories);
final ListView list=(ListView)findViewById(R.id.List);
list.setAdapter(ad);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { }
});
}
}
Slightly more efficiently / correctly:
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < checked.size(); ++i)
{
if (checked.valueAt(i))
{
int pos = checked.keyAt(i);
doSomethingWith(adapter.getItem(pos));
}
}
Use the method getCheckedItemPosition().
take the count of the selected item in the int and make for loop like below.
int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < len; i++){
if (checked.get(i)) {
String item = cont_list.get(i);
/* do whatever you want with the checked item */
}
}

Categories

Resources