anon
anon

Reputation:

Using a SQlite database to store checkbox states in custom baseadapter listview

I am using a custom BaseAdapter listview to display a list of installed apps with a checkbox next to it. I am trying to save the each listview item and checkbox state in an SQLite database after attempting to do so with SharedPreferences.

I would like it to store the state of the checkbox once the listview has been closed and once the application has been closed aswell.

enter image description here

I have done much research and have been at this for well over a week, but haven't been able to produce or find a solution that works for me.

How to save state of checkboxes in database (both true and false states)

Storing the state of checkbox in listview while using custom BaseAdapter in android?

Here is my BaseAdapter class:

package com.ibc.android.demo.appslist.app;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.spicycurryman.getdisciplined10.app.R;

import java.util.List;

public class ApkAdapter extends BaseAdapter {



    //Pastebin link:  http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK http://pastebin.com/gFuuM4dY

    SharedPreferences sharedPrefs;
    List<PackageInfo> packageList;
    Activity context;
    PackageManager packageManager;
    boolean[] itemChecked;

    String PACKAGE_NAME;


    public ApkAdapter(Activity context, List<PackageInfo> packageList,
                      PackageManager packageManager) {
        super();
        this.context = context;
        this.packageList = packageList;
        this.packageManager = packageManager;
        itemChecked = new boolean[packageList.size()];


    }


    private class ViewHolder {
        TextView apkName;
        CheckBox ck1;
    }

    public int getCount() {
        return packageList.size();
    }

    public Object getItem(int position) {
        return packageList.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

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

        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.installed_apps, null);
            holder = new ViewHolder();

            holder.apkName = (TextView) convertView
                    .findViewById(R.id.appname);
            holder.ck1 = (CheckBox) convertView
                    .findViewById(R.id.checkBox1);

            convertView.setTag(holder);
            //holder.ck1.setTag(packageList.get(position));

        } else {

            holder = (ViewHolder) convertView.getTag();
        }


        // ViewHolder holder = (ViewHolder) convertView.getTag();
        PackageInfo packageInfo = (PackageInfo) getItem(position);


        Drawable appIcon = packageManager
                .getApplicationIcon(packageInfo.applicationInfo);

        PACKAGE_NAME = packageInfo.packageName;

        final String appName = packageManager.getApplicationLabel(
                packageInfo.applicationInfo).toString();
        appIcon.setBounds(0, 0, 80, 80);
        holder.apkName.setCompoundDrawables(appIcon, null, null, null);
        holder.apkName.setCompoundDrawablePadding(15);
        holder.apkName.setText(appName);

        holder.ck1.setChecked(false);


        if (itemChecked[position])
            holder.ck1.setChecked(true);
        else
            holder.ck1.setChecked(false);

        Log.d("just loaded??", appName);


        Log.d("just loaded 2?", appName);


        holder.ck1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

               /* sharedPrefs = context.getSharedPreferences("apps", Context.MODE_PRIVATE);
                holder.ck1.setChecked(sharedPrefs.getBoolean(appName,false));
                SharedPreferences.Editor editor = context.getSharedPreferences(appName, Context.MODE_PRIVATE).edit();*/

                if (holder.ck1.isChecked()) {
                    itemChecked[position] = true;
                    holder.ck1.setChecked(true);
                    Log.i("This is", " checked: " + position);
                    //editor.putBoolean(appName, true);
                    Log.d("put true", appName);

                    //editor.apply();

                } else {
                    itemChecked[position] = false;
                    holder.ck1.setChecked(false);
                    Log.i("This is", " not checked: " + position);
                    //editor.putBoolean(appName, false);
                    Log.d("put false", appName);

                    //editor.apply();

                }

            }

        });


        return convertView;

    }

}

Here is my DataBaseHandler class:

package com.ibc.android.demo.appslist.app;

