logo
down
shadow

Getting value from the listview with custom adpter of selected checkbox to the activity


Getting value from the listview with custom adpter of selected checkbox to the activity

By : user2956456
Date : November 22 2020, 10:56 AM
I wish did fix the issue. Try to add one more boolean field in adapter item modle class CandidateModel :
code :
public class CandidateModel {

    private boolean isSelected;

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }
}
holder.contactCheckBox.setChecked(cm.isSelected());
holder.contactCheckBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       cm.setSelected(isChecked);         
    }
});
public ArrayList<CandidateModel> getCheckAllItem(){
    ArrayList<CandidateModel> candidateModelArrayList = new ArrayList<CandidateModel>();
    for(CandidateModel model :candidateList){
        if(model.isSelected()){
           candidateModelArrayList.add(model);
        }
    }
    return candidateModelArrayList
}
public boolean isItemChecked (int index){
   return candidateList.get(index).isSelected();
}


Share : facebook icon twitter icon
How to get selected list items from a Listview with checkBox and Custom Adapter?

How to get selected list items from a Listview with checkBox and Custom Adapter?


By : Brian How
Date : March 29 2020, 07:55 AM
wish helps you I have a ListView with CheckBox on it. and i am using Custom Adapter to populate the ListView. , Below Snippet does exactly what you want.
code :
package com.windrealm.android;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PlanetsActivity extends Activity
{

    private ListView mainListView;
    private Planet[] planets;
    private ArrayAdapter<Planet> listAdapter;
    private Button check;
    private Context context;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = PlanetsActivity.this;
        check = (Button) findViewById(R.id.check);
        // Find the ListView resource.
        mainListView = (ListView) findViewById(R.id.mainListView);

        // When item is tapped, toggle checked properties of CheckBox and
        // Planet.
        mainListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View item,
                            int position, long id)
                    {
                        Planet planet = listAdapter.getItem(position);
                        planet.toggleChecked();
                        PlanetViewHolder viewHolder = (PlanetViewHolder) item
                                .getTag();
                        viewHolder.getCheckBox().setChecked(planet.isChecked());
                    }
                });

        // Create and populate planets.
        planets = (Planet[]) getLastNonConfigurationInstance();
        if (planets == null)
        {
            planets = new Planet[]
            { new Planet("Mercury"), new Planet("Venus"), new Planet("Earth"),
                    new Planet("Mars"), new Planet("Jupiter"),
                    new Planet("Saturn"), new Planet("Uranus"),
                    new Planet("Neptune"), new Planet("Ceres"),
                    new Planet("Pluto"), new Planet("Haumea"),
                    new Planet("Makemake"), new Planet("Eris") };
        }
        ArrayList<Planet> planetList = new ArrayList<Planet>();
        planetList.addAll(Arrays.asList(planets));

        // Set our custom array adapter as the ListView's adapter.
        listAdapter = new PlanetArrayAdapter(this, planetList);
        mainListView.setAdapter(listAdapter);

        check.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View view)
            {
                for (int i = 0; i < listAdapter.getCount(); i++)
                {
                    Planet planet = listAdapter.getItem(i);
                    if (planet.isChecked())
                    {
                        Toast.makeText(context,
                                planet.getName() + " is Checked!!",
                                Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
    }

    /** Holds planet data. */
    private static class Planet
    {
        private String name = "";
        private boolean checked = false;

        public Planet()
        {
        }

        public Planet(String name)
        {
            this.name = name;
        }

        public Planet(String name, boolean checked)
        {
            this.name = name;
            this.checked = checked;
        }

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public boolean isChecked()
        {
            return checked;
        }

        public void setChecked(boolean checked)
        {
            this.checked = checked;
        }

        public String toString()
        {
            return name;
        }

        public void toggleChecked()
        {
            checked = !checked;
        }
    }

    /** Holds child views for one row. */
    private static class PlanetViewHolder
    {
        private CheckBox checkBox;
        private TextView textView;

        public PlanetViewHolder()
        {
        }

        public PlanetViewHolder(TextView textView, CheckBox checkBox)
        {
            this.checkBox = checkBox;
            this.textView = textView;
        }

        public CheckBox getCheckBox()
        {
            return checkBox;
        }

        public void setCheckBox(CheckBox checkBox)
        {
            this.checkBox = checkBox;
        }

        public TextView getTextView()
        {
            return textView;
        }

        public void setTextView(TextView textView)
        {
            this.textView = textView;
        }
    }

    /** Custom adapter for displaying an array of Planet objects. */
    private static class PlanetArrayAdapter extends ArrayAdapter<Planet>
    {

        private LayoutInflater inflater;

        public PlanetArrayAdapter(Context context, List<Planet> planetList)
        {
            super(context, R.layout.simplerow, R.id.rowTextView, planetList);
            // Cache the LayoutInflate to avoid asking for a new one each time.
            inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            // Planet to display
            Planet planet = (Planet) this.getItem(position);

            // The child views in each row.
            CheckBox checkBox;
            TextView textView;

            // Create a new row view
            if (convertView == null)
            {
                convertView = inflater.inflate(R.layout.simplerow, null);

                // Find the child views.
                textView = (TextView) convertView
                        .findViewById(R.id.rowTextView);
                checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);

                // Optimization: Tag the row with it's child views, so we don't
                // have to
                // call findViewById() later when we reuse the row.
                convertView.setTag(new PlanetViewHolder(textView, checkBox));

                // If CheckBox is toggled, update the planet it is tagged with.
                checkBox.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        CheckBox cb = (CheckBox) v;
                        Planet planet = (Planet) cb.getTag();
                        planet.setChecked(cb.isChecked());
                    }
                });
            }
            // Reuse existing row view
            else
            {
                // Because we use a ViewHolder, we avoid having to call
                // findViewById().
                PlanetViewHolder viewHolder = (PlanetViewHolder) convertView
                        .getTag();
                checkBox = viewHolder.getCheckBox();
                textView = viewHolder.getTextView();
            }

            // Tag the CheckBox with the Planet it is displaying, so that we can
            // access the planet in onClick() when the CheckBox is toggled.
            checkBox.setTag(planet);

            // Display planet data
            checkBox.setChecked(planet.isChecked());
            textView.setText(planet.getName());

            return convertView;
        }

    }

    public Object onRetainNonConfigurationInstance()
    {
        return planets;
    }
}
how to send string array from custom adpter to main activity

