gpt4 book ai didi

java - ListView 选中的复选框

转载 作者:行者123 更新时间:2023-11-29 22:37:20 24 4
gpt4 key购买 nike

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

我做了一个word的List,里面包含了一个CheckBoxes和TextView,TextView是用来显示这个word的,CheckBox的作用是判断我选中了ListView中的哪个item。

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

这是 Activity

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

}
...

最佳答案

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

重要的方面是在 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 的第二个参数替换(绑定(bind)),在本例中,它是一个包含单个元素的字符串 [],该元素是要更改的行的 id

这可以从 CheckBox 的 onClick 调用,传递从 View 标签中提取的 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;
}
}
}
  • 注意为方便起见,包含了 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 Activity :-

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

Second Run row 2 勾选然后重新启动

enter image description here

Third Run all 3 checkeck boxes reversed and then restarted

enter image description here

关于java - ListView 选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59388949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com