ListView选中的复选框

问题描述 投票:0回答:1

我正在创建一个用于交流学习的Android应用程序

[我制作了一个单词列表,它包含一个CheckBoxes和TextView,TextView用于显示单词,使用CheckBox以确定我在ListView中选择了哪个项目。

我使用“提交”按钮将单词的ID存储在SQLite中。当我关闭并再次打开活动时,我想查看已选中的复选框,但是此代码仅保存到我的数据库中,而当我再次打开活动时不显示所选项目

这是活动

public class PerkembanganLevel1 extends AppCompatActivity{

    private ContentDao contentDao;
    private ChildDao childDao;
    private Child anakYangDipilih;

    public Global global;

    private AssessmentDao assessmentDao;
    private Assessment assessment;

    String idYangSudahBisa;

    PerkembanganAdapter perkembanganAdapter = null;

    ContentHistory contentHistory;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_perkembangan_level1);

        contentDao = new ContentDao(this);
        contentDao.open();

        childDao = new ChildDao(this);
        childDao.open();

        anakYangDipilih = ((Global) getApplicationContext()).getChild();

        idYangSudahBisa = anakYangDipilih.getLevel1();

        ArrayList<ContentHistory> listKataLevel1 = (ArrayList<ContentHistory>) contentDao.getAllWordByLevel(1);

        perkembanganAdapter = new PerkembanganAdapter(this, R.layout.list_perkembangan, listKataLevel1);

        ListView level1 =  findViewById(R.id.LVPlv1);
        level1.setAdapter(perkembanganAdapter);
        Log.i("listKataLevel1 ", String.valueOf(listKataLevel1));
        level1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                contentHistory = (ContentHistory) parent.getItemAtPosition(position);

            }
        });
        findViewById(R.id.BtnPLv1Submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idYangSudahBisa = perkembanganAdapter.idYangSudahBisa();

                anakYangDipilih.getId();
                anakYangDipilih.setLevel1(idYangSudahBisa);
                anakYangDipilih.setCreatedBy(((Global) getApplicationContext()).getTherapist().getId());
                anakYangDipilih.setUpdatedBy(((Global) getApplicationContext()).getTherapist().getId());
                anakYangDipilih.setCreatedDate(new Date());
                anakYangDipilih.setUpdatedDate(new Date());
                anakYangDipilih = childDao.saveChild(anakYangDipilih);

                Toast.makeText(PerkembanganLevel1.this, "Perkembangan Anak pada level 1 Berhasil Diperbarui", Toast.LENGTH_SHORT).show();
            }
        });


    }

}

这是适配器


public class PerkembanganAdapter extends ArrayAdapter<ContentHistory> {


    String idYangSudahBisa;

    private ChildDao childDao;
    private Child anakYangDipilih;

    public ArrayList<ContentHistory> contentHistories;

    public PerkembanganAdapter(Context context, int id, ArrayList<ContentHistory> contentHistories){
        super(context, id, contentHistories);
        this.contentHistories = new ArrayList<>();
        this.contentHistories.addAll(contentHistories);



        childDao = new ChildDao(getContext());
        childDao.open();

        anakYangDipilih = ((Global) context.getApplicationContext()).getChild();
        this.idYangSudahBisa = anakYangDipilih.getLevel1();

    }

    private class ViewHolder{
        TextView title;
        CheckBox checkBoxes;
    }

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

        ViewHolder viewHolder = null;
        if (convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_perkembangan, null);

            viewHolder = new ViewHolder();
            viewHolder.title = convertView.findViewById(R.id.TVListPerkembangan);
            viewHolder.checkBoxes = convertView.findViewById(R.id.CBListPerkembangan);

            convertView.setTag(viewHolder);

            viewHolder.checkBoxes.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CheckBox checkBox = (CheckBox) v;
                    ContentHistory contentHistory = (ContentHistory) checkBox.getTag();
                    contentHistory.setSelected(checkBox.isChecked());
                    if (checkBox.isChecked()){
                        idYangSudahBisa = idYangSudahBisa + ","+contentHistory.getId();
                        //Toast.makeText(getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show();
                    } else {
                        idYangSudahBisa = idYangSudahBisa.replace(","+contentHistory.getId(), "");
                        //Toast.makeText(getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show();
                    }

                }
            });



        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }


        ContentHistory contentHistory = contentHistories.get(position);
        viewHolder.title.setText(contentHistory.getTitle());

        viewHolder.checkBoxes.setChecked(contentHistory.getSelected());
        viewHolder.checkBoxes.setTag(contentHistory);


        return convertView;

    }

    public String idYangSudahBisa(){

        return this.idYangSudahBisa;
    }

}
...
java android checkbox android-sqlite listviewitem
1个回答
0
投票

不需要提交按钮,因为您可以在单击复选框时实时更新(切换)数据库。

