我有一个 SQLite数据库,它通过 ArrayList 将数据提供给cardviews。数据库中的每条记录都包含不同的颜色代码,我想将每张卡的背景颜色设置为数据库中各自的颜色。颜色代码位于数据库内的“ 颜色 ”列下。
现在这里是我的代码,因为你可以看到我的 SQL SELECT查询应该只为每张卡选择一个特定记录,但这里做的是它选择所有记录存在于数据库中。
如果我使用c.moveToFirst();
,它会选择表格的第一行,如果我使用c.moveToLast();
,它会选择表格的最后一行?如果我清除提及...where id ="+cardid+";"
,是不是应该只选择一个特定的行?
我面临的问题是它为所有卡片视图设置了一个共同的背景颜色,我需要它对每张卡片都不同。我做错了什么?
代码参考:
TextView myid 包含数据库中每条记录的唯一标识符
PersonViewHolder(View itemView, final Activity theact) {
super(itemView);
personName = (TextView)itemView.findViewById(R.id.person_name);
personAge = (TextView)itemView.findViewById(R.id.person_age);
personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
myid = (TextView)itemView.findViewById(R.id.IDTAG);
ohcolor = (TextView)itemView.findViewById(R.id.COLORCODE);
cv = (CardView)itemView.findViewById(R.id.cv);
cv.setUseCompatPadding(true);
openDatabase();
final String cardid = myid.getText().toString().trim();
c = db.rawQuery("SELECT color FROM persons WHERE id ="+cardid+";", null);
c.moveToFirst();
colorbro = c.getString(0);
i = Integer.parseInt(colorbro);
cv.setCardBackgroundColor(i);
cv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// do something
}
});
}
答案 0 :(得分:0)
问题是,您只有一个对cardView的引用,当您为其分配新对象时,它会更新。
替换此行代码
cv = (CardView)itemView.findViewById(R.id.cv);
用这个
CardView cv = (CardView)itemView.findViewById(R.id.cv);
这应该可以解决您的问题。
答案 1 :(得分:0)
db.rawQuery
的文档说" SQL字符串不能是;终止",这可能是你的问题。 http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
答案 2 :(得分:0)
从colors.xml
文件获取颜色的正确方法是为getColor
方法提供颜色名称或其ID:
i = Integer.parseInt(colorbro);
cv.setCardBackgroundColor(ContextCompat.getColor(context, i));
我不确定您i
变量中的内容。调试并查看它是否具有正确的值。
答案 3 :(得分:0)
我自己找到了一个解决方案,我们可以在 OnBindViewHolder 方法中设置卡片的背景颜色
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
personViewHolder.myid.setText(persons.get(i).id);
personViewHolder.personName.setText(persons.get(i).name);
personViewHolder.personAge.setText(persons.get(i).age);
personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
personViewHolder.ohcolor.setText(persons.get(i).color);
//setting background color here
personViewHolder.cv.setCardBackgroundColor(Integer.parseInt(persons.get(i).color));
}
此处,人是从SQLite数据库获取数据的ArrayList。由于我的数据库还有一个颜色代码列,我将它提供给ArrayList并在 OnBindViewHolder 中检索它,并设置每张卡的背景颜色。