我正在安卓工作室制作一个智力竞赛应用程序。我面临的问题是,我有数百个问题,有四个选项,还有下一个和上一个按钮。对于选项,我使用单选按钮。我希望在用户为第一个问题选择一个选项,转到下一个问题并为第二个问题选择选项后,他将能够转到上一个问题,并且在那里,单选按钮将与用户先前选择的选项进行核对。
我该怎么做?请帮忙!
这是我的代码:
public class MainActivity extends AppCompatActivity {
int score;
float percentage;
int answerSelected;
private TextView quizQuestion,questionNumber;
private RadioGroup radioGroup;
private RadioButton optionOne;
private RadioButton optionTwo;
private RadioButton optionThree;
private RadioButton optionFour;
private ImageView question_image;
private int currentQuizQuestion;
private int quizCount;
private QuizWrapper firstQuestion;
private List<QuizWrapper> parsedObject;
private boolean mIsDestroyed;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
score = 0;
quizQuestion = (TextView)findViewById(R.id.quiz_question);
questionNumber = (TextView)findViewById(R.id.question_number);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
optionOne = (RadioButton)findViewById(R.id.radio0);
optionTwo = (RadioButton)findViewById(R.id.radio1);
optionThree = (RadioButton)findViewById(R.id.radio2);
optionFour = (RadioButton)findViewById(R.id.radio3);
question_image = (ImageView)findViewById(R.id.question_image);
final Button previousButton = (Button)findViewById(R.id.previousquiz);
final Button nextButton = (Button)findViewById(R.id.nextquiz);
AsyncJsonObject asyncObject = new AsyncJsonObject();
asyncObject.execute("");
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int radioSelected = radioGroup.getCheckedRadioButtonId();
int userSelection = getSelectedAnswer(radioSelected);
int correctAnswerForQuestion = firstQuestion.getIs_correct();
if(userSelection == correctAnswerForQuestion){
// correct answer
score++;
// Toast.makeText(MainActivity.this, "You got the answer correct", Toast.LENGTH_LONG).show();
currentQuizQuestion++;
if(currentQuizQuestion >= quizCount){
previousButton.setVisibility(View.VISIBLE);
AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
alertConfirm.setTitle("Confirm Submission");
alertConfirm.setMessage("Do you want to submit quiz?");
alertConfirm.setCancelable(true);
alertConfirm.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// submit(view);
}
});
AlertDialog dialog = alertConfirm.create();
dialog.show();
Toast.makeText(MainActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
else{
previousButton.setVisibility(View.VISIBLE);
// uncheckedRadioButton();
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else{
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.get.split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}
}
else{
currentQuizQuestion++;
// failed question
// Toast.makeText(MainActivity.this, "You chose the wrong answer", Toast.LENGTH_LONG).show();
if( currentQuizQuestion<quizCount) {
previousButton.setVisibility(View.VISIBLE);
// uncheckedRadioButton();
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else{
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.get.split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}else {
AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
alertConfirm.setTitle("Confirm Submission");
alertConfirm.setMessage("Do you want to submit quiz?");
alertConfirm.setCancelable(true);
alertConfirm.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// submit(view);
submit();
}
});
AlertDialog dialog = alertConfirm.create();
dialog.show();
// Toast.makeText(MainActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
}
}
});
previousButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentQuizQuestion <= 0) {
previousButton.setVisibility(View.INVISIBLE);
}else {
currentQuizQuestion--;
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if (firstQuestion.getQuestion_image().isEmpty()) {
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
} else {
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
// AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
// alertConfirm.setTitle("Finish Test");
// alertConfirm.setMessage("You cannot resume once you submit.Are you sure you want to submit this test?");
// alertConfirm.setCancelable(true);
// alertConfirm.setNegativeButton("RESUME", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
//
// }
// });
// alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// // submit(view);
// submit();
// }
// });
// AlertDialog dialog = alertConfirm.create();
// dialog.show();
//
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mIsDestroyed = true;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
String url = "";
HttpPost httpPost = new HttpPost(url);
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "Loading Quiz","Wait....", true);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
progressDialog.dismiss();
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else {
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private List<QuizWrapper> returnParsedJsonObject(String result){
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
String test = "";
jsonArray = resultObject.optJSONArray(test);
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("id");
String answera = jsonChildNode.getString("option_a");
String answerb = jsonChildNode.getString("option_b");
String answerc = jsonChildNode.getString("option_c");
String answerd = jsonChildNode.getString("option_d");
int correctAnswer = jsonChildNode.getInt("is_correct");
int questionnumber = jsonChildNode.getInt("question_number");
String question = jsonChildNode.getString("questions");
String questionimage = jsonChildNode.getString("question_image");
newItemObject = new QuizWrapper(id, answera,answerb,answerc,answerd, correctAnswer,questionnumber,question,questionimage);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObject;
}
private int getSelectedAnswer(int radioSelected){
answerSelected = 0;
radioGroup.clearCheck();
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
if(radioSelected == R.id.radio3){
answerSelected = 4;
}
return answerSelected;
}
private void uncheckedRadioButton() {
optionOne.setChecked(false);
optionTwo.setChecked(false);
optionThree.setChecked(false);
optionFour.setChecked(false);
}
@Override
public void onBackPressed() {
Toast.makeText(this, "Back Press is not allowed", Toast.LENGTH_LONG).show();
}
private void submit(){
// if (submit)
// checkScore();
// submit = false;
percentage = (float) (score * 100) /parsedObject.size();
//.setVisibility(View.INVISIBLE);
optionOne.setClickable(false);
optionTwo.setClickable(false);
optionThree.setClickable(false);
optionFour.setClickable(false);
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.alert_dialog, null);
final ProgressBar progressBar = alertLayout.findViewById(R.id.circularProgressbar);
final TextView textView = alertLayout.findViewById(R.id.tv);
Drawable drawable = getResources().getDrawable(R.drawable.circular);
progressBar.setMax(parsedObject.size());
progressBar.setSecondaryProgress(parsedObject.size());
progressBar.setProgress(score);
progressBar.setProgressDrawable(drawable);
textView.setText((int) percentage + "%");
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("RESULT");
alert.setMessage("You scored " + score + " out of " + parsedObject.size() );
alert.setView(alertLayout);
alert.setCancelable(false);
alert.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
alert.setPositiveButton("View Solutions", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//clickSolutions();
Intent intent = new Intent(MainActivity.this,SolutionActivity.class);
startActivity(intent);
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
}
这是Kotlin,但用Java编写也是一样的。
ShareReference函数:
private val sharedPreferences = context.getSharedPreferences("YourFile", Context.MODE_PRIVATE)
功能:
fun setInt(key: String, value: Int) {
with(sharedPreferences.edit()) {
putInt(key, value)
apply()
}
}
fun getInt(key: String): Int {
return sharedPreferences.getInt(key, -1)
}
保存选中的:
// save to sharedPreferences
val CHECKED = "checkedRadio"
val checkedButtonId = radioGroup.checkedRadioButtonId
setInt(CHECKED, checkedButtonId)
加载选中的:
val mRatioId = getInt(CHECKED)
radioGroup.check(mRatioId)
让我们在监听器中使用它:
val mRadioGroup = view?.findViewById<RadioGroup>(R.id...)
mRadioGroup?.setOnCheckedChangeListener { _, checkedId ->
setInt(checkedId)
}
单击任意单选按钮后,其单选组将把该选项保存到共享首选项中。此代码正在保存R.id。但您可以将id转换为ABCD。
静态变量:
const val aRb = R.id.aRb
const val bRb = R.id.bRb
const val cRb = R.id.cRb
const val dRb = R.id.dRb
而是保存整数。您可以将其保存在字符串中。
fun setString(key: String, value: String) {
with(sharedPreferences.edit()) {
putString(key, value)
apply()
}
}
fun getString(key: String): String {
return sharedPreferences.getString(key, "")!!
}
选择问题#12作为示例:
when (checkedId) {
aRb -> setString("Q12", 'a')
bRb -> setString("Q12", 'b')
cRb -> setString("Q12", 'c')
dRb -> setString("Q12", 'd')
}