how to send string array from custom adpter to main activity


By : Vijit Vashishtha
Date : March 29 2020, 07:55 AM
this one helps. Create function in your custom adapter for getting data you need. You need to have reference of the adapter in your main activity class.
how to select all checkbox in custom listview from activity in android

how to select all checkbox in custom listview from activity in android


By : Ravens1996
Date : March 29 2020, 07:55 AM
I hope this helps . I have a custom listview which content two textview and one checkbox. When checkbox is checked then id is stored in the database and if unchecked then id is removed from database. But I want to select all checkboxes and store all ids into database or uncheck all checkboxes and remove all ids from database. What exactly i have to implement for this. please help me this is my adapter code , use an ArrayList to store your Items Ids
code :
ArrayList<Integer> tcontact = new ArrayList<Integer>();
 if(isChecked)
    {
         tcontact.add(Integer.parseInt(list.get(position).getContacts()))
        sqhandle.changeCheck("1", f_id);
        Toast.makeText(context, "Selected Contacts: "+total_contacts, Toast.LENGTH_LONG).show();

    }
    else
    {
      for(int i=0;i<tcontact.size;i++) {
      if(tcontact.get(i) == Integer.parseInt(list.get(position).getContacts())) {
      tcontact.remove(i);
      sqhandle.changeCheck("0", f_id);

        Toast.makeText(context, "Selected Contacts: "+total_contacts, Toast.LENGTH_LONG).show();
}
}}
custom listview with only one checkbox is selected one at a time

custom listview with only one checkbox is selected one at a time


