如何检索按钮数据,并移动到下一个按钮?按钮、数据

2023-09-07 03:08:35 作者:浅夏~夜未眠

我工作的一个Android测验。我创建了我的数据库,一个问题和沿四个选项的难度级别。我创建了一个布局,四个按钮显示的问题。现在的问题是我如何将问题和四个按钮连接我的数据库。

,以便,当我点击右边的按钮移动到下一个问题,当我点击错了按钮它给出了一个错误,然后退出。

code。在XML

 <?XML版本=1.0编码=UTF-8&GT?;< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android机器人:方向=垂直的android:layout_width =FILL_PARENT机器人:layout_height =FILL_PARENT机器人:比重=CENTER_HORIZONTAL机器人:背景=@绘制/背景><的LinearLayout机器人:方向=横向      机器人:layout_width =WRAP_CONTENT    机器人:layout_height =110dp    机器人:paddingTop =5dip的android:paddingBottom会=5dip    机器人:重力=CENTER_HORIZONTAL>    < ImageView的        机器人:ID =@ + ID /标志        机器人:layout_width =WRAP_CONTENT        机器人:layout_height =WRAP_CONTENT        机器人:paddingBottom会=1dip        机器人:paddingTop =1dip        机器人:SRC =@绘制/ LOGO2/>< / LinearLayout中><的LinearLayout机器人:方向=横向    机器人:layout_width =FILL_PARENT机器人:layout_height =WRAP_CONTENT    机器人:paddingTop =5dip的android:paddingBottom会=5dip    机器人:重力=CENTER_HORIZONTAL>    < RadioGroup中的android:layout_width =FILL_PARENT        机器人:layout_height =WRAP_CONTENT机器人:方向=垂直        机器人:背景=#99CCFF        机器人:ID =@ + ID /组1>        <的TextView的android:layout_width =FILL_PARENT            机器人:layout_height =WRAP_CONTENT            机器人:背景=#0000CC            机器人:文字样式=大胆的机器人:ID =@ + ID /问题/>        <按钮安卓的onClick =false的机器人:ID =@ + ID / ANSWER1            机器人:layout_width =150dip/>        <按钮安卓的onClick =false的机器人:ID =@ + ID / ANSWER2            机器人:layout_width =150dip/>        <按钮安卓的onClick =false的机器人:ID =@ + ID / ANSWER3            机器人:layout_width =150dip/>        <按钮安卓的onClick =false的机器人:ID =@ + ID / answer4            机器人:layout_width =150dip/>    < / RadioGroup中>< / LinearLayout中> 