/**
 * Created by Spicycurryman on 8/5/14.
 */
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

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

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "packagenameManager";

    // Packagename table name
    private static final String TABLE_PACKAGE_NAME = "packagenames";

    // Contacts Table Columns names
    private static final String KEY_PACKAGE_NAME = "packagenames";
    private static final String KEY_STATE = "state";


    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_PACKAGE_NAME + "("
                + KEY_PACKAGE_NAME + " STRING PRIMARY KEY," + KEY_STATE + " INT,"
                 + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_PACKAGE_NAME);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new packagename
    void addPackageName(PackageName packageName) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_STATE, packageName.getPACKAGENAME()); // Packagename

        // Inserting Row
        db.insert(TABLE_PACKAGE_NAME, null, values);
        db.close(); // Closing database connection
    }

    // Getting single package
    PackageName getPackageName(String packagename) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_PACKAGE_NAME, new String[] {KEY_PACKAGE_NAME,
                        KEY_STATE }, KEY_PACKAGE_NAME + "=?",
                new String[] { packagename }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        PackageName packageName = new PackageName((cursor.getString(0)),
                cursor.getInt(1));
        // return packagename
        return packageName;
    }

    // Getting All packagenames
    public List<PackageName> getAllPackageNames() {
        List<PackageName> packageNameList = new ArrayList<PackageName>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_PACKAGE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                PackageName packageName = new PackageName();
                packageName.setPACKAGENAME(cursor.getString(0));
                packageName.setState(cursor.getInt(1));
                // Adding contact to list
                packageNameList.add(packageName);
            } while (cursor.moveToNext());
        }

        // return packagename list
        return packageNameList;
    }

    // Updating single packagename
    public int updatePackageName(PackageName packageName) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_STATE, packageName.getState());

        // updating row
        return db.update(TABLE_PACKAGE_NAME, values, KEY_PACKAGE_NAME + " = ?",
                new String[] { String.valueOf(packageName.getPACKAGENAME()) });
    }

    // Deleting single packagename
    public void deletePackageName(PackageName packageName) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_PACKAGE_NAME, KEY_PACKAGE_NAME + " = ?",
                new String[] { String.valueOf(packageName.getPACKAGENAME()) });
        db.close();
    }


    // Getting packagename Count
    public int getPackageNameCount() {
        String countQuery = "SELECT  * FROM " + TABLE_PACKAGE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}

And lastly here is my Object class:

package com.ibc.android.demo.appslist.app;

/**
 * Created by Spicycurryman on 8/5/14.
 */
public class PackageName {

    //private variables
    String _packagename;
    int _state;

    // Empty constructor
    public PackageName(){

    }
    // constructor
    public PackageName(String packagename, int state){
        this._packagename = packagename;
        this._state = state;
    }

    // constructor
    public PackageName(int state){
        this._state = state;
    }
    // getting PACKAGENAME
    public String getPACKAGENAME(){
        return this._packagename;
    }

    // setting packagename
    public void setPACKAGENAME(String packagename){
        this._packagename = packagename;
    }

    // getting state
    public int getState(){
        return this._state;
    }

    // setting state
    public void setState(int state){
        this._state = state;
    }


}

How would I go about achieving this?

Upvotes: 2

Views: 6165

Answers (1)

SaravanaRaja
SaravanaRaja

Reputation: 3406

ListView_CheckBoxActivity class

@SuppressLint("NewApi")
public class ListView_CheckBoxActivity extends Activity {
CheckboxAdapter listItemAdapter;
DataHandler handler;
Button cancel;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    handler=new DataHandler(getBaseContext());
    handler.open();
    System.out.println("Entered in the checked box");
    Button getValue=(Button)findViewById(R.id.get_value);
    cancel=(Button) findViewById(R.id.cancel);
    getValue.setOnClickListener(listener);  
    //listview 
    ListView list = (ListView) findViewById(R.id.list);        
    ArrayList<HashMap<String, Object>> listData=new ArrayList<HashMap<String,Object>>();
    int size=0;
    Cursor getSize=handler.CategoryNameLength();
    getSize.moveToFirst();
    size=getSize.getInt(0);

    String[] name=new String[size];
    int catgoryIndex=0;
    Cursor getCategoryName=handler.CategoryName();

    cancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();
        }
    });
    if(getCategoryName.moveToFirst())
    {
        do
        {
            name[catgoryIndex]=getCategoryName.getString(0);
            System.out.println("Strng"+name[catgoryIndex]);
            catgoryIndex++;

        }while(getCategoryName.moveToNext());
    }
    for(int i=0;i<size;i++){            
        HashMap<String, Object> map=new HashMap<String, Object>();
        System.out.println("Line1");
        map.put("friend_image", R.drawable.icon);
        map.put("friend_username", name[i]);
        listData.add(map);
    }       
    listItemAdapter = new CheckboxAdapter(this, listData);
    list.setAdapter(listItemAdapter);
}

