首页 > 解决方案 > Unable to save ListItem checkbox status to SQLite

问题描述

I am working on a ListView which has ImageView, TextView, and Checkbox.

I want to save the Checkbox status to SQLite. Right now changes lost when I change the Activity or reload the application.

I am using CustomArrayAdaptor. Here is the code-

package com.eranujsaini.todos;

import android.content.Context;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomArrayAdaptor extends ArrayAdapter<NoteItem> {

Context context;
int resource;
ArrayList<NoteItem> objects;
DatabaseHelper databaseHelper;

public CustomArrayAdaptor(Context context, int resource, ArrayList<NoteItem> objects) {
    super(context, resource, objects);
    this.context= context;
    this.resource= resource;
    this.objects= objects;

    databaseHelper= new DatabaseHelper(context);
}

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

    final Holder holder;
    if(convertView == null) {
        holder = new Holder();
        convertView = LayoutInflater.from(context).inflate(resource,null);
        holder.heading = (TextView) convertView.findViewById(R.id.tv_list_item_title);
        holder.taskStatus = (CheckBox) convertView.findViewById(R.id.taskStatus);
        holder.finalPriority = (ImageView) convertView.findViewById(R.id.selected_priority);
        convertView.setTag(holder);
    }
    else {
        holder = (Holder) convertView.getTag();
    }

    //ToDo to set task priority
    if(objects.get(position).getSelectedPriority()==1) {
        holder.finalPriority.setImageResource(R.drawable.ic_priority_1st_24dp);
    }else if(objects.get(position).getSelectedPriority()==2) {
        holder.finalPriority.setImageResource(R.drawable.ic_priority_2nd_24dp);
    } else if(objects.get(position).getSelectedPriority()==3) {
        holder.finalPriority.setImageResource(R.drawable.ic_priority_3rd_24dp);
    }
    //ToDo to set task heading
    holder.heading.setText(objects.get(position).getHeading());

    //ToDo to set task status
    holder.taskStatus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            NoteItem noteItem = new NoteItem();
            String flag;
            if(isChecked) {
                //ToDo to mark task as completed.
                holder.heading.setPaintFlags(holder.heading.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                flag = "true";
                noteItem.setTaskStatus(flag);
                databaseHelper.updateNote(noteItem);
            } else {

                //ToDo to mark task as uncompleted.
                holder.heading.setPaintFlags(0);
                flag = "false";
                noteItem.setTaskStatus(flag);
                databaseHelper.updateNote(noteItem);
            }
        }
    });
    return convertView;
}

class Holder {
    ImageView finalPriority;
    CheckBox taskStatus;
    TextView heading;
    TextView description;
}
}

The DatabaseHelper Class is as below

package com.eranujsaini.todos;
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;

