简体   繁体   中英

Android Checkbox with Listview and SQLite

I have created an application that a user can store player information. I am now looking to have a checkbox to confirm that the player is available. I know that sqlite cannot store a boolean value so was wondering if someone could help me with a way around this. I have added the checkbox but at the moment i have it stored as a 0 value with no functionality.

Below is the display adapter:

public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email;
//private ArrayList<String> ConFirm;


public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
    this.mContext = c;

    this.id = id;
    this.firstName = fname;
    this.lastName = lname;
    this.Email = email;
    this.ConFirm = check;
}

public int getCount() {
    // TODO Auto-generated method stub
    return id.size();
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public View getView(int pos, View child, ViewGroup parent) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (child == null) {
        layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        child = layoutInflater.inflate(R.layout.listcell, null);
        mHolder = new Holder();
        mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
        mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
        mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
        mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
        mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
        child.setTag(mHolder);
    } else {
        mHolder = (Holder) child.getTag();
    }
    mHolder.txt_id.setText(id.get(pos));
    mHolder.txt_fName.setText(firstName.get(pos));
    mHolder.txt_lName.setText(lastName.get(pos));
    mHolder.txt_eMail.setText(Email.get(pos));

    return child;
}

public class Holder {
    TextView txt_id;
    TextView txt_fName;
    TextView txt_lName;
    TextView txt_eMail;
    CheckBox txt_cOnfirm;
}

}

Here is the display call from the main activity:

private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    user_eMail.clear();
    user_cOnfirm.clear();
    if (mCursor.moveToFirst()) {
        do {
            userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
            user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
            user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
            user_cOnfirm.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
    userList.setAdapter(disadpt);
    mCursor.close();
}
{

}

And finally the Dbhelper:

 public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TEXT DEFAULT 0)";
    db.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

}

If you would like any more information or code just let me know. Thankyou in advance.

------UPDATED------

Below is the db update function from the FoursFragment.java class:

//add 
    view.findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {


        public void onClick(View v) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("update", false);
            startActivity(i);

        }
    });

//Update
userList.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("Confirm", user_cOnfirm.get(arg2));
            i.putExtra("Mail", user_eMail.get(arg2));
            i.putExtra("Fname", user_fName.get(arg2));
            i.putExtra("Lname", user_lName.get(arg2));
            i.putExtra("ID", userId.get(arg2));
            i.putExtra("update", true);
            startActivity(i);

        }
    });




    //delete
    userList.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {

            build = new AlertDialog.Builder(getActivity());
            build.setTitle("Delete " + user_fName.get(arg2) + " "
                    + user_lName.get(arg2) + " " + user_eMail.get(arg2));
            build.setMessage("Do you want to delete ?");
            build.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {

                            Toast.makeText(
                                    getActivity(),
                                    user_fName.get(arg2) + " "
                                            + user_lName.get(arg2)
                                            + " is deleted.", 3000).show();

                            dataBase.delete(
                                    DbHelper.TABLE_NAME,
                                    DbHelper.KEY_ID + "="
                                            + userId.get(arg2), null);
                            displayData();
                            dialog.cancel();
                        }
                    });

            build.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = build.create();
            alert.show();

            return true;
        }
    });
    return view;
    }
    }}



@Override
public void onResume() {
    displayData();
    super.onResume();
}


//display


@SuppressLint("UseValueOf")
private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    user_eMail.clear();
    user_cOnfirm.clear();
    if (mCursor.moveToFirst()) {
        do {
            userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
            user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
            user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
            user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
    userList.setAdapter(disadpt);
    mCursor.close();
}
{

At first you should change your database table. Don't use the type 'TEXT' to store the boolean, use the type 'TINYINT' instead of that. TINYINT provides 1 byte to save the value. Because of that you can define a constraint (the check at the end), to avoid saving values like 3.

String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";

To read the value from the database change the loop.

  while(mCursor.moveToNext()) {      
        userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
        user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
        user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
        user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
        user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
  }

You request an Integer instead of a String as returning value from the database. If you need to get a boolean, you can add the comparision with 1.

Just a tip, you don't need your do-while. The cursor points at the beginning on a position before the first entry. With the call of moveToNext for the first time, you move it to the first entry. If there's no entry, the loop will be skipped.

You need to change the type of the ArrayList to Boolean (with a big B).

Add the initialization with the value for the checkbox

mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos));

These are the necessary changes. I add the changed code below (not tested)

public class DisplayAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> id;
    private ArrayList<String> firstName;
    private ArrayList<String> lastName;
    private ArrayList<String> Email; // better name it email
    private ArrayList<Boolean> ConFirm; //better name it confirm, it's one word


    public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
        this.mContext = c;

        this.id = id;
        this.firstName = fname;
        this.lastName = lname;
        this.Email = email;
        this.ConFirm = check;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return id.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder; // the m shows that this shall be a member variable, this is just local for this method.
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.listcell, null);
            mHolder = new Holder();
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
            mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
            mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
            mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_id.setText(id.get(pos));
        mHolder.txt_fName.setText(firstName.get(pos));
        mHolder.txt_lName.setText(lastName.get(pos));
        mHolder.txt_eMail.setText(Email.get(pos));
        mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos).booleanValue());
        return child;
    }

    public class Holder {
        TextView txt_id;
        TextView txt_fName;
        TextView txt_lName;
        TextView txt_eMail;
        CheckBox txt_cOnfirm;
    }

    }

The part from your main activity

private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    user_eMail.clear();
    user_cOnfirm.clear();
    while(mCursor.moveToNext()) {      
        userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
        user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
        user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
        user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
        user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
  }
    DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
    userList.setAdapter(disadpt);
    mCursor.close();
}
{

}

And your DBHelper

public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, 2); // The 2 is the version. It have to be higher than the old, because we changed the database schema

}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
    db.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

}

I hope this solves your problem, if not feel free to ask another question, if please rate this answer as positive.

Ps: Take a look at the coding guidelines: https://source.android.com/source/code-style.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM