Android Quiz App,后退和下一个按钮问题

时间:2017-05-25 09:34:47

标签: java android

我正在开发一个测验应用程序,我正面临着后退和下一个按钮的问题。情况如下:

  1. 我总共有40个问题,在测验的java类中我初始化一个整数rowID = 1

  2. w ^ 我正处于按钮被禁用的第一个位置,但当我按下一个按钮时它仍处于禁用状态,下一个按钮也是如此

  3. 我有一个TextView,显示当前问题的数量,如果我在问题编号40,然后再次按下,那就是41.它不应该
  4. 这是我的代码:

       import android.app.AlertDialog;
       import android.app.Dialog;
       import android.content.ContentValues;
       import android.database.Cursor;
       import android.database.sqlite.SQLiteDatabase;
       import android.graphics.drawable.ColorDrawable;
       import android.net.Uri;
       import android.os.Bundle;
       import android.os.CountDownTimer;
       import android.support.design.widget.FloatingActionButton;
       import android.support.v7.app.AppCompatActivity;
       import android.support.v7.widget.Toolbar;
       import android.text.Html;
       import android.view.MenuItem;
       import android.view.View;
       import android.widget.Button;
       import android.widget.RadioGroup;
       import android.widget.TextView;
       import android.widget.Toast;
    
       import com.afollestad.materialdialogs.MaterialDialog;
       import com.google.gson.Gson;
       import com.google.gson.GsonBuilder;
       import com.shawnlin.numberpicker.NumberPicker;
    
       import org.json.JSONObject;
    
       import java.util.List;
       import java.util.concurrent.TimeUnit;
    
       import retrofit2.Call;
       import retrofit2.Callback;
    
       import static autoshkolla.almotech.org.autoshkollastudenti.R.id.testi;
    
       public class Activity_Quiz extends AppCompatActivity {
           SaveData saveData;
           String ApiKey;
           Dialog dialog;
           Gson gson;
           Button next_question, previous_question;
           int quizID, questionID, trueanswer, useranswer;
           int rowID = 1;
           String question, filename, mime, image;
           SQLiteDatabase db;
           TextView viewquestion, question_number, user_email, user_id, quiz_number;
           QuizAdapter quizAdapter;
           private AllLectureAdapter adapter;
           DbProductModel dbProductModel;
           List < Quiz_Data > lecture;
           RadioGroup my_answer;
    
           NumberPicker numberPicker;
           Button start_timer, stop_timer;
           MyCountDownTimer myCountDownTimer;
           TextView koha;
    
           @Override
           protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity__quiz);
               Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
               setSupportActionBar(toolbar);
    
               getSupportActionBar().setDisplayHomeAsUpEnabled(true);
               getSupportActionBar().setHomeButtonEnabled(false);
               getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'><b>QUIZ</b></font>"));
               saveData = new SaveData(getApplication());
               gson = new GsonBuilder().create();
               ApiKey = "bearer " + saveData.getAutoUserToken();
    
               if (!saveData.getQuizStatus().equalsIgnoreCase("start")) {
                   myCountDownTimer = new MyCountDownTimer(2400000, 1000);
                   myCountDownTimer.start();
                   loading();
                   generate_quiz(ApiKey);
                   saveData.setQuizStatus("in_progress");
    
               }
    
               question_number = (TextView) findViewById(R.id.questionnumber);
               user_email = (TextView) findViewById(R.id.email);
               user_id = (TextView) findViewById(R.id.ID);
               quiz_number = (TextView) findViewById(testi);
               user_email.setText("Email : " + saveData.getAutoUserEmail());
               user_id.setText("ID : " + saveData.getAutoUserId() + "");
    
               next_question = (Button) findViewById(R.id.nextbtn);
               previous_question = (Button) findViewById(R.id.prevbtn);
               viewquestion = (TextView) findViewById(R.id.question);
               my_answer = (RadioGroup) findViewById(R.id.useranswer);
               final QuizSendModel results = new QuizSendModel();
    
               koha = (TextView) findViewById(R.id.time);
    
               if (rowID > 1 && rowID < 40) {
                   previous_question.setEnabled(true);
                   next_question.setEnabled(true);
               } else if (rowID == 40) {
                   next_question.setEnabled(false);
               } else if (rowID == 1) {
                   previous_question.setEnabled(false);
               }
    
    
               FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.gotoquestion);
               fab.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
    
                       final Dialog dialog = new Dialog(Activity_Quiz.this);
                       dialog.setContentView(R.layout.questions);
                       dialog.setCancelable(true);
                       dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
                       Button shiko = (Button) dialog.findViewById(R.id.shikopyetje);
                       numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
    
                       dialog.show();
    
                       /* Window window = dialog.getWindow();
                        window.setLayout(400, 600);*/
    
                       shiko.setOnClickListener(new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {
    
                               question_number.setText(String.valueOf(numberPicker.getValue()) + "/40");
                               String[] proj = {
                                   UsersProvider.QUESTION,
                                   UsersProvider.USER_ANSWER
                               };
                               String[] args = {
                                   String.valueOf(numberPicker.getValue())
                               };
                               Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
                               if (c.moveToFirst()) {
                                   do {
    
                                       viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
                                       String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
    
                                       if (uswanswradio == null) {
                                           my_answer.clearCheck();
                                       } else if (uswanswradio.equalsIgnoreCase("0")) {
                                           my_answer.check(R.id.radioJO);
                                       } else if (uswanswradio.equalsIgnoreCase("1")) {
                                           my_answer.check(R.id.radioPO);
                                       }
                                   } while (c.moveToNext());
                               }
                               dialog.dismiss();
                           }
                       });
                   }
               });
    
               viewquestion.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, null, null, null, null);
                       if (c.moveToFirst()) {
                           do {
                               /*Toast.makeText(getApplicationContext()," "+c.getString(c.getColumnIndex(UsersProvider.NAME))+", "+c.getString(c.getColumnIndex(UsersProvider.ADDRESS)),Toast.LENGTH_LONG).show();
                               System.out.println("emri : "+c.getString(c.getColumnIndex(UsersProvider.NAME))+" address : "+c.getString(c.getColumnIndex(UsersProvider.ADDRESS)));*/
                               results.setId_question(c.getString(c.getColumnIndex(UsersProvider.ID_QUESTION)));
                               results.setUser_answer(c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER)));
                               System.out.println("pyetja : " + results.getId_question());
                               System.out.println("uans : " + results.getUser_answer());
                           } while (c.moveToNext());
                       }
                   }
               });
    
               my_answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    
                   public void onCheckedChanged(RadioGroup group,
                       int checkedId) {
                       if (checkedId == R.id.radioPO) {
                           useranswer = 1;
                       } else if (checkedId == R.id.radioJO) {
                           useranswer = 0;
                       }
                       ContentValues values = new ContentValues();
                       values.put(UsersProvider.USER_ANSWER, useranswer);
                       String row = String.valueOf(rowID);
                       String[] whereArgs = {
                           row
                       };
                       getContentResolver().update(UsersProvider.CONTENT_URI, values, UsersProvider.ID_ROW + " =? ", whereArgs);
                   }
               });
    
               previous_question.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       rowID = rowID - 1;
    
                       question_number.setText(rowID + "/40");
                       String[] proj = {
                           UsersProvider.QUESTION,
                           UsersProvider.USER_ANSWER
                       };
                       String[] args = {
                           String.valueOf(rowID)
                       };
                       Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
                       if (c.moveToFirst()) {
                           do {
    
                               viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
    
                               String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
                               System.out.println("pergjigjeeuserit : " + c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER)));
                               if (uswanswradio == null) {
                                   my_answer.clearCheck();
                               } else if (uswanswradio.equalsIgnoreCase("0")) {
                                   my_answer.check(R.id.radioJO);
                               } else if (uswanswradio.equalsIgnoreCase("1")) {
                                   my_answer.check(R.id.radioPO);
                               }
                           } while (c.moveToNext());
                       }
                   }
               });
    
               next_question.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
    
                       my_answer.clearCheck();
                       rowID = rowID + 1;
    
                       question_number.setText(rowID + "/40");
                       String[] proj = {
                           UsersProvider.QUESTION,
                           UsersProvider.USER_ANSWER
                       };
                       String[] args = {
                           String.valueOf(rowID)
                       };
                       Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
                       if (c.moveToFirst()) {
                           do {
    
                               viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
                               String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
                               if (uswanswradio == null) {
                                   my_answer.clearCheck();
                               } else if (uswanswradio.equalsIgnoreCase("0")) {
                                   my_answer.check(R.id.radioJO);
                               } else if (uswanswradio.equalsIgnoreCase("1")) {
                                   my_answer.check(R.id.radioPO);
                               }
                           } while (c.moveToNext());
                       }
    
                   }
               });
    
               String[] proj = {
                   UsersProvider.QUESTION
               };
               String[] args = {
                   String.valueOf(1)
               };
               Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
               if (c.moveToFirst()) {
                   do {
                       rowID = 1;
    
                       viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
                   } while (c.moveToNext());
               }
           }
    
           public void generate_quiz(String APIKEY) {
               API api = APIClient.getApi(APIKEY);
               Call < Quiz > totclient = api.quiz();
               totclient.enqueue(new Callback < Quiz > () {
                   @Override
                   public void onResponse(Call < Quiz > call, retrofit2.Response < Quiz > response) {
                       dialog.dismiss();
                       // Log.d(TAG, "Succes:" + response.body().isError());
                       JSONObject obj = new JSONObject();
                       System.out.println("AllLectures:" + gson.toJson(response.body()));
                       System.out.println("quiz id:" + gson.toJson(response.body().getQuizNumber()));
                       quiz_number.setText("Testi : " + gson.toJson(response.body().getQuizNumber()));
                       if (!gson.toJson(response.body()).equalsIgnoreCase("null")) {
                           if (gson.toJson(response.body().getError()).equalsIgnoreCase("false")) {
                               ContentValues values = new ContentValues();
                               getContentResolver().delete(UsersProvider.CONTENT_URI, null, null);
                               lecture = response.body().getData();
    
                               final List < Quiz_Data > movies = response.body().getData();
    
                               for (int i = 0; i < movies.size(); i++) {
                                   quizID = response.body().getQuizNumber();
                                   questionID = response.body().getData().get(i).getId();
                                   question = response.body().getData().get(i).getQuestion();
                                   trueanswer = response.body().getData().get(i).getTrueAnswer();
                                   filename = response.body().getData().get(i).getOriginalFilename();
                                   mime = response.body().getData().get(i).getMime();
                                   image = response.body().getData().get(i).getImage();
    
                                   values.put(UsersProvider.QUESTION, question);
                                   values.put(UsersProvider.ID_ROW, i + 1);
                                   values.put(UsersProvider.ID_QUESTION, questionID);
                                   values.put(UsersProvider.TRUE_ANSWER, trueanswer);
                                   //  values.put(UsersProvider.USER_ANSWER,-1);
                                   values.put(UsersProvider.ORIGINAL_FILENAME, filename);
                                   values.put(UsersProvider.MIME, mime);
                                   values.put(UsersProvider.IMAGE, image);
                                   Uri uri = getContentResolver().insert(UsersProvider.CONTENT_URI, values);
                                   // Toast.makeText(getApplicationContext(),uri.toString(),Toast.LENGTH_LONG).show();
                                   System.out.println("URI :" + uri);
    
                               }
    
    
                           } else {
    
                           }
                       } else {
                           Toast.makeText(getApplicationContext(), "Sesioni juaj ka skaduar ju duhet te rilogoheni", Toast.LENGTH_LONG).show();
                       }
                   }
    
                   @Override
                   public void onFailure(Call < Quiz > call, Throwable t) {
                       dialog.dismiss();
                   }
               });
           }
    
           public void loading() {
               dialog = new MaterialDialog.Builder(Activity_Quiz.this)
                   .title("Duke hyre ne sistem!")
                   .content("Ju lutem prisni...")
                   .progress(true, 0)
                   .show();
           }
    
           @Override
           public boolean onOptionsItemSelected(MenuItem item) {
               //handle the click on the back arrow click
               switch (item.getItemId()) {
                   case android.R.id.home:
                       finish();
                       return true;
                   default:
                       return super.onOptionsItemSelected(item);
               }
           }
    
    
           public class MyCountDownTimer extends CountDownTimer {
    
               public MyCountDownTimer(long millisInFuture, long countDownInterval) {
                   super(millisInFuture, countDownInterval);
               }
    
               @Override
               public void onTick(long millisUntilFinished) {
    
                   int progress = (int)(millisUntilFinished / 10000);
    
    
                   koha.setText("" + String.format("%d : %d",
                       TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                       TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                       TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
               }
    
               @Override
               public void onFinish() {
                   //finish();
                   saveData.setQuizStatus("start");
                   Toast.makeText(getApplicationContext(), "Koha mbaroi", Toast.LENGTH_LONG).show();
               }
           }
       }
    

    谢谢!

1 个答案:

答案 0 :(得分:0)

由于逻辑处于onCreate状态,因此按钮的状态仅更新一次。 考虑将该逻辑转换为函数,并在更新rowID后在按钮的onClick处理程序中调用它。

例如

private void updateButtonState() {
    if (rowID > 1 && rowID < 40) {
        previous_question.setEnabled(true);
        next_question.setEnabled(true);
    } else if (rowID == 40) {
        next_question.setEnabled(false);
    } else if (rowID == 1) {
        previous_question.setEnabled(false);
    }
}

并在你的onClick

@Override
public void onClick(View v) {
    rowID = rowID - 1; // + 1 if next button
    updateButtonState();
    ...
}