保存交换机状态

时间:2019-08-29 20:10:47

标签: android switch-statement onclicklistener ischecked

我正在为创建待办事项的项目创建一个“待办事项”应用程序,它们被保存在SQLite数据库中,并显示在RecyclerView中,如下所示。

This is the interface

我想知道在刷新活动或杀死/重新启动应用程序后如何保存开关状态(选中或未选中),就像EditTexts一样。

这是SqliteDatabase代码:

public class SqliteDatabase extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "todo_db";
private static final String TABLE_TODOS = "todos";

private static final String COLUMN_ID = "id";
private static final String COLUMN_TITLE = "todotitle";
private static final String COLUMN_DESC = "tododescription";

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

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TODOS_TABLE = "CREATE TABLE " + TABLE_TODOS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_TITLE + " TEXT," + COLUMN_DESC + " TEXT" + ")";
    db.execSQL(CREATE_TODOS_TABLE);
}

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

public ArrayList<Todos> listTodos() {
    String sql = "select * from " + TABLE_TODOS;
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<Todos> storeTodos = new ArrayList<>();
    Cursor cursor = db.rawQuery(sql, null);
    if(cursor.moveToFirst()){
        do{
            int id = Integer.parseInt(cursor.getString(0));
            String todo = cursor.getString(1);
            String description = cursor.getString(2);
            storeTodos.add(new Todos(id, todo, description));
        }while (cursor.moveToNext());
    }
    cursor.close();
    return storeTodos;
}

public void addTodos(Todos todos){
    ContentValues values = new ContentValues();
    values.put(COLUMN_TITLE, todos.getTodo());
    values.put(COLUMN_DESC, todos.getDescription());
    SQLiteDatabase db = this.getWritableDatabase();
    db.insert(TABLE_TODOS, null, values);
}

public void updateTodos(Todos todos){
    ContentValues values = new ContentValues();
    values.put(COLUMN_TITLE, todos.getTodo());
    values.put(COLUMN_DESC, todos.getDescription());
    SQLiteDatabase db = this.getWritableDatabase();
    db.update(TABLE_TODOS, values, COLUMN_ID + " =?", new String[] {String.valueOf(todos.getId())});
}

public Todos findTodos(String todo){
    String query = "Select * FROM " + TABLE_TODOS + " WHERE " + COLUMN_TITLE + " = " + "todo";
    SQLiteDatabase db = getWritableDatabase();
    Todos todos = null;
    Cursor cursor = db.rawQuery(query, null);
    if (cursor.moveToFirst()){
        int id = Integer.parseInt(cursor.getString(0));
        String todoslist = cursor.getString(1);
        String todosdesc = cursor.getString(2);
        todos = new Todos(id, todoslist, todosdesc);
    }
    cursor.close();
    return todos;
}

public void deleteTodo (int id){
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_TODOS, COLUMN_ID + " =?", new String[] {String.valueOf(id)});
}
}

这是Todos对象的模型类:

public class Todos {
private int id;
private String todo;
private String description;
private boolean done;
private boolean fav;

public Todos(String todo, String description){
    this.todo = todo;
    this.description = description;
    this.done = done;
    this.fav = fav;
}

public Todos(int id, String todo, String description){
    this.id = id;
    this.todo = todo;
    this.description = description;
    this.done = done;
    this.fav = fav;
}

public int getId() {
    return id;
}

public String getTodo() {
    return todo;
}

public String getDescription() {
    return description;
}

public boolean isDone() {
    return done;
}

public boolean isFav() {
    return fav;
}

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

public void setTodo(String todo) {
    this.todo = todo;
}

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

public void setDone() {
    this.done = done;
}

public void setFav(boolean fav) {
    this.fav = fav;
}
}

这是视图持有人:

public class TodoViewHolder extends RecyclerView.ViewHolder {

public TextView todo,description;
public Switch done;
public ToggleButton fav;

public TodoViewHolder(View itemView) {
    super(itemView);
    todo = (TextView) itemView.findViewById(R.id.title_view);
    description = (TextView) itemView.findViewById(R.id.description_view);
    done = (Switch) itemView.findViewById(R.id.done_switch);
    fav = (ToggleButton) itemView.findViewById(R.id.fav_button);
}
}

这是我基本上卡在其中的适配器:

public class TodoAdapter extends RecyclerView.Adapter<TodoViewHolder> implements Filterable {
private Context context;
private ArrayList<Todos> listTodos;
private ArrayList<Todos> mArrayList;

private SqliteDatabase mDatabase;

public TodoAdapter(Context context, ArrayList<Todos> listTodos){
  this.context = context;
  this.listTodos = listTodos;
  this.mArrayList = listTodos;
  mDatabase = new SqliteDatabase(context);
}

@Override
public TodoViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_list_layout, parent, false);
    return new TodoViewHolder(view);
}

