从DbHelper得到一个随机字符串爪哇 [英] Get A random String from DbHelper on Java

查看:172
本文介绍了从DbHelper得到一个随机字符串爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在Android上的问答游戏,我试图随机化问答题命令,这样我就不会每次我启动它的时间得到同样的问题,以相同的顺序,这里是我的DBhelper。 java的:

I'm currently working on a quiz game on android and I am trying to randomize the quiz questions' order, so that I do not get the same questions in the same order every time I launch it, here is my DBhelper.java :

package com.total.eureka;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class DbHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "triviaQuiz";
    // tasks table name
    private static final String TABLE_QUEST = "quest";
    // tasks Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_QUES = "question";
    private static final String KEY_ANSWER = "answer"; //correct option
    private static final String KEY_OPTA= "opta"; //option a
    private static final String KEY_OPTB= "optb"; //option b
    private static final String KEY_OPTC= "optc"; //option c
    private SQLiteDatabase dbase;
    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        dbase=db;
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
                + " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
                +KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT)";
        db.execSQL(sql);        
        addQuestions();
        //db.close();
    }
    private void addQuestions()
    {
        Question q1=new Question("Which company is the largest manufacturer" +
                " of network equipment?","HP", "IBM", "CISCO", "CISCO");
        this.addQuestion(q1);
        Question q2=new Question("Which of the following is NOT " +
                "an operating system?", "SuSe", "BIOS", "DOS", "BIOS");
        this.addQuestion(q2);
        Question q3=new Question("Which of the following is the fastest" +
                " writable memory?","RAM", "FLASH","Register","Register");
        this.addQuestion(q3);
        Question q4=new Question("Which of the following device" +
                " regulates internet traffic?", "Router", "Bridge", "Hub","Router");
        this.addQuestion(q4);
        Question q5=new Question("Which of the following is NOT an" +
                " interpreted language?","Ruby","Python","BASIC","BASIC");
        this.addQuestion(q5);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
        // Create tables again
        onCreate(db);
    }
    // Adding new question
    public void addQuestion(Question quest) {
        //SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_QUES, quest.getQUESTION()); 
        values.put(KEY_ANSWER, quest.getANSWER());
        values.put(KEY_OPTA, quest.getOPTA());
        values.put(KEY_OPTB, quest.getOPTB());
        values.put(KEY_OPTC, quest.getOPTC());
        // Inserting Row
        dbase.insert(TABLE_QUEST, null, values);        
    }
    public List<Question> getAllQuestions() {
        List<Question> quesList = new ArrayList<Question>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        dbase=this.getReadableDatabase();
        Cursor cursor = dbase.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Question quest = new Question();
                quest.setID(cursor.getInt(0));
                quest.setQUESTION(cursor.getString(1));
                quest.setANSWER(cursor.getString(2));
                quest.setOPTA(cursor.getString(3));
                quest.setOPTB(cursor.getString(4));
                quest.setOPTC(cursor.getString(5));
                quesList.add(quest);
            } while (cursor.moveToNext());
        }
        // return quest list
        return quesList;
    }

    public int rowcount()
    {
        int row=0;
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery,null);
        row=cursor.getCount();
        return row;
    }
}

这是启动竞猜,活动QuizActivity.java:

And here is the activity that launches the quiz, QuizActivity.java :

package com.total.eureka;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.List;

public class QuizActivity extends Activity {
    List<Question> quesList;
    int score=0;
    int qid=0;
    Question currentQ;
    TextView txtQuestion;
    RadioButton rda, rdb, rdc;
    Button butNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        DbHelper db=new DbHelper(this);
        quesList=db.getAllQuestions();
        currentQ=quesList.get(qid);
        txtQuestion=(TextView)findViewById(R.id.textView1);
        rda=(RadioButton)findViewById(R.id.radio0);
        rdb=(RadioButton)findViewById(R.id.radio1);
        rdc=(RadioButton)findViewById(R.id.radio2);
        butNext=(Button)findViewById(R.id.button1);
        setQuestionView();
        butNext.setOnClickListener(new View.OnClickListener() {     
            @Override
            public void onClick(View v) {
                RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
                RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
                Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
                if(currentQ.getANSWER().equals(answer.getText()))
                {
                    score++;
                    Log.d("score", "Your score"+score);
                }
                if(qid<5){                  
                    currentQ=quesList.get(qid);
                    setQuestionView();
                }else{
                    Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
                    Bundle b = new Bundle();
                    b.putInt("score", score); //Your score
                    intent.putExtras(b); //Put your score to your next Intent
                    startActivity(intent);
                    finish();
                }
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_quiz, menu);
        return true;
    }
    private void setQuestionView()
    {
        txtQuestion.setText(currentQ.getQUESTION());
        rda.setText(currentQ.getOPTA());
        rdb.setText(currentQ.getOPTB());
        rdc.setText(currentQ.getOPTC());
        qid++;
    }
}

这是我应该怎么做的任何想法?
P.S:我几乎一noob,所以即插即用code段将是非常欢迎的。先谢谢了。

Any ideas on how I should do it? P.S: I'm almost a noob, so a "plug and play" code snippet would be very welcome. Thanks in advance.

推荐答案

而不是0开始递增的(加1):

Instead of starting with zero and incrementing (adding 1):

int qid = 0; // Index in quesList.
...
++qid;

一个人需要随机挑选的问题,并确保它是不是已经问。
删除QID。

one needs to randomly pick a question and ensure it is not asked already. Delete qid.

让我们来解决重复的prevention如下:

Let's solve the prevention of repetitions as follows:


  • 在年初,我们可以从所有的问题挑

  • 在问一个问题,我们将其放置在背面,由1
  • decremnt可用的问题
  • 如果0可用的问题达成协议,重新所有问题变得可用

  • At the beginning we can pick from all questions
  • On asking a question we place it at the back, and decremnt the available questions by 1
  • If 0 available questions reached, again all questions become available

所以:

int availableQuestions; // Questions 0 till (askable - 1) can be asked
Random random = new Random();

通常情况下人们所期望的:

Normally one would expect at:

quesList = db.getAllQuestions();

设置availableQuestions,但0都是再次可用,我们并不需要:

to set the availableQuestions, but as on 0 all are available again, we do not need:

//availableQuestions = quesList.size();

不过既然选择了每一个问题后可能会停止。

However you might stop after having chosen every question.

而不是:

currentQ = quesList.get(qid); // Occures twice

DO

currentQ = pickQuestion();

private Question pickQuestion() {
    if (availableQuestions == 0) { // Takes care of initialisation too.
        availableQuestions = quesList.size();
    }
    int qid = random.nextInt(availableQuestions);
    Question q = quesList.get(qid);

    // Switch question with the last one, and have one less available:
    --availableQuestions;
    quesList.put(qid, quesList.get(availableQuestions));
    quesList.put(availableQuestions, q);
    return q;
}

这篇关于从DbHelper得到一个随机字符串爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