如何获得测验应用程序的问题和答案?

时间:2019-05-06 17:40:51

标签: java android sqlite

我正在android中做一个测验应用程序,但我有点卡住了。我有一个如下所示的sqlite数据库:

问题 ID 问题

答案 ID 追问 回答 柯林斯

但是我不知道如何一一回答问题,也不知道如何获得与按钮中的问题相关的答案。我已经有sqlite数据库,但是我没有方法应该如何以及如何在主要活动中调用它 有帮助吗?

顺便说一句,corinc表示它是否正确,真值或假值也是如此

我尝试使用适配器获取按钮的列表视图,但我认为这不是一个好主意,因为如果ananser的优劣(包括声音和图像),我想添加警报。我像默认值一样传递Idquestion

数据库代码

public List<Answers> getAnswers(int Idquestion) {
Answers a = null;
List<Answers> list = new ArrayList<>();

openDatabase();

Cursor cursor = database.rawQuery("SELECT * FROM ANSWERS " +
                "WHERE Idquestion = ?",
        new String[]{String.valueOf(Idquestion)}
);

cursor.moveToNext();

while (!cursor.isAfterLast()) {

    a = new Answers(
            cursor.getInt(0),
            cursor.getInt(1),
            cursor.getString(2),
            cursor.getString(3));
    list.add(a);
    cursor.moveToNext();
}

return list;

}

适配器代码

public View getView(final int i, View convertView, ViewGroup viewGroup) {

View view = View.inflate(context, R.layout.listview, null);
final Button btnAnswers = (Button)view.findViewById(R.id.btnAnswers);
btnAnswers.setText(list.get(i).getAnswer());
view.setTag(list.get(i).getId());

btnAnswers.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {


        //Toast.makeText(view.getContext(), list.get(i).getAnswer(), Toast.LENGTH_SHORT).show();
        if (list.get(i).getValue().equals("true")) {
            Toast.makeText(view.getContext(), "YES", Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(view.getContext(), "NO", Toast.LENGTH_SHORT).show();
        }
    }
});

return view;
}

1 个答案:

答案 0 :(得分:1)

  1. 在您的活动中,为正在询问的当前问题(例如int current_question = 0)添加一个类变量(第一个为0),
  2. 假设您有一个 Questions 类(类似于您的 Answers 类)(如果未创建),则使用数据库代码中的方法来提取所有问题(或全部)必填问题)放入List<Questions>(非常类似于List)。
  3. 开始活动时,构建列表并设置视图,以根据 current_question 值显示从列表中获得的问题中的问题。
  4. 根据使用 current_question 作为偏移量获得的问题的getIDQuestion方法,填充或重新填充答案列表。
  5. 在任何情况下,如果您想触发下一个问题,然后将此增量设为 current_question 值(只要它小于List的大小),然后转到4。

这里是一个示例,为方便起见,将Cursor和SimpleCursor适配器用于答案列表。

此示例获取所有问题,并具有一个按钮,用于显示下一个Question触发器(为简单起见)。单击按钮转到下一个问题。到达最后一个问题时,按钮被隐藏。

该示例大致基于您的适配器代码。

在这种情况下,活动MainActivity是:-

public class MainActivity extends AppCompatActivity {

    DatabaseCode mDBHlpr;
    List<Questions> questions_to_Ask; //<<<<<<<<<< ready for 2.
    int current_question = 0; //<<<<<<<<<<< 1.