@Override
public void onBindViewHolder(final TodoViewHolder holder, int position) {
    final Todos todo = listTodos.get(position);

    holder.todo.setText(todo.getTodo());
    holder.description.setText(todo.getDescription());

// HERE IS WHERE I'M STUCK
holder.done.setChecked(todo.isDone());
    holder.done.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            editTaskDialog(todo);
        }
    });

    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            mDatabase.deleteTodo(todo.getId());
            ((Activity)context).finish();
            context.startActivity(((Activity) context).getIntent());
            return false;
        }
    });
}

@Override
public Filter getFilter() {

    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {

            String charString = charSequence.toString();

            if (charString.isEmpty()) {

                listTodos = mArrayList;
            } else {

                ArrayList<Todos> filteredList = new ArrayList<>();

                for (Todos todos : mArrayList) {

                    if (todos.getTodo().toLowerCase().contains(charString)) {

                        filteredList.add(todos);
                    }
                }

                listTodos = filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = listTodos;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            listTodos = (ArrayList<Todos>) filterResults.values;
            notifyDataSetChanged();
        }
    };
}

@Override
public int getItemCount() {
    return listTodos.size();
}

private void editTaskDialog(final Todos todos){
    LayoutInflater inflater = LayoutInflater.from(context);
    View subView = inflater.inflate(R.layout.add_todo, null);

    final EditText titleField = (EditText)subView.findViewById(R.id.title);
    final EditText descriptionField = (EditText)subView.findViewById(R.id.description);

    if(todos != null){
        titleField.setText(todos.getTodo());
        descriptionField.setText(String.valueOf(todos.getDescription()));
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Edit Note");
    builder.setView(subView);
    builder.create();

    builder.setPositiveButton("EDIT NOTE", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final String todo = titleField.getText().toString();
            final String description = descriptionField.getText().toString();

            if(TextUtils.isEmpty(todo)){
                Toast.makeText(context, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
            }
            else{
                mDatabase.updateTodos(new Todos(todos.getId(), todo, description));
                ((Activity)context).finish();
                context.startActivity(((Activity)context).getIntent());
            }
        }
    });

    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(context, "Task cancelled", Toast.LENGTH_LONG).show();
        }
    });
    builder.show();
}
}

1 个答案:

答案 0 :(得分:1)

  1. 在表中添加一列以存储已选中/未选中状态。
    String CREATE_TODOS_TABLE = "CREATE TABLE " + TABLE_TODOS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_TITLE + " TEXT," + COLUMN_DESC + " TEXT," + COLUMN_IS_CHECKED + " INTEGER DEFAULT 0)";

  1. unchecked存储 0 ,为checked值存储 1 (也为updateTodos进行编码)。
    public void addTodos(Todos todos){
        ContentValues values = new ContentValues();
        values.put(COLUMN_TITLE, todos.getTodo());
        values.put(COLUMN_DESC, todos.getDescription());
        values.put(COLUMN_IS_CHECKED, todos.isDone()?1:0);
        SQLiteDatabase db = this.getWritableDatabase();
        db.insert(TABLE_TODOS, null, values);
    }

  1. 准备待办事项清单,如下所示:
    public ArrayList<Todos> listTodos() {
        String sql = "select * from " + TABLE_TODOS;
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<Todos> storeTodos = new ArrayList<>();
        Cursor cursor = db.rawQuery(sql, null);
        if(cursor.moveToFirst()){
            do{
                int id = Integer.parseInt(cursor.getString(0));
                String todo = cursor.getString(1);
                String description = cursor.getString(2);
                boolean isChecked = cursor.getInt(3)==0 ? false: true;
                storeTodos.add(new Todos(id, todo, description, isChecked));
            }while (cursor.moveToNext());
        }
        cursor.close();
        return storeTodos;
    }

  1. Todos类中添加一个构造函数,并将参数添加到setDone方法中。
    public Todos(int id, String todo, String description, boolean done){
        this.id = id;
        this.todo = todo;
        this.description = description;
        this.done = done;
        this.fav = fav;
    }

    public void setDone(boolean done) {
        this.done = done;
    }


  1. 更新列表项的选中按钮状态
    holder.done.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //update list item checked button state here to keep it changed after scrolling
            todo.setDone(isChecked);
            listTodos.get(position).setDone(isChecked);
            //update state to keep changed after refreshing or re-launching app
            mDatabase.updateTodos(todo);
        }
    });