[重要的方面是在ContentDao中添加了一种方法,例如:-

public void toggleCheckedById(long id) {

    db.execSQL(
            "UPDATE " + TABLE_NAME +
                    " SET " + COLUMN_CHECKED + " = NOT  " + COLUMN_CHECKED +
                    " WHERE " + COLUMN_ID + "=?",
            new String[]{String.valueOf(id)}
    );
}
  • 这等于UPDATE the_table SET the_check_column = NOT the_check_column WHERE the_id_column =?
    • 注意?使用传递给execSQL的第二个参数替换(绑定),该参数在这种情况下是String [],其中包含单个元素,该元素是要更改的行的id

这可以通过CheckBox的onClick调用,并传递从视图的Tag中提取的ID。

考虑此代码的简化版本:-

数据库助手(也许是您的[[Global.java类)] DatabaseHelper.java:-

public class DatabaseHelper extends SQLiteOpenHelper { public static final String DBNAME = "perkembangan.db"; public static final int DBVERSION = 1; private static DatabaseHelper sInstance; private DatabaseHelper(Context context) { super(context, DBNAME, null, DBVERSION); } public static synchronized DatabaseHelper getInstance(Context context) { if (sInstance == null) { sInstance = new DatabaseHelper(context); } return sInstance; } @Override public void onCreate(SQLiteDatabase db) { String createContentSQL = "CREATE TABLE IF NOT EXISTS " + ContentDao.TABLE_NAME + "(" + ContentDao.COLUMN_ID + " INTEGER PRIMARY KEY, " + ContentDao.COLUMN_NAME + " TEXT, " + ContentDao.COLUMN_CHECKED + " INTEGER DEFAULT 0" + ")"; db.execSQL(createContentSQL); /* ADD SOME TESTING DATA WHEN THE DATABASE IS CREATED */ ContentValues cv = new ContentValues(); for (int i=0; i < 3; i++) { cv.clear(); cv.put(ContentDao.COLUMN_NAME,"Name" + String.valueOf(i)); db.insert(ContentDao.TABLE_NAME,null,cv); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public static String qualifyColumnName(String table, String column) { return table + "." + column; } }
    注意,这会添加3行进行测试。
  • 您可能不需要此。
  • ContentDao.java

  • (对其解释):-public class ContentDao { private static DatabaseHelper sInstance; private static SQLiteDatabase db; public static final String TABLE_NAME = "content"; public static final String COLUMN_ID = BaseColumns._ID; public static final String QUALIFIEDCOLUMN_ID = DatabaseHelper.qualifyColumnName(TABLE_NAME,COLUMN_ID); public static final String COLUMN_NAME = "name"; public static final String COLUMN_CHECKED = "checked"; public ContentDao(Context context) { db =(sInstance = DatabaseHelper.getInstance(context)).getWritableDatabase(); } public void toggleCheckedById(long id) { db.execSQL( "UPDATE " + TABLE_NAME + " SET " + COLUMN_CHECKED + " = NOT " + COLUMN_CHECKED + " WHERE " + COLUMN_ID + "=?", new String[]{String.valueOf(id)} ); } public SQLiteDatabase getDb() { return db; } public int updateCheckedById(ContentHistory ch) { ContentValues cv = new ContentValues(); cv.put(COLUMN_CHECKED,ch.isChecked()); return db.update(TABLE_NAME,cv,COLUMN_ID + "=?",new String[]{String.valueOf(ch.getId())}); } public ArrayList<ContentHistory> getContentHistory() { ArrayList<ContentHistory> rv = new ArrayList<>(); Cursor csr = db.query(TABLE_NAME,null,null,null,null,null,null); while (csr.moveToNext()) { rv.add(new ContentHistory(csr.getLong(csr.getColumnIndex(COLUMN_ID)), csr.getString(csr.getColumnIndex(COLUMN_NAME)), csr.getInt(csr.getColumnIndex(COLUMN_CHECKED))> 0) ); } csr.close(); return rv; } public class ContentHistory { private long id; private String name; private boolean checked; ContentHistory(long id, String name, boolean checked) { this.id = id; this.name = name; this.checked = checked; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } } }
      << [NOTE
    为方便起见,已包含ContentHistory类
  • 使用名称代替标题(直到后来才意识到)
  • 如上所述,重要的补充是
  • toggleCheckedById
  • 方法。
  • PerkembanganAdapter.java

    public class PerkembanganAdapter extends ArrayAdapter<ContentDao.ContentHistory> { ContentDao contentDao; public ArrayList<ContentDao.ContentHistory> contentHistories; public PerkembanganAdapter(Context context, int id, ArrayList<ContentDao.ContentHistory> contentHistories){ super(context, id, contentHistories); contentDao = new ContentDao(context); this.contentHistories = new ArrayList<>(); this.contentHistories.addAll(contentHistories); /* childDao = new ChildDao(getContext()); childDao.open(); anakYangDipilih = ((Global) context.getApplicationContext()).getChild(); this.idYangSudahBisa = anakYangDipilih.getLevel1(); */ } private class ViewHolder{ TextView title; CheckBox checkBoxes; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null){ LayoutInflater layoutInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = layoutInflater.inflate(R.layout.list_perkembangan, null); viewHolder = new ViewHolder(); viewHolder.title = convertView.findViewById(R.id.TVListPerkembangan); viewHolder.checkBoxes = convertView.findViewById(R.id.CBListPerkembangan); convertView.setTag(viewHolder); viewHolder.checkBoxes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox checkBox = (CheckBox) v; ContentDao.ContentHistory contentHistory = (ContentDao.ContentHistory) checkBox.getTag(); contentHistory.setChecked(checkBox.isChecked()); contentDao.toggleCheckedById(contentHistory.getId()); //<<<<< will update (toggle) database in real time /* NOT NEEDED if (checkBox.isChecked()){ //idYangSudahBisa = idYangSudahBisa + ","+contentHistory.getId(); //Toast.makeText(v.getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show(); } else { //idYangSudahBisa = idYangSudahBisa.replace(","+contentHistory.getId(), ""); //Toast.makeText(getContext(), ""+idYangSudahBisa,Toast.LENGTH_SHORT).show(); } */ } }); } else { viewHolder = (ViewHolder) convertView.getTag(); } ContentDao.ContentHistory contentHistory = contentHistories.get(position); viewHolder.title.setText(contentHistory.getName()); viewHolder.checkBoxes.setChecked(contentHistory.isChecked()); viewHolder.checkBoxes.setTag(contentHistory); return convertView; } }

    请注意,许多原始代码已被删除,只剩下了演示所需的重要代码。

    • 为方便起见,也似乎已省略/更改了看来是外语名称的名称。
    • 显然,该代码必须进行调整以适合。这是正在演示的技术。
  • PerkembanganLevel1.java活动:-

    public class PerkembanganLevel1 extends AppCompatActivity{ private ContentDao contentDao; private ListView level1; private PerkembanganAdapter perkembanganAdapter; private ArrayList<ContentDao.ContentHistory> contentHistory; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_perkembangan_level1); level1 = this.findViewById(R.id.level1); contentDao = new ContentDao(this); manageListView(); /*contentDao.open(); childDao = new ChildDao(this); childDao.open(); anakYangDipilih = ((Global) getApplicationContext()).getChild(); idYangSudahBisa = anakYangDipilih.getLevel1(); */ /* ArrayList<ContentDao.ContentHistory> listKataLevel1 = (ArrayList<ContentDao.ContentHistory>) contentDao.getAllWordByLevel(1); perkembanganAdapter = new PerkembanganAdapter(this, R.layout.list_perkembangan, listKataLevel1); //ListView level1 = findViewById(R.id.LVPlv1); level1.setAdapter(perkembanganAdapter); Log.i("listKataLevel1 ", String.valueOf(listKataLevel1)); level1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { contentHistory = (ContentDao.ContentHistory) parent.getItemAtPosition(position); } }); findViewById(R.id.BtnPLv1Submit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { idYangSudahBisa = perkembanganAdapter.idYangSudahBisa(); anakYangDipilih.getId(); anakYangDipilih.setLevel1(idYangSudahBisa); anakYangDipilih.setCreatedBy(((Global) getApplicationContext()).getTherapist().getId()); anakYangDipilih.setUpdatedBy(((Global) getApplicationContext()).getTherapist().getId()); anakYangDipilih.setCreatedDate(new Date()); anakYangDipilih.setUpdatedDate(new Date()); anakYangDipilih = childDao.saveChild(anakYangDipilih); Toast.makeText(PerkembanganLevel1.this, "Perkembangan Anak pada level 1 Berhasil Diperbarui", Toast.LENGTH_SHORT).show(); } }); */ } /* Will refresh the Listview when returning from an invoked activity just in case data has changed */ @Override protected void onResume() { super.onResume(); manageListView(); } private void manageListView() { contentHistory = contentDao.getContentHistory(); if (perkembanganAdapter == null) { perkembanganAdapter = new PerkembanganAdapter(this,R.layout.list_perkembangan,contentHistory); level1.setAdapter(perkembanganAdapter); } else { perkembanganAdapter.notifyDataSetChanged(); // Not really needed if updating when checked } } } 演示结果

    第一次运行时:-

    enter image description here

    第二运行第2行打勾,然后重新启动

    enter image description here

    第三次运行所有3个复选框,然后重新启动

    enter image description here

  • © www.soinside.com 2019 - 2024. All rights reserved.