【问题标题】:How to Remove Duplicate item in SQLite when Using ListView使用 ListView 时如何删除 SQLite 中的重复项
【发布时间】:2020-04-26 16:26:15
【问题描述】:

在使用 ListView 从 SQLite 获取数据时,我一直有重复的项目,我正在使用来自两个不同表中两个不同列的数据填充两个 TextView。当我使用每个列和表中的单个数据时,它们按计划工作,但在一起有重复的项目。

来自database.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 绑定到 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】:

    没有看到您的数据库表架构,这或多或少只是 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

    【讨论】:

      【解决方案2】:

      我建议您将ID 用于您的数据库记录,并根据ID 获取unique,但是请记住,您不能多次添加相同的数据,在这种情况下,您可以比较数据(如果它存在于DB 然后不添加 else 添加。

      【讨论】:

      猜你喜欢
      • 2022-01-27
      • 2014-11-11
      • 2022-01-01
      • 2019-02-02
      • 2017-10-08
      • 2016-12-19
      • 1970-01-01
      • 2018-03-10
      • 2011-11-29
      相关资源
      最近更新 更多