在SQLite中使用ListView时如何删除重复的项目?

问题描述 投票:0回答:1

当我使用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);
    }
}

当绑定适配器到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]
java android sqlite android-studio
1个回答
1
投票

如果没有看到你的db表模式,这或多或少只是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,可汗Acadamy有一个伟大的互动学习路径。

https:/www.khanacademy.orgcomputer-programmingsql-join-on-tables5409956539006976


0
投票

我建议你用 ID 为您的数据库记录,并得到它 unique 但是,请记住,你不能多次添加相同的数据,在这种情况下,你可以比较数据是否存在于 DB 那就不加了,否则就加了。

© www.soinside.com 2019 - 2024. All rights reserved.