0

I'm very new to android and seeking for help about listview optimization for data fetched from the database. "I want to check the boxes and then press the get button to show them in a toast."

with SimpleCursorAdapter :

package com.example.adapterx;


import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {

DBAdapter myDb;            

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    openDB();
    display();
    insertdata();

}


private void insertdata() {

String pap = "1";
String pap1 = "2";
String pap2 = "3";
String pap3 = "4";
String pap4= "5";
String pap5 = "6";
String pap6 = "7";
String pap7 = "8";
String pap8 = "9";
String pap9 = "10";
String pap10 = "11";
String pap11 = "12";
String pap12 = "13";
String pap13= "14";
String pap14 = "15";
String pap15 = "16";
String pap16 = "17";
String pap17 = "18";
String pap18 = "19";
String pap19 = "20";
String pap20 = "21";
String pap21 = "22";
String pap22 = "23";


myDb.insertRow(pap);
myDb.insertRow(pap1);
myDb.insertRow(pap2);
myDb.insertRow(pap3);
myDb.insertRow(pap4);
myDb.insertRow(pap5);
myDb.insertRow(pap6);
myDb.insertRow(pap7);
myDb.insertRow(pap8);
myDb.insertRow(pap9);
myDb.insertRow(pap10);
myDb.insertRow(pap11);
myDb.insertRow(pap12);
myDb.insertRow(pap13);
myDb.insertRow(pap14);
myDb.insertRow(pap15);
myDb.insertRow(pap16);
myDb.insertRow(pap17);
myDb.insertRow(pap18);
myDb.insertRow(pap19);
myDb.insertRow(pap20);
myDb.insertRow(pap21);
myDb.insertRow(pap22);
Toast.makeText(this, "inserted successfully.",    Toast.LENGTH_LONG).show();

}


 @Override
protected void onDestroy() {
super.onDestroy();  
closeDB();
}
 private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}


private void display() {

    final Cursor cursor = myDb.getAllRows();
    String[] fromFieldNames = new String[]{DBAdapter.KEY_NAME};
    int[] toViewIDs = new int[]{R.id.textsv};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter= new     SimpleCursorAdapter(getBaseContext(),R.layout.item_layoutt,cursor , fromFieldNames , toViewIDs ,0);
    final ListView myList = (ListView) findViewById(R.id.listView1);
    myList.setAdapter(myCursorAdapter);


}

Activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.adapterx.MainActivity" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_below="@+id/textView1" >

</ListView>

<Button
    android:id="@+id/get"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/listView1"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/listView1"
    android:text="Get" />

</RelativeLayout>

item_layoutt.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<CheckBox
    android:id="@+id/textcb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/textsv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="TextView" />

</LinearLayout>

enter image description here

It displays the list perfectly, but when I click on any checkbox the checked item repeats and changes when scrolled up and down.

I don't know how to solve this with ViewHolder .I read an article http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/ ,but I fail to optimize the listview.

How can I modify MainActivity class with MyCustomAdapter class to solve this problem.Please help me with the entire code.

private class MyCustomAdapter extends dataAdapter {

 private LayoutInflater mInflater;
 private Cursor cur;

 public MyCustomAdapter(Context context, Cursor c) {
 super(context,c);   
 this.mInflater = LayoutInflater.from(context);
 this.cur = c;
 }


 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

 ViewHolder holder = null;

 if (convertView == null) {
 convertView = this.mInflater.inflate(R.layout.chamber_item, null);
            viewHolder = new ViewHolder();
            viewHolder.text = (TextView)convertView.findViewById(R.id.textsv);
            viewHolder.checkbox =  (CheckBox)convertView.findViewById(R.id.textcb);

            convertView.setTag(viewHolder);
 } 
 else {
 holder = (ViewHolder) convertView.getTag();
 }
 this.cur.moveToPosition(position);

             viewHolder.text.setText(this.cur.getString(this.cur.getColumnIndex("texts")));          
          viewHolder.checkbox.setText(this.cur.getString(this.cur.getColumnIndex("istrue")));
       return convertView;
   }
   static class ViewHolder
    {
        TextView text;
        CheckBox checkbox;

    }

 }