public class DatabaseHelper extends SQLiteOpenHelper {

//TODOs to create a data table
String TABLE_NOTES="user_notes";
String KEY_ID="id";
String HEADING= "heading";
String DESCRIPTION = "description";
String PRIORITY = "taskPriority";
String STATUS = "taskStatus";

String CREATE_TABLE_USER_NOTES = "CREATE TABLE IF NOT EXISTS " +
        TABLE_NOTES +
        "(" +
        KEY_ID +
        " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        HEADING +
        " VARCHAR(100), " +
        DESCRIPTION +
        " VARCHAR(500)," +
        PRIORITY +
        " VARCHAR(1000)," +
        STATUS +
        " VARCHAR(1000)" +
        ")";
public DatabaseHelper(Context context) {
    super(context, "Notes", null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_USER_NOTES);
}
public void createNote(NoteItem noteItem){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values= new ContentValues();
    values.put(HEADING, noteItem.getHeading());
    values.put(DESCRIPTION, noteItem.getDescription());
    values.put(PRIORITY, noteItem.getSelectedPriority());
    values.put(STATUS, noteItem.getTaskStatus());
    db.insert(TABLE_NOTES, null, values);
}
public void updateNote(NoteItem noteItem){
    SQLiteDatabase db= this.getWritableDatabase();
    ContentValues values= new ContentValues();
    values.put(HEADING, noteItem.getHeading());
    values.put(DESCRIPTION, noteItem.getDescription());
    values.put(PRIORITY, noteItem.getSelectedPriority());
    values.put(STATUS, noteItem.getTaskStatus());
    db.update(TABLE_NOTES, values, KEY_ID + "=" + noteItem.getId(), null);
}
public void deleteNote(Integer id){
    SQLiteDatabase db= this.getWritableDatabase();
    db.delete(TABLE_NOTES, KEY_ID + "=" + id, null);
    }
public NoteItem getNote(Integer id) {
    SQLiteDatabase db= this.getReadableDatabase();
    NoteItem noteItem= new NoteItem();
    String query="SELECT * FROM " + TABLE_NOTES + " WHERE " + KEY_ID + "=" + id;
    Cursor c= db.rawQuery(query,null);
    if(c.moveToFirst()) {
        noteItem.setId(c.getInt(c.getColumnIndex(KEY_ID)));
        noteItem.setHeading(c.getString(c.getColumnIndex(HEADING)));
        noteItem.setDescription(c.getString(c.getColumnIndex(DESCRIPTION)));
        noteItem.setSelectedPriority(c.getInt(c.getColumnIndex(PRIORITY)));
        noteItem.setTaskStatus(c.getString(c.getColumnIndex(STATUS)));
    }
    return noteItem;
}
public ArrayList<NoteItem> getAllNotes() {
    SQLiteDatabase db= this.getReadableDatabase();
    ArrayList<NoteItem> noteItems= new ArrayList<>();
    String query="SELECT * FROM " + TABLE_NOTES;
    Cursor c= db.rawQuery(query,null);
    if(c.moveToFirst()) {
        do {
            NoteItem noteItem= new NoteItem();
            noteItem.setId(c.getInt(c.getColumnIndex(KEY_ID)));
            noteItem.setHeading(c.getString(c.getColumnIndex(HEADING)));
            noteItem.setDescription(c.getString(c.getColumnIndex(DESCRIPTION)));
            noteItem.setSelectedPriority(c.getInt(c.getColumnIndex(PRIORITY)));
            noteItem.setTaskStatus(c.getString(c.getColumnIndex(STATUS)));
            noteItems.add(noteItem);
        } while(c.moveToNext());
    }
    return noteItems;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
    onCreate(db);
}
}

The NoteItem class is as below

package com.eranujsaini.todos;
public class NoteItem {

Integer id;
Integer selectedPriority;
String heading;
String description;
String taskStatus;

public Integer getId() { return id; }

public void setId(Integer id) { this.id = id; }

public Integer getSelectedPriority() { return selectedPriority; }

public void setSelectedPriority(Integer selectedPriority) { this.selectedPriority = selectedPriority; }

public String getHeading() { return heading; }

public void setHeading(String heading) { this.heading = heading; }

public String getDescription() { return description; }

public void setDescription(String description) { this.description = description; }

public String getTaskStatus() { return taskStatus; }

public void setTaskStatus(String taskStatus) { this.taskStatus = taskStatus; }

@Override
public String toString() { return getHeading(); }
}

Custom List Item code is as below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:descendantFocusability="blocksDescendants">

<ImageView
    android:id="@+id/selected_priority"
    android:layout_width="24dp"
    android:layout_height="24dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:focusableInTouchMode="false"
    android:layout_marginTop="20dp"
    android:gravity="center_vertical"
    android:focusable="false"
    app:srcCompat="@drawable/ic_priority_3rd_24dp"
    tools:ignore="VectorDrawableCompat" />
<TextView
    android:id="@+id/tv_list_item_title"
    android:layout_width="228dp"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceListItem"
    android:gravity="center_vertical"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="46dp"
    android:text="TextView" />
<CheckBox
    android:id="@+id/taskStatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/tv_list_item_title"
    android:layout_alignParentEnd="true"
    android:layout_marginEnd="12dp"
    android:text="" />
</RelativeLayout>

Please review the code, and help me to save the Checkbox status to database. I am not enough active on StackOverflow. So please ignore the mistakes.

Thanks for your forthcoming response.

标签: androidlistviewcustom-arrayadapter

解决方案


您没有分配已保存的检查状态

...
    //ToDo to set task heading
    holder.heading.setText(objects.get(position).getHeading());


// Set task status           
holder.taskStatus.setChecked(objects.get(position).getTaskStatus().equals("true"));

    //ToDo to set task status
    holder.taskStatus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
...

您也不应该对所有内容都使用字符串,但这应该可以使其正常工作。考虑更改您的数据库以使用整数和类以使用布尔值。


推荐阅读