By : user2785880
Date : March 29 2020, 07:55 AM
Hope this helps Try to change all item boolean value false exclude selected item after notify adapter and also implement ViewHolder design pattern for ListView performance :
code :
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.list,null);
            holder.txt1 = (TextView) convertView.findViewById(R.id.textView1);
            holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txt1.setText(items.get(position));
        holder.chkbox.setChecked(array[position]);
        holder.chkbox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                for (int i=0;i<array.length;i++){
                    if(i==position){
                        array[i]=true;
                    }else{
                        array[i]=false;
                    }
                }
                notifyDataSetChanged();
            }
        });

        return convertView;
    }

    class ViewHolder{
        TextView txt1;
        CheckBox chkbox;
    }
how to check and uncheck all checkbox in custom listview from activity?

how to check and uncheck all checkbox in custom listview from activity?


By : Afandi A
Date : March 29 2020, 07:55 AM
To fix the issue you can do You need to update the information in your custom CursorAdapter because Listview only build enough "list view" for show and recycle reuse and dynamic change those views for efficiency.
Under your custom Adapter, add global variance and update it.
code :
boolean allcheck = false; //Default unchecked   
public void bindView(View view, Context context, Cursor cursor) {
CheckBox box = (CheckBox) view.findViewById(R.id.checkBox);

      box.setChecked(allcheck);

    }
Related Posts Related Posts :
  • Passing variables from one activity to another
  • Create Multicolored Pie Chart in Android Studio
  • how to kill progress dialog in android
  • Show Error on the tip of the Edit Text Android
  • How do I use getWindowManager() by another java file
  • fetching images from gallery on android phones with internal storage
  • How to discover devices like Google TV and Nexus-Q using MediaRoute API on Android?
  • "Unfortunately your app stopped working"- Facebook Integration for Android
  • How to animate button in android?
  • Resource Not Found Exception in class without context or activity
  • Launching Android Netflix App And Passing Video Id
  • Making a Phone Call with a Number Extension
  • NullPointerException at BoringLayout.isBoring is anything but boring
  • java.lang.RuntimeException: Unable to get provider
  • Testing custom Views with Robolectric
  • tools:listheader doesn't work although tools:listitem does
  • oppo, vivo app kill notification not coming in android fcm
  • OnClick Method could not function correctly with if else statement
  • Best method to download image from url in Android
  • How can I open Drawer Layout moving all the view and not just slide over?
  • how to show profile pictures of friends in a list view?
  • Creating TimePickerDialog with custom style in Android
  • Android 2.3.6 support library v7 option menu is missing
  • need of vblank in Display subssytem
  • Android MP4 stream - Video cannot be played
  • FastAdapter: Undo button does not show up after swipe
  • What are reasons to pass getActivity as the LifecycleOwner to the LiveData's observe method in a fragment?
  • Implement Face Recognition in Android
  • Titanium studio cannot run "titanium" command in terminal
  • How to execute command line ffmpeg commands programatically in android?
  • Make Android List Items clickable with each item pointing to a different link
  • listview runs successfully, but nothing is display in emulator
  • How to zoom in a bitmap with high resolution?
  • Passing listView data through intent
  • Google map route direction show by arrows in android v2
  • how to start "uiautomator test run" from android code?
  • Proguard in Android Library
  • Alarm Clock from GIT - Gives error - Android
  • Mock injection using Mockito - Android
  • Get Bitmap from universal image loader
  • Unable to include custom font in android
  • Basics on using logcat in Android development
  • Android: Clear cache programmatically
  • Android: pass object without serialization
  • Can not scroll and click item on gridview inside scrollview
  • Android device keeps disconnecting from adb / eclipse
  • Volley cannot create cache directory. Could not clean up file
  • ShareActionProvider icon in actionbar
  • How to open a custom attachment using an Android app?
  • Unable to add column dynamically into the sqlite table
  • android persistence activity which never stop
  • The Google Play services resources were not found. Check your project configuration to ensure that the resources are inc
  • How to select files from google drive in android?
  • Run a AsyncTask every 10 seconds until cancelled
  • Blur on touch. Android application
  • NDK Android - Can't build ARMv5 and V7 at the same time
  • Android development with Eclipse clean and build
  • How to set Different Key Background for every Key in Android Custom Keyboard
  • Face recognition using OpenCV in android?
  • Tumblr API - Jumblr for Android [OAuthConnectionException]
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org