OnClickListener listener=new OnClickListener() {        
    @Override
    public void onClick(View v) {
        HashMap<Integer, Boolean> state =listItemAdapter.state;         
        String options="***Selected***";        
        for(int j=0;j<listItemAdapter.getCount();j++){
            System.out.println("state.get("+j+")=="+state.get(j));
               //checking the state is on , if on i,m updating my table
            if(state.get(j)!=null){
                @SuppressWarnings("unchecked")
                HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
                String username=map.get("friend_username").toString();
                Cursor getID=handler.getIdForCategory(username);
                getID.moveToFirst();
                int id=getID.getInt(0);
                System.out.println("ID=="+id);
                handler.updateDefaulttable_flag_1(id);//updating my table
                options+="\n"+username;

            }
           //same as checking sate is off, if off updating my database table
            if(state.get(j)== null){
                @SuppressWarnings("unchecked")
                HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
                String username=map.get("friend_username").toString();
                Cursor getID=handler.getIdForCategory(username);
                getID.moveToFirst();
                int id=getID.getInt(0);
                System.out.println("ID=="+id);
                handler.updateDefaulttable_flag_0(id);
            }
        }
        Toast.makeText(getApplicationContext(), options, Toast.LENGTH_LONG).show();
        finish();
    }
};  
}

item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/RelativeLayout" 
 android:layout_width="fill_parent"         
 android:layout_height="wrap_content" 
 android:paddingBottom="4dip" 
 android:paddingRight="12dip" >
 <ImageView android:id="@+id/friend_image"
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"  
 android:paddingTop="6dip"
 android:paddingLeft="2dip"
 android:layout_centerVertical="true"
 android:layout_alignParentLeft="true" /> 
 <TextView android:id="@+id/friend_username"  
 android:layout_width="fill_parent"   
 android:layout_height="wrap_content" 
 android:textSize="18dip" 
 android:textColor="#ccc"     
 android:paddingTop="6dip"
 android:paddingRight="2dip"
 android:layout_toRightOf="@id/friend_image"    />
 <TextView android:id="@+id/friend_id"
 android:layout_width="fill_parent"    
 android:layout_height="wrap_content"             
 android:layout_below="@+id/friend_username"        
 android:layout_marginRight="36dip"
 android:paddingRight="2dip"
 android:layout_toRightOf="@id/friend_image"    
 android:textColor="#fff"                        
 android:maxLines="2" />
<CheckBox android:id="@+id/selected" 
 android:layout_width="wrap_content"    
 android:layout_height="wrap_content"
 android:layout_marginLeft="36dip"        
 android:layout_centerVertical="true"
 android:layout_alignParentRight="true"
 android:focusable="false"  />
</RelativeLayout>

CheckboxAdapter class

public class CheckboxAdapter extends BaseAdapter {
DataHandler handler;
SQLiteDatabase db;

Context context;
ArrayList<HashMap<String, Object>> listData;    
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();      

public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData) {
    this.context = context;
    this.listData = listData;   
}

@Override
public int getCount() {
    return listData.size();
}

@Override
public Object getItem(int position) {
    return listData.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

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

    LayoutInflater mInflater = LayoutInflater.from(context);
    convertView = mInflater.inflate(R.layout.item, null);
    ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
    image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
    TextView username = (TextView) convertView.findViewById(R.id.friend_username);
    username.setText((String) listData.get(position).get("friend_username"));
    CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);    
    boolean isChecked=true;
    handler=new DataHandler(context);
    handler.open();

    Cursor setUserFlag = handler.setCheckFlagID();
    if(setUserFlag.moveToFirst())
    {
        do
        {
            int getid = setUserFlag.getInt(0);
            getid = getid - 1;
            state.put(getid , isChecked);   
        }while(setUserFlag.moveToNext());
    }
    check.setChecked((state.get(position) == null ? false : true));

    handler.close();


    check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            if (isChecked) {
                state.put(position, isChecked);                 
            } else {
                state.remove(position);             
            }
        }
    });

    check.setChecked((state.get(position) == null ? false : true));
    return convertView;
}
}

datahandler

public Cursor setCheckFlagID() {
        return db.rawQuery("select _id from default_category_table where flag=1;", null);

    }
public void updateDefaulttable_flag_1(int id) {
        String selectQuery = "UPDATE  default_category_table SET flag=1 WHERE _id='"+id+"'";
        Cursor cursor = db.rawQuery(selectQuery, null);
        System.out.print("Count"+cursor.getCount()); 

    }

    public void updateDefaulttable_flag_0(int id) {
        String selectQuery = "UPDATE  default_category_table SET flag=0 WHERE _id='"+id+"'";
        Cursor cursor = db.rawQuery(selectQuery, null);
        System.out.print("Count"+cursor.getCount());
    }
public Cursor getIdForCategory(String username) {
        return db.rawQuery("select _id from default_category_table where   category='"+username+"';", null);
    }
public Cursor CategoryNameLength() {
        return db.rawQuery("select count(category) from Default_Category_Table", null);

    }

main.xml

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

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="272dp"
    android:layout_weight="5.16" />

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/get_value"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="23dp"
        android:paddingRight="20dp"
        android:text="Save" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="34dp"
        android:text="Cancel" />

</RelativeLayout>

</LinearLayout>

Upvotes: 2

Related Questions