java - 如何在使用 ListView 时删除 SQLite 中的重复项

标签 java android sqlite android-studio

使用 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/

相关文章:

java - 从坐标获取城市名称

java - 在开始另一个 Activity 之前使用 Thread.sleep(Milliseconds) 等待一下是一种不好的做法吗?

java - Android API 25 之后,SQLite db 文件在设备/模拟器上的位置是什么?

sql - 当有重音字符时如何 SQL 比较列?

Java OutOfMemory 异常 : mmap error on loading zip file

java - 如何测试涉及 java 组件的 Contivo map ?

java - 如何测量java方法的内存使用情况

android - 尝试使用 ionic cordova run android --device 时未找到设备/模拟器

Sqlite3 - 为什么我可以将字符串插入整数字段?

java - 在 Java 中,如何以简单的方式遍历队列而不破坏它?