How to bind data from a database to an Android CheckBox in a ListView?

AndroidApps/ApplicationsMobile Development

This example demonstrates how to bind data from a database to an Android CheckBox in a ListView.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <ListView
      android:id="@+id/listView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>

Step 3 − Add the following code to res/layout/row_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:padding="10dp"
   android:layout_width="match_parent"
   android:layout_height="wrap_content">
   <TextView
      android:id="@+id/txtName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_centerVertical="true"
      android:textSize="16sp" />
   <CheckBox
      android:id="@+id/checkBox"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentTop="true" />
</RelativeLayout>

Step 4 − Add the following code to src/MainActivity.java

package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   ArrayList dataModels;
   ListView listView;
   private CustomAdapter adapter;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      listView = (ListView) findViewById(R.id.listView);
      dataModels = new ArrayList();
      dataModels.add(new DataModel("Apple Pie", false));
      dataModels.add(new DataModel("Banana Bread", false));
      dataModels.add(new DataModel("Cupcake", false));
      dataModels.add(new DataModel("Donut", true));
      dataModels.add(new DataModel("Eclair", true));
      dataModels.add(new DataModel("Froyo", true));
      dataModels.add(new DataModel("Gingerbread", true));
      dataModels.add(new DataModel("Honeycomb", false));
      dataModels.add(new DataModel("Ice Cream Sandwich", false));
      dataModels.add(new DataModel("Jelly Bean", false));
      dataModels.add(new DataModel("Kitkat", false));
      dataModels.add(new DataModel("Lollipop", false));
      dataModels.add(new DataModel("Marshmallow", false));
      dataModels.add(new DataModel("Nougat", false));
      adapter = new CustomAdapter(dataModels, getApplicationContext());
      listView.setAdapter(adapter);
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView parent, View view, int position, long id) {
            DataModel dataModel= (DataModel) dataModels.get(position);
            dataModel.checked = !dataModel.checked;
            adapter.notifyDataSetChanged();
         }
      });
   }
}

Step 5 − Add the following code to src/DataModel.java

package com.app.sample;
public class DataModel {
   public String name;
   boolean checked;
   DataModel(String name, boolean checked) {
      this.name = name;
      this.checked = checked;
   }
}

Step 6 − Add the following code to src/CustomAdapter.java

package com.app.sample;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter{
   private ArrayList dataSet;
   Context mContext;
   // View lookup cache
   private static class ViewHolder {
      TextView txtName;
      CheckBox checkBox;
   }
   public CustomAdapter(ArrayList data, Context context) {
      super(context, R.layout.row_item, data);
      this.dataSet = data;
      this.mContext = context;
   }
   @Override
   public int getCount() {
      return dataSet.size();
   }
   @Override
   public DataModel getItem(int position) {
      return (DataModel) dataSet.get(position);
   }
   @Override
   public View getView(int position, View convertView, @NonNull ViewGroup parent){
      ViewHolder viewHolder;
      final View result;
      if (convertView == null) {
         viewHolder = new ViewHolder();
         convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, parent, false);
         viewHolder.txtName = (TextView) convertView.findViewById(R.id.txtName);
         viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
         result=convertView;
         convertView.setTag(viewHolder);
      } else {
         viewHolder = (ViewHolder) convertView.getTag();
         result=convertView;
      }
      DataModel item = getItem(position);
      viewHolder.txtName.setText(item.name);
      viewHolder.checkBox.setChecked(item.checked);
      return result;
   }
}

Step 7 − Add the following code to Manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

raja
Published on 26-Nov-2019 09:54:13
Advertisements