babiro
  • 95
  • 2
  • 11
  • would you please explain more detail about this line :when I click on any checkbox the checked item repeats and changes when scrolled up and down. – Tanim reja May 19 '15 at 04:16
  • When I check only on item 1, it's also checked on regular intervals say on 5,10,15 so on .When scrolled up and down ,I see the checked items change their place ,i.e. the item 1 is unchecked , item 3 is checked , item 8 is checked...that's so randomly checked and unchecked . – babiro May 19 '15 at 04:31
  • hmm got it .....wait – Tanim reja May 19 '15 at 04:32

2 Answers2

0

Try the below adapter and see if it helps.

 private static class MyCustomAdapter extends dataAdapter  {

     private LayoutInflater mInflater;
     private Cursor cur;
     private HashMap<Integer, Boolean> tracker = new HashMap<Integer, Boolean>();

     public MyCustomAdapter(Context context, Cursor c) {
      super(context,c);   
      this.mInflater = LayoutInflater.from(context);
      this.cur = c;
      for(int i=0;i<c.getCount();i++){
         tracker.put(i, false);
      }
     }


     @Override
     public View getView(final int position, View convertView, ViewGroup parent) {

     final ViewHolder holder = null;

     if (convertView == null) {
     convertView = this.mInflater.inflate(R.layout.chamber_item, null);
                holder = new ViewHolder();
                holder .text = (TextView)convertView.findViewById(R.id.textsv);
                holder .checkbox =  (CheckBox)convertView.findViewById(R.id.textcb); 
                convertView.setTag(holder );
     } 
     else {
     holder = (ViewHolder) convertView.getTag();
     }
     this.cur.moveToPosition(position);
     holder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            tracker.put(position, isChecked);
        }
    });
     holder.text.setText(this.cur.getString(this.cur.getColumnIndex("texts")));          
     holder.checkbox.setText(this.cur.getString(this.cur.getColumnIndex("istrue")));
     holder.checkbox.setChecked(tracker.get(position));

           return convertView;
       }
       static class ViewHolder
        {
            TextView text;
            CheckBox checkbox;
        }


     }
dora
  • 2,047
  • 3
  • 18
  • 20
0

Add a private ArrayList<Integer> selectedPosision = new ArrayList<Integer> to keep the selected checkbox position that will help you when you scroll your listview because getview(...) method will also call this time. make final int position in your getView (...) parameter this prevent randomly selected your listitem when you click only one itme. and add a clickListener for keeping the record of checkbox( checked or unchecked) state .. viewHolder.checkbox.setChecked(selectedPosition.indexOf(position)>-1); this line make sure that this checkbox was selected or not... in every time when list scrolled....

   private class MyCustomAdapter extends dataAdapter {

     private LayoutInflater mInflater;
     private Cursor cur;
     private ArrayList<Integer> selectedPosision = new ArrayList<Integer> ();

     public MyCustomAdapter(Context context, Cursor c) {
     super(context,c);   
     this.mInflater = LayoutInflater.from(context);
     this.cur = c;
     }


     @Override
     public View getView(final int position, View convertView, ViewGroup parent) {

     ViewHolder holder = null;

     if (convertView == null) {
     convertView = this.mInflater.inflate(R.layout.chamber_item, null);
                viewHolder = new ViewHolder();
                viewHolder.text = (TextView)convertView.findViewById(R.id.textsv);
                viewHolder.checkbox =  (CheckBox)convertView.findViewById(R.id.textcb);

                convertView.setTag(viewHolder);
     } 
     else {
     holder = (ViewHolder) convertView.getTag();
     }
     this.cur.moveToPosition(position);

                 viewHolder.text.setText(this.cur.getString(this.cur.getColumnIndex("texts")));          
              viewHolder.checkbox.setText(this.cur.getString(this.cur.getColumnIndex("istrue")));

viewHolder.checkbox.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub                  
                    if (selectedPosition.indexOf(position) > -1) {
                      selectedPosition.remove(selectedPosition.indexOf(position));
                    } else {
                       selectedPosition.add(position);
                    }

                }
            });
            viewHolder.checkbox.setChecked(selectedPosition.indexOf(position)>-1);
           return convertView;
       }
       static class ViewHolder
        {
            TextView text;
            CheckBox checkbox;

        }

     }
Tanim reja
  • 2,120
  • 1
  • 16
  • 23