Select all items using a button in a custom listview - android

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

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.

How to get the Spinner value to save in a variable

I know there are several questions around this, but do not quite get how to solve it.
The problem is that I am showing some values from local SQlite database, the different options are shown ok and I can select them and the value displayed is ok. the problem is that when I try to save it, the getSelectedItem, gets the first item on the list. Any help or suggestions on how to solve it would be great.
Product product = new Product();
productsList = product.getProducts();
Spinner spinnerProduct = findViewById(R.id.spinnerProduct);
String[] arrayProduct = new String[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).nameProduct;
}
ArrayAdapter<String> adapterProduct = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayProduct);
adapterProduct.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProduct.setAdapter(adapterProduct);
spinnerProduct.setOnItemSelectedListener(onItemSelectedListener1);
String productSelected=spinnerProduct.getSelectedItem().toString();
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Product product = new Product();
productsList = product.getProducts();
int[] arrayProduct = new int[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).stockCurrent;
}
String productStock = String.valueOf(arrayProduct[position]);
product_amount_available.setText(productStock);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
A spinner uses Event listening so you cannot just do below in a linear fashion:
spinnerProduct.setOnItemSelectedListener(onItemSelectedListener1);
String productSelected=spinnerProduct.getSelectedItem().toString();
Basically what your code is doing is setting the listener, and immediately after, it's getting some arbitrary/default value from your spinnerProduct object. But you haven't even entered any input to the spinner yet. You must process all the UI and business logic in the event listener's onItemSelected() method only.
You need to implement OnItemSelectedListener and override
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
}
More info can be found here https://developer.android.com/guide/topics/ui/controls/spinner#SelectListener
Thanks for the help. I solved it. I made the global variables.
int idProduct,idStorage;
String productSelected,storageSelected;
first fill the spinners
Product product = new Product();
productsList = product.getProducts();
Storage storage = new Storage();
storageList = storage.getStorage();
Spinner spinnerProduct = findViewById(R.id.spinnerProduct);
spinnerProduct.setOnItemSelectedListener(this);
Spinner spinnerStorage = findViewById(R.id.spinnerStorage);
spinnerStorage.setOnItemSelectedListener(this);
String[] arrayProduct = new String[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).nameProduct;
}
ArrayAdapter<String> adapterProduct = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayProduct);
adapterProduct.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProduct.setAdapter(adapterProduct);
spinnerProduct.setOnItemSelectedListener(this);
String[] arrayStorage = new String[storageList.size()];
for(int i = 0; i < storageList.size(); i++) {
arrayStorage[i] = storageList.get(i).nameStorage;
}
ArrayAdapter<String> adapterStorage = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayStorage);
adapterStorage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStorage.setAdapter(adapterStorage);
spinnerProduct.setOnItemSelectedListener(this);
then, as suggested implemented the onclicklisteners
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
if(adapterView.getId() == R.id.spinnerProduct)
{
idProduct=(int) adapterView.getSelectedItemId();
productSelected=adapterView.getSelectedItem().toString();
Product product = new Product();
productsList = product.getProducts();
int[] arrayProduct = new int[productsList.size()];
for(int i = 0; i < productsList.size(); i++) {
arrayProduct[i] = productsList.get(i).stockCurrent;
}
String productStock = String.valueOf(arrayProduct[pos]);
product_amount_available.setText(productStock);
}
else if(adapterView.getId() == R.id.spinnerStorage)
{
storageSelected=adapterView.getSelectedItem().toString();
idStorage=(int) adapterView.getSelectedItemId();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
and at last I passed the values into the method triggered by a button
btnSaveTransferProduct.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
saveTransferProduct(idProduct,productSelected, idStorage, storageSelected);
}
}
});

How do I pull the selected items from a simple_list_item_multiple_choice with checkboxes?

I am trying to pull the items selected in a multiple checkbox ListView but getcheckitempositions() keeps returning null.
Relevant code:
Checkbox binding:
final ListView list = (ListView) whoView.findViewById(R.id.listView);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter(this.getActivity(), android.R.layout.simple_list_item_multiple_choice, friendList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView checkedTextView = ((CheckedTextView) view);
checkedTextView.setChecked(!checkedTextView.isChecked());
}
});
Trying to pull the items:
ListView list = (ListView) whoView.findViewById(R.id.listView);
List<String> invited = new ArrayList<String>();
SparseBooleanArray checked;
if (list != null) {
checked = list.getCheckedItemPositions(); {
for (int i = 0; i <= checked.size(); i++) {
if (checked.valueAt(i)) {
invited.add(list.getAdapter().getItem(i).toString());
}
}
}
}
I suspect it has to do with the getcheckitempositions() pulling from the ListView and not the checkboxes, but I'm not sure how I would go about fixing this.

Android ListView Removing Item on click

I am trying to remove an item from the list when I click on the selected item but I get an error on logcat saying that the removeViewAt method is not supported on AddapterView. Any idea of what I could use here in order to achieve this ?
Many thanks.
Here is my code.
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
listView.removeViewAt(position);
listView.invalidateViews();
}
});
}
Try this:
ArrayList<String> arrlist=new ArrayList<String>();
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
arrlist.add("D");
ListView listView = (ListView) findViewById(R.id.mylist);
String[] items = { "Milk", "Butter", "Yogurt", "Toothpaste", "Ice Cream" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
items.remove(position);
adapter.notifyDataSetChanged();
}
});
}
This fades away the clicked item using Animation, Requires API level 16
private List<String> myList;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listerX);
myList = new ArrayList<String>();
File directory = Environment.getExternalStorageDirectory();
file = new File( directory + "/myAppCache/" );
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
#Override
public void run()
{
Toast.makeText(getApplicationContext(), ""+item,
Toast.LENGTH_LONG).show();
}
});
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listView.setAdapter(adapter); //Set all the file in the list.
}
you are populate list with any array or collection item
Then remove item at position of clicked position.
And now notify adapter by calling adapter.notifydatasetchange();
Enjoy your code

Using Checkbox array in 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();
}

Categories

Resources