gpt4 book ai didi

java - 列表值和我给定的值相等,那么复选框将被选中?

转载 作者:行者123 更新时间:2023-12-02 09:36:46 24 4
gpt4 key购买 nike

我正在开发 Android 项目。我的情况我将列表值存储在 firebase 实时数据库中,然后列表值和我给定的值相等,复选框将被选中。

For example: the List holding 36,40, 44.then my given value is equals to that List value then the equivalent checkbox will be checked. enter image description here

我的代码是

checkcheck=FirebaseDatabase.getInstance().getReference().child("Products").child(newprokey);

checkcheck.child("size").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

final List<String> areas = new ArrayList<String>();

for (DataSnapshot areaSnapshot : dataSnapshot.getChildren()) {
String areaName = areaSnapshot.child("Value").getValue(String.class);
areas.add(areaName);
}

String[] check = areas.toArray(new String[areas.size()]);

for (int i= 0;i<check.length;i++)
{
if (check[i] == "36")
{
jS36.setChecked(true);
}
if (check[i] == "38")
{
jM38.setChecked(true);
}
if (check[i] == "40")
{
jL40.setChecked(true);
}

if (check[i] == "42")
{
jXl42.setChecked(true);
}

if (check[i] == "44")
{
jXxl44.setChecked(true);
}
if (check[i] == "46")
{
jXXXl46.setChecked(true);
}
}

}


@Override
public void onCancelled(DatabaseError databaseError) {

}
});

我尝试这个代码。它不起作用,给我解决方案。

最佳答案

您应该使用 .equals 来比较字符串,而不是 == 检查此 answer另外,您可以遍历 List 而不是创建数组。

final List<String> areas = new ArrayList<String>();

for (DataSnapshot areaSnapshot : dataSnapshot.getChildren()) {
String areaName = areaSnapshot.child("Value").getValue(String.class);
areas.add(areaName);
}

for (String area : areas){
if(area.equals("36")){
jS36.setChecked(true);
}
if(area.equals("38")){
jM38.setChecked(true);
}
// continue
}

编辑更简单的解决方案是创建一个复选框映射并直接使用区域名称更改状态。

// Have this Map where you initialize the checkboxes(ie after you call `findViewById` to reference the checkboxes)
HashMap<String, CheckBox> checkBoxHashMap = new HashMap<>();
checkBoxHashMap.put("36", js36);
checkBoxHashMap.put("38", jM38);
// add all the checkboxes with the areaName

for (DataSnapshot areaSnapshot : dataSnapshot.getChildren()) {
String areaName = areaSnapshot.child("Value").getValue(String.class);
// To make sure areaName is a valid value in the Checkbox HashMap
if(checkBoxHashMap.containsKey(areaName)){
checkBoxHashMap.get(areaName).setChecked(true);
}
}

关于java - 列表值和我给定的值相等,那么复选框将被选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57443699/

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