无法将ListItem复选框状态保存到SQLite

时间:2018-06-19 08:21:59

标签: android listview custom-arrayadapter

我正在使用一个包含ImageView,TextView和Checkbox的ListView。

我想将Checkbox状态保存到SQLite。现在,当我更改活动或重新加载应用程序时,更改丢失了。

我正在使用 CustomArrayAdaptor 。这是代码 -

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;
}
}

DatabaseHelper类如下

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);
}
}

NoteItem类如下

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(); }
}

自定义列表商品代码如下

<?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>

请查看代码,并帮助我将 Checkbox状态保存到数据库。 我在StackOverflow上不够活跃。所以请忽略错误。

感谢您即将回复。

1 个答案:

答案 0 :(得分:0)

您没有指定已保存的已检查状态

In [74]: Person.name.__doc__
Out[74]: "I'm the property."

你也不应该将String用于所有事情,但这应该让它运作起来。考虑更改数据库以使用整数和类来使用布尔值。