MY DBHelper.java

 公共类DBHelper扩展SQLiteOpenHelper {//你的应用程序数据库的Andr​​oid的默认系统路径。私人静态字符串DB_PATH =/data/data/com.starchazer.cyk/databases/;私人静态字符串DB_NAME =questionsDb;私人SQLiteDatabase MYDATABASE;私人最终上下文myContext;/ ** *构造 *注意到并保持以访问该应用程序的资产和资源所传递的上下文的引用。 * @参数方面 * /公共DBHelper(上下文的背景下){    超级(上下文,DB_NAME,空,1);    this.myContext =背景;}/ ** *在系统上创建一个空数据库,并与自己的数据库重写它。 * * /公共无效的CreateDatabase()抛出IOException    布尔dbExist = checkDataBase();    如果(!dbExist)    {        //通过调用此方法与空的数据库将被创建到默认的系统路径        //你的应用程序,所以我们要能够覆盖该数据库与我们的数据库。        this.getReadableDatabase();        尝试{            copyDataBase();        }赶上(IOException异常五){            抛出新的错误(错误复制数据库);        }    }}/ ** *检查是否已存在于数据库,以避免重新复制每次打开应用程序时的文件。 *如果存在返回:真的,假的,如果它不 * /私人布尔checkDataBase(){    SQLiteDatabase CHECKDB = NULL;    尝试{        字符串mypath中= DB_PATH + DB_NAME;        CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);    }赶上(SQLiteException E){        //数据库开不存在。    }    如果(CHECKDB!= NULL){        checkDB.close();    }    返回CHECKDB!= NULL?真假;}/ ** *副本数据库从本地资产文件夹在刚才创建的空数据库 *系统文件夹,从那里可以访问和处理。 *这是通过转流的字节流进行。 * * /私人无效copyDataBase()抛出IOException    //打开本地数据库的输入流    InputStream的myInput = myContext.getAssets()开(DB_NAME)。    //路径刚刚创建的空分贝    字符串outFileName = DB_PATH + DB_NAME;    //打开空分贝的输出流    的OutputStream myOutput =新的FileOutputStream(outFileName);    //传递从inputfile中字节到OUTPUTFILE    字节[]缓冲区=新的字节[1024];    INT长;    而((长度= myInput.read(缓冲液))大于0){        myOutput.write(缓冲液,0,长度);    }    //关闭流    myOutput.flush();    myOutput.close();    myInput.close();}公共无效的openDatabase()抛出的SQLException {    //打开数据库    字符串mypath中= DB_PATH + DB_NAME;    MYDATABASE = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);}@覆盖公共同步无效的close(){    如果(MYDATABASE!= NULL)        myDataBase.close();    super.close();}@覆盖公共无效的onCreate(SQLiteDatabase DB){}@覆盖公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){}//添加您的公开辅助方法访问并从数据库中获取的内容。//你可以做返回游标返回myDataBase.query(....),因此这将会是很容易//你创建你的意见适配器。公开名单<问题> getQuestionSet(INT困难,诠释numQ){    清单<问题> questionSet =新的ArrayList<问题>();    光标C = myDataBase.rawQuery(SELECT * FROM WHERE质询难度=+ +困难            ORDER BY RANDOM()LIMIT+ numQ,NULL);    而(c.moveToNext()){        //Log.d(\"QUESTION,问题DB中找到:+ c.getString(1));        问Q =新问题();        q.setQuestion(c.getString(1));        q.setAnswer(c.getString(2));        q.setOption1(c.getString(3));        q.setOption2(c.getString(4));        q.setOption3(c.getString(5));        q.setRating(困难);        questionSet.add(Q);    }    返回questionSet;}} 

MY QuestionActivity

 公共类QuestionActivity扩展活动实现OnClickListener {私人问题currentQ;私人游戏currentGame;@覆盖公共无效的onCreate(捆绑savedInstanceState){    super.onCreate(savedInstanceState);    的setContentView(R.layout.question);    / **     *配置当前游戏并获得问题     * /    currentGame =((XYZ_Application)getApplication())getCurrentGame();    currentQ = currentGame.getNextQuestion();    按钮C1 =(按钮)findViewById(R.id.answer1);    c1.setOnClickListener(本);    按钮C2 =(按钮)findViewById(R.id.answer2);    c2.setOnClickListener(本);    按钮C3 =(按钮)findViewById(R.id.answer3);    c3.setOnClickListener(本);    按钮C4 =(按钮)findViewById(R.id.answer4);    c4.setOnClickListener(本);    / **     *更新的问题和答案选项..     * /    setQuestions();}/ ** *方法来设置从目前游戏的问题和答案的文字 *当前问题 * /私人无效setQuestions(){    //设置与当前讨论的问题文本    字符串的问题= Utility.capitalise(currentQ.getQuestion())+?;    TextView的QTEXT =(的TextView)findViewById(R.id.question);    qText.setText(问题);    //设置可用的选项    清单<串GT;答案= currentQ.getQuestionOptions();    TextView的选项1 =(的TextView)findViewById(R.id.answer1);    option1.setText(Utility.capitalise(answers.get(0)));    TextView的选项2 =(的TextView)findViewById(R.id.answer2);    option2.setText(Utility.capitalise(answers.get(1)));    TextView的选项3 =(的TextView)findViewById(R.id.answer3);    option3.setText(Utility.capitalise(answers.get(2)));    TextView的选项4 =(的TextView)findViewById(R.id.answer4);    option4.setText(Utility.capitalise(answers.get(3)));}@覆盖公共无效的onClick(查看为arg0){    / **     *验证buttonselected已被选择     * /    如果回报(checkAnswer()!);    / **     *检查,如果比赛结束     * /    如果(currentGame.isGameOver()){        意图I =新意图(这一点,Main.class);        startActivity(ⅰ);        完();    }    其他{        意图I =新意图(这一点,QuestionActivity.class);        startActivity(ⅰ);        完();    }}@覆盖公共布尔的onkeydown(INT键code,KeyEvent的事件){    开关(键code)    {    案例KeyEvent.KEY code_BACK:        返回true;    }    返回super.onKeyDown(键code,事件);}/ ** *检查复选框已被选中,并且如果它 *已经然后检查其正确和更新gamescore * /私人布尔checkAnswer(){    字符串的答案= getSelectedAnswer();    如果(回答== NULL){        返回false;    }    其他{        如果(currentQ.getAnswer()。equalsIgnoreCase(回答))        {            //Log.d(\"Questions,正确答案)!;            currentGame.incrementRightAnswers();        }        其他{            //Log.d(\"Questions,不正确的答案)!;            currentGame.incrementWrongAnswers();        }        返回true;    }}/ ** * * /私人字符串getSelectedAnswer(){    按钮C1 =(按钮)findViewById(R.id.answer1);    按钮C2 =(按钮)findViewById(R.id.answer2);    按钮C3 =(按钮)findViewById(R.id.answer3);    按钮C4 =(按钮)findViewById(R.id.answer4);    如果(c1.callOnClick())    {        返回c1.getText()的toString()。    }    如果(c2.callOnClick())    {        返回c2.getText()的toString()。    }    如果(c3.callOnClick())    {        返回c3.getText()的toString()。    }    如果(c4.callOnClick())    {        返回c4.getText()的toString()。    }    返回null;}} 
用欧姆龙PLC控制器编程,三个点动按钮控制一个灯,随便按下按钮都能控制灯的亮与熄,

解决方案

我很抱歉,我不会在这里给code。

下面是我会做当Actvity启动

从分贝负载问题与选项我会preFER选项,阵列/ ArrayList的分配文本选项给每个按钮

添加一个普通的onclick听众如这

 公共无效的onClick(视图v){INT ID = v.getId();字符串的答案= v.getText();如果(answer.equals('回答DB'){//如果正确的话下一个问题//别的MainActivity    }/ **开关(ID){    案例R.id.answer1:         processAnswer(1);         打破;    案例R.id.answer2:         processAnswer(2);         打破;    //所以在    } ** /} 

和processAnswer看起来像

 无效processAnswer(INT选项){//由于我这里的选项//我将与数据库检查//如果正确,那么接下来的问题别人退出} 

I am working on an Android quiz . I have created my database with one question and four options along-with difficulty level. I have created a layout to display the question with four buttons . Now the problem is how will i connect my database with the question and four buttons.

so as to, when I click on right button it moves to the next question and when I click on wrong button it gives an error and exits.

Code In XML

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center_horizontal"
android:background="@drawable/background">

<LinearLayout android:orientation="horizontal"
      android:layout_width="wrap_content"
    android:layout_height="110dp" 
    android:paddingTop="5dip" android:paddingBottom="5dip"
    android:gravity="center_horizontal">

    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="1dip"
        android:paddingTop="1dip"
        android:src="@drawable/logo2" />

</LinearLayout>

<LinearLayout android:orientation="horizontal"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:paddingTop="5dip" android:paddingBottom="5dip"
    android:gravity="center_horizontal">

    <RadioGroup android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="vertical"
        android:background="#99CCFF"
        android:id="@+id/group1">

        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"        
            android:background="#0000CC"
            android:textStyle="bold" android:id="@+id/question"/>

        <Button android:onClick="false" android:id="@+id/answer1"
            android:layout_width="150dip" />

        <Button android:onClick="false" android:id="@+id/answer2"
            android:layout_width="150dip" />    
        <Button android:onClick="false" android:id="@+id/answer3" 
            android:layout_width="150dip"/> 
        <Button android:onClick="false" android:id="@+id/answer4"
            android:layout_width="150dip" />    
    </RadioGroup>
</LinearLayout>

MY DBHelper.java

public class DBHelper extends SQLiteOpenHelper{

//The Android's default system path of your application database.

private static String DB_PATH = "/data/data/com.starchazer.cyk/databases/";
private static String DB_NAME = "questionsDb";
private SQLiteDatabase myDataBase; 
private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public DBHelper(Context context) {
    super(context, DB_NAME, null, 1);
    this.myContext = context;
}   

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * */
public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();
    if(!dbExist)
    {
        //By calling this method and empty database will be created into the default system path
        //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {
            copyDataBase(); 
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase(){
    SQLiteDatabase checkDB = null;
    try{
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }catch(SQLiteException e){
        //database does't exist yet.
    }
    if(checkDB != null){
        checkDB.close();
    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException{
    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {
    if(myDataBase != null)
        myDataBase.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {
}

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

// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.




public List<Question> getQuestionSet(int difficulty, int numQ){
    List<Question> questionSet = new ArrayList<Question>();
    Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty +
            " ORDER BY RANDOM() LIMIT " + numQ, null);
    while (c.moveToNext()){
        //Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
        Question q = new Question();
        q.setQuestion(c.getString(1));
        q.setAnswer(c.getString(2));
        q.setOption1(c.getString(3));
        q.setOption2(c.getString(4));
        q.setOption3(c.getString(5));
        q.setRating(difficulty);
        questionSet.add(q);
    }
    return questionSet;
}
}

MY QuestionActivity

public class QuestionActivity extends Activity implements OnClickListener{

private Question currentQ;
private GamePlay currentGame;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.question);
    /**
     * Configure current game and get question
     */



    currentGame = ((XYZ_Application)getApplication()).getCurrentGame();
    currentQ = currentGame.getNextQuestion();
    Button c1 = (Button) findViewById(R.id.answer1 );
    c1.setOnClickListener(this);
    Button c2 = (Button) findViewById(R.id.answer2 );
    c2.setOnClickListener(this);
    Button c3 = (Button) findViewById(R.id.answer3 );
    c3.setOnClickListener(this);
    Button c4 = (Button) findViewById(R.id.answer4 );
    c4.setOnClickListener(this);

    /**
     * Update the question and answer options..
     */
    setQuestions();

}


/**
 * Method to set the text for the question and answers from the current games
 * current question
 */
private void setQuestions() {
    //set the question text from current question
    String question = Utility.capitalise(currentQ.getQuestion()) + "?";
    TextView qText = (TextView) findViewById(R.id.question);
    qText.setText(question);

    //set the available options
    List<String> answers = currentQ.getQuestionOptions();
    TextView option1 = (TextView) findViewById(R.id.answer1);
    option1.setText(Utility.capitalise(answers.get(0)));

    TextView option2 = (TextView) findViewById(R.id.answer2);
    option2.setText(Utility.capitalise(answers.get(1)));

    TextView option3 = (TextView) findViewById(R.id.answer3);
    option3.setText(Utility.capitalise(answers.get(2)));

    TextView option4 = (TextView) findViewById(R.id.answer4);
    option4.setText(Utility.capitalise(answers.get(3)));
}


@Override
public void onClick(View arg0) {


    /**
     * validate a buttonselected has been selected
     */    
    if (!checkAnswer()) return;


    /**
     * check if end of game
     */
    if (currentGame.isGameOver()){


        Intent i = new Intent(this, Main.class);
        startActivity(i);
        finish();
    }
    else{
        Intent i = new Intent(this, QuestionActivity.class);
        startActivity(i);
        finish();
    }
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    switch (keyCode)
    {
    case KeyEvent.KEYCODE_BACK :
        return true;
    }

    return super.onKeyDown(keyCode, event);
}


/**
 * Check if a checkbox has been selected, and if it
 * has then check if its correct and update gamescore
 */
private boolean checkAnswer() {
    String answer = getSelectedAnswer();
    if (answer==null){

        return false;
    }
    else {

        if (currentQ.getAnswer().equalsIgnoreCase(answer))
        {
            //Log.d("Questions", "Correct Answer!");
            currentGame.incrementRightAnswers();
        }
        else{
            //Log.d("Questions", "Incorrect Answer!");
            currentGame.incrementWrongAnswers();
        }
        return true;
    }
}


/**
 * 
 */
private String getSelectedAnswer() {
    Button c1 = (Button)findViewById(R.id.answer1);
    Button c2 = (Button)findViewById(R.id.answer2);
    Button c3 = (Button)findViewById(R.id.answer3);
    Button c4 = (Button)findViewById(R.id.answer4);
    if (c1.callOnClick())
    {
        return c1.getText().toString();
    }
    if (c2.callOnClick())
    {
        return c2.getText().toString();
    }
    if (c3.callOnClick())
    {
        return c3.getText().toString();
    }
    if (c4.callOnClick())
    {
        return c4.getText().toString();
    }

    return null;
}


}

解决方案

I am sorry I will not be giving code here.

Here is what I would have done When Actvity Starts

Load Question from Db with Options I ll prefer option as array/arraylist Assign Text Option to each button

Add a common onclick listener like this

public void onClick(View v){
int id=v.getId();
String answer=v.getText();
if(answer.equals('ANSWER FROM DB'){
// If right then next question
// Else to MainActivity
    }

/**switch(id){
    case R.id.answer1:
         processAnswer(1);

         break;
    case R.id.answer2:
         processAnswer(2);
         break;
    // So on
    }
 **/
}

And processAnswer would look like

void processAnswer(int option){
// Since I have the option here
// I will check it with Database
// If its correct then next question else exit
}