使用 ListView 从 SQLite 获取数据时,我一直有重复的项目,我用两个不同表中两个不同列的数据填充两个 TextView。当我使用每列和表中的单独数据时,它们按计划工作,但在一起时存在重复的项目。
来自数据库.java
public Cursor getQuestionAndAnswer(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
return sqLiteDatabase.rawQuery("select * from Question_Table, Answer_Table" ,null);
}
从光标适配器
public class QuestionAndAnswerAdapter extends CursorAdapter {
public QuestionAndAnswerAdapter(Context context, Cursor c) {
super(context, c, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.q_a_layout,parent,false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView Question = view.findViewById(R.id.text_question);
String listQuestion = cursor.getString(cursor.getColumnIndexOrThrow("QUESTIONS"));
Question.setText(listQuestion);
TextView Answer = view.findViewById(R.id.text_answer);
String listAnswer = cursor.getString(cursor.getColumnIndexOrThrow("ANSWERS"));
Answer.setText(listAnswer);
}
}
将Adapter绑定(bind)到ListView时
questionCursor = myDataBaseClass.getQuestionAndAnswer();
if (questionCursor != null) {
QuestionAndAnswerAdapter questionAndAnswerAdapter = new QuestionAndAnswerAdapter(this, questionCursor);
QuestionList.setAdapter(questionAndAnswerAdapter);
}
[![The first text is duplicated, while the second text displays correctly][1]][1]
最佳答案
如果没有看到您的数据库表架构,这或多或少只是 sudo 代码,但我认为您可能只需要更改 SQL 语句。
// give me ALL columns, from both tables
select * from Question_Table, Answer_Table
我认为您似乎正在尝试匹配问题的答案。
// give me all columns from this table matched up with this ID from that table.
SELECT * FROM question_table JOIN answer_table ON question_table.id = answer_table.questionID
对于快速温习 SQL,Khan Acadamy 有一个很棒的交互式学习路径:
https://www.khanacademy.org/computer-programming/sql-join-on-tables/5409956539006976
关于java - 如何在使用 ListView 时删除 SQLite 中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61444188/