    SimpleCursorAdapter mSCA;
    Cursor mAnswers;
    ListView mAnswerListView;
    TextView mQuestion;
    Button mNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAnswerListView = this.findViewById(R.id.answerlist);
        mQuestion = this.findViewById(R.id.question);
        mNext = this.findViewById(R.id.next);
        mDBHlpr = new DatabaseCode(this);
        addSomeQuestionsIfNone();
        questions_to_Ask = mDBHlpr.getQuestions(); //<<<<<<<<<< 2.
        handleAnswersForQuestion();
        handleNextQuestionButton();
    }

    //<<<<<<<<<< 4. >>>>>>>>>
    private void handleAnswersForQuestion() {
        mQuestion.setText(questions_to_Ask.get(current_question).getQuestion()); // sets the text for the current question 3.
        mAnswers =  mDBHlpr.getAnswersAsCursor((questions_to_Ask.get(current_question)).getId());
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_1,
                    mAnswers,
                    new String[]{DatabaseCode.COl_ANSWERS_ANSWER},
                    new int[]{android.R.id.text1},
                    0
            );
            mAnswerListView.setAdapter(mSCA);
        } else {
            mSCA.swapCursor(mAnswers);
        }
    }

    //<<<<<<<<<< 5. >>>>>>>>>>
    private void handleNextQuestionButton() {
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                current_question++;
                if (current_question < questions_to_Ask.size()) {
                    handleAnswersForQuestion(); //<<<<<<<<<<

                    //<<<<<<<<< ????? hide button if no more
                    if (current_question == (questions_to_Ask.size() - 1)) {
                        mNext.setVisibility(View.INVISIBLE);
                    }
                } else {
                    // No next Question
                    current_question--;
                }
            }
        });
    }


    private void addSomeQuestionsIfNone() {
        if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DatabaseCode.TABLE_QUESTIONS) == 0) {
            mDBHlpr.addQuestionWithAnswers("What is 1 + 1?",
                    Arrays.asList(
                            new Answers("0",Answers.INCORRECTANSWER),
                            new Answers("1",Answers.INCORRECTANSWER),
                            new Answers("2",Answers.CORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("What is 2 * 2",
                    Arrays.asList(
                            new Answers("4",Answers.CORRECTANSWER),
                            new Answers("3",Answers.INCORRECTANSWER),
                            new Answers("5",Answers.INCORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("Who killed Cok Robin",
                    Arrays.asList(
                            new Answers("The fly with a little eye",Answers.INCORRECTANSWER),
                            new Answers("The sparrow with a bow and arrow",Answers.CORRECTANSWER),
                            new Answers("The bull with a pull",Answers.INCORRECTANSWER)
                    ));

            mDBHlpr.addQuestionWithAnswers("What is 1 + 1?",
                    Arrays.asList(
                            new Answers("0",Answers.INCORRECTANSWER),
                            new Answers("1",Answers.INCORRECTANSWER),
                            new Answers("2",Answers.CORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("What is 2 * 2",
                    Arrays.asList(
                            new Answers("4",Answers.CORRECTANSWER),
                            new Answers("3",Answers.INCORRECTANSWER),
                            new Answers("5",Answers.INCORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("Who killed Cok Robin",
                    Arrays.asList(
                            new Answers("The fly with a little eye",Answers.INCORRECTANSWER),
                            new Answers("The sparrow with a bow and arrow",Answers.CORRECTANSWER),
                            new Answers("The bull with a pull",Answers.INCORRECTANSWER)
                    ));

            mDBHlpr.addQuestionWithAnswers("What is 1 + 1?",
                    Arrays.asList(
                            new Answers("0",Answers.INCORRECTANSWER),
                            new Answers("1",Answers.INCORRECTANSWER),
                            new Answers("2",Answers.CORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("What is 2 * 2",
                    Arrays.asList(
                            new Answers("4",Answers.CORRECTANSWER),
                            new Answers("3",Answers.INCORRECTANSWER),
                            new Answers("5",Answers.INCORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("Who killed Cok Robin",
                    Arrays.asList(
                            new Answers("The fly with a little eye",Answers.INCORRECTANSWER),
                            new Answers("The sparrow with a bow and arrow",Answers.CORRECTANSWER),
                            new Answers("The bull with a pull",Answers.INCORRECTANSWER)
                    ));

            mDBHlpr.addQuestionWithAnswers("What is 1 + 1?",
                    Arrays.asList(
                            new Answers("0",Answers.INCORRECTANSWER),
                            new Answers("1",Answers.INCORRECTANSWER),
                            new Answers("2",Answers.CORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("What is 2 * 2",
                    Arrays.asList(
                            new Answers("4",Answers.CORRECTANSWER),
                            new Answers("3",Answers.INCORRECTANSWER),
                            new Answers("5",Answers.INCORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("Who killed Cok Robin",
                    Arrays.asList(
                            new Answers("The fly with a little eye",Answers.INCORRECTANSWER),
                            new Answers("The sparrow with a bow and arrow",Answers.CORRECTANSWER),
                            new Answers("The bull with a pull",Answers.INCORRECTANSWER)
                    ));

            mDBHlpr.addQuestionWithAnswers("What is 1 + 1?",
                    Arrays.asList(
                            new Answers("0",Answers.INCORRECTANSWER),
                            new Answers("1",Answers.INCORRECTANSWER),
                            new Answers("2",Answers.CORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("What is 2 * 2",
                    Arrays.asList(
                            new Answers("4",Answers.CORRECTANSWER),
                            new Answers("3",Answers.INCORRECTANSWER),
                            new Answers("5",Answers.INCORRECTANSWER)
                    )
            );
            mDBHlpr.addQuestionWithAnswers("Who killed Cok Robin",
                    Arrays.asList(
                            new Answers("The fly with a little eye",Answers.INCORRECTANSWER),
                            new Answers("The sparrow with a bow and arrow",Answers.CORRECTANSWER),
                            new Answers("The bull with a pull",Answers.INCORRECTANSWER)
                    ));

        }
    }
}
  • 请注意方法 addSomeQuestionsIfNone 将15个问题(为方便起见,将5个问题归为相同的三个问题)添加到数据库中。

DatabaseCode.java 是:-

public class DatabaseCode extends SQLiteOpenHelper {

    public static final String DBNAME = "qandadb";
    public static final int DBVERSION = 1;
    public static final String TABLE_QUESTIONS = "questions";
    public static final String TABLE_ANSWERS = "answers";

    public static final String COL_QUESTIONS_ID = BaseColumns._ID;
    public static final String COl_QUESTIONS_QUESTION = "question";
    public static final String COl_ANSWERS_ID = BaseColumns._ID;
    public static final String COL_ANSWERS_QUESTIONID = "IdQuestion";
    public static final String COl_ANSWERS_ANSWER = "answer";
    public static final String COL_ANSWERS_CORINC = "corinc";


    SQLiteDatabase database;

    public DatabaseCode(Context context) {
        super(context, DBNAME, null, DBVERSION);
        database = this.getWritableDatabase();
    }

    private void openDatabase() {
        database = this.getWritableDatabase();
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String crt_questions_table_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTIONS + "(" +
                COL_QUESTIONS_ID + " INTEGER PRIMARY KEY," +
                COl_QUESTIONS_QUESTION + " TEXT" +
                ")";
        String crt_answers_table_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_ANSWERS + "(" +
                COl_ANSWERS_ID + " INTEGER PRIMARY KEY," +
                COL_ANSWERS_QUESTIONID + " INTEGER," +
                COl_ANSWERS_ANSWER + " TEXT," +
                COL_ANSWERS_CORINC + " TEXT" +
                ")";
        db.execSQL(crt_questions_table_sql);
        db.execSQL(crt_answers_table_sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long addQuestion(String question) {
        ContentValues cv = new ContentValues();
        cv.put(COl_QUESTIONS_QUESTION,question);
        return database.insert(TABLE_QUESTIONS,null,cv);
    }

    public long addAnswer(long questionid, String answer, String corinc) {
        ContentValues cv = new ContentValues();
        cv.put(COL_ANSWERS_QUESTIONID,questionid);
        cv.put(COl_ANSWERS_ANSWER,answer);
        cv.put(COL_ANSWERS_CORINC,corinc);
        return database.insert(TABLE_ANSWERS,null,cv);
    }

    public void addQuestionWithAnswers(String question, List<Answers> answerlist) {
        boolean intransaction = false;
        if (!database.inTransaction()) {
            database.beginTransaction();
        } else {
            intransaction = true;
        }
        long questionid = addQuestion(question);
        if (questionid > 0) {
            for (Answers a : answerlist) {
                addAnswer(questionid, a.getAnswer(), a.getCorinc());
            }
            if (!intransaction) {
                database.setTransactionSuccessful();
            }
        }
        if (!intransaction) {
            database.endTransaction();
        }
    }

    public Cursor getAnswersAsCursor(long idquestion) {
        String whereclause = COL_ANSWERS_QUESTIONID + "=?";
        String[] whereargs = new String[]{String.valueOf(idquestion)};
        return database.query(TABLE_ANSWERS,null,whereclause,whereargs,null,null,null);
    }

    public List<Answers> getAnswers(int Idquestion) {
        Answers a = null;
        List<Answers> list = new ArrayList<>();
        openDatabase();
        Cursor cursor = database.rawQuery("SELECT * FROM ANSWERS " +
                        "WHERE Idquestion = ?",
                new String[]{String.valueOf(Idquestion)}
        );

        cursor.moveToNext();
        while (!cursor.isAfterLast()) {

            a = new Answers(
                    cursor.getInt(0),
                    cursor.getInt(1),
                    cursor.getString(2),
                    cursor.getString(3));
            list.add(a);
            cursor.moveToNext();
        }
        cursor.close(); //<<<<<<<<<<<< IMPORTANT
        return list;
    }

    public List<Questions> getQuestions() {
        List<Questions> list = new ArrayList<>();
        Cursor csr = database.query(TABLE_QUESTIONS,null,null,null,null,null,null);
        while (csr.moveToNext()) {
            list.add(
                    new Questions(
                            csr.getLong(csr.getColumnIndex(COL_QUESTIONS_ID)),
                            csr.getString(csr.getColumnIndex(COl_QUESTIONS_QUESTION))
                    )
            );
        }
        csr.close();
        return list;
    }
}
  • 您可能希望注意并考虑以下一些问题(getAnswers与getQuestions方法之间的差异),例如:-

    • 使用了SQLiteDatabase query 方法,这是对 rawQuery 方法的建议。
    • Cursor处理循环使用更简单的while(the_cursor.moveToNext() { ....... },而不是在循环之前添加moveToNext()。
    • 硬编码的偏移量被替换为根据列名提取偏移量,这消除了计算偏移量的需要,并且更加灵活(例如,是否更改了数据库模式以在最后一列之前添加一列(在对硬编码的偏移量进行编码后,将需要对整个应用程序中的某些偏移量进行重新编码,而在使用从列名得出的偏移量时不需要进行此类更改))。
    • 尽管对于小型数据库而言并不重要,但实际上id应该是 long ,而不是 int ,因为id可以是64位有符号整数值。
    • 完成操作后应关闭光标(请注意,这已添加到您的 getAnswers 方法中)
    • 位于其下方的光标是一个文件,并且一次可以使用的文件描述符的数量受到限制(我认为是1024),关闭光标会释放文件描述符,因此使用该数字的可能性较小将会超出该值,从而导致异常(开放代码14),有关问题将在https://nodejs.org/de/docs/guides/event-loop-timers-and-nexttick/中给出答案。

Questions.java 是:-

public class Questions {

    private long id;
    private String question;

    public Questions(long id, String question) {
        this.id = id;
        this.question = question;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }
}

Answers.java 是:-

public class Answers {

    public static final String CORRECTANSWER = "true";
    public static final String INCORRECTANSWER = "false";
    private int id; //<<<<<<<<<< should really be long
    private int questionid;
    private String answer;
    private String corinc;

    public Answers(int id,  int questionid, String answer, int corinc) {
        this.id = id;
        this.answer = answer;
        this.questionid = questionid;
        if (corinc > 0) {
            this.corinc = Boolean.toString(true);
        } else {
            this.corinc = Boolean.toString(false);
        }
    }

    public Answers(int id, int questionid, String answer, String corinc) {
        this.id = id;
        this.questionid = questionid;
        this.answer = answer;
        this.corinc = corinc;
    }

    public Answers(int questionid, String answer, String corinc) {
        this(-1,questionid,answer,corinc);
    }

    public Answers(String answer, String corinc) {
        this(-1,-1,answer,corinc);
    }

    public Answers() {
        this(-1,-1,"",0);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getQuestionid() {
        return questionid;
    }

    public void setQuestionid(int questionid) {
        this.questionid = questionid;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getCorinc() {
        return corinc;
    }

    public void setCorinc(String corinc) {
        this.corinc = corinc;
    }
}

activity_main.xml 是:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NEXT"/>

    <TextView
        android:id="@+id/question"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/answerlist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

simple_list_item_1 是一种库存(提供)布局,为方便起见再次使用。

该应用程序看起来像:-

第一个问题(开始时):-

here

单击下一步后:-

enter image description here

....直到隐藏按钮时最后一个问题(第15次单击,因为有15个问题):-

enter image description here