Answer the question
In order to leave comments, you need to log in
Does the data reset when you rotate the screen?
How to save data in onSaveInstanceState(Bundle outState) and return via onRestoreInstanceState(Bundle savedInstanceState). I save the flag variable, the values are still reset.
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.media.SoundPool;
import android.media.AudioManager;
public class MainActivity extends AppCompatActivity {
private SoundPool mSound;
private SoundPool mSound2;
private SoundPool mSound3;
private int mMelody = 1;
private int mPlay;
boolean start = false;
TextView tv, textView;
Button submitbutton, quitbutton;
RadioGroup radio_g;
RadioButton rb1, rb2, rb3, rb4;
final String LOG_TAG = "myLogs";
String hints[] = {"", "Подсказака1","Подсказака2","Подсказака3","Подсказака4"};
String questions[] = {
"Which method can be defined only once in a program?",
"Which of these is not a bitwise operator?",
"Which keyword is used by method to refer to the object that invoked it?",
"Which of these keywords is used to define interfaces in Java?",
"Which of these access specifiers can be used for an interface?",
"Which of the following is correct way of importing an entire package ‘pkg’?",
"What is the return type of Constructors?",
"Which of the following package stores all the standard java classes?",
"Which of these method of class String is used to compare two String objects for their equality?",
"An expression involving byte, int, & literal numbers is promoted to which of these?"
};
String answers[] = {"main method", "<=", "this", "interface", "public", "import pkg.*", "None of the mentioned", "java", "equals()", "int"};
String opt[] = {
"finalize method", "main method", "static method", "private method",
"&", "&=", "+", "-",
"import", "this", "catch", "abstract",
"Interface", "interface", "intf", "Intf",
"public", "protected", "private", "All of the mentioned",
"Import pkg.", "import pkg.*", "Import pkg.*", "import pkg.",
"int", "float", "void", "None of the mentioned",
"lang", "java", "util", "java.packages",
"equals()", "Equals()", "isequal()", "Isequal()",
"int", "long", "byte", "float"
};
int flag = 0;
public static int marks = 0, correct = 0, wrong = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_TAG, "OnCreate");
mSound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSound.load(this, R.raw.sound3, 1);
mSound2 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSound2.load(this, R.raw.sound4, 1);
mSound3 = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mSound3.load(this, R.raw.sound4, 1);
final TextView score = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.user);
Intent intent = getIntent();//Принимаем данные от намерения Intent окна Activity
String name = intent.getStringExtra("myname");// Помещаем в переменную NAME преобразованную в строку через метод putExtra
if (name.trim().equals(""))//ПРОВЕРКА если поле EditText пустое, то переходим в тест с именем по умолчанию USER. И меняем Текст TextView на принятые данные.
textView.setText("Привет, User");
else
textView.setText("Привет," + name);//ПРОВЕРКА если введено какое либо имя принимаем данные из переменной NAME. И меняем Текст TextView на принятые данные.
submitbutton = (Button) findViewById(R.id.button3);
quitbutton = (Button) findViewById(R.id.buttonquit);
tv = (TextView) findViewById(R.id.tvque);
radio_g = (RadioGroup) findViewById(R.id.radio_g);
rb1 = (RadioButton) findViewById(R.id.radioButton);
rb2 = (RadioButton) findViewById(R.id.radioButton2);
rb3 = (RadioButton) findViewById(R.id.radioButton3);
rb4 = (RadioButton) findViewById(R.id.radioButton4);
tv.setText(questions[flag]);
rb1.setText(opt[0]);
rb2.setText(opt[1]);
rb3.setText(opt[2]);
rb4.setText(opt[3]);
submitbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//ПРОВЕРКА Если ответ не выбран выводим сообщение "Выберете ответ"
if (radio_g.getCheckedRadioButtonId() == -1) {
//ПРОВЕРКА Если нажата Radio кнопка без выбора ответа, то выводим сообщение о просьбе выбрать ответ
Toast.makeText(getApplicationContext(), "Выберете ответ", Toast.LENGTH_SHORT).show();
return;
}
//Получаем даннеы о нажатой RadioButton. Помещаем в переменную ansText.То есть выбранный индекс из массива opt
RadioButton uans = (RadioButton) findViewById(radio_g.getCheckedRadioButtonId());
String ansText = uans.getText().toString();//В переменную ansText помещаем
//Toast.makeText(getApplicationContext(), ansText, Toast.LENGTH_SHORT).show();
if (ansText.equals(answers[flag])) {
correct++;
//Toast.makeText(getApplicationContext(), "Верно", Toast.LENGTH_SHORT).show();
} else {
wrong++;
//Toast.makeText(getApplicationContext(), "Не верно", Toast.LENGTH_LONG).show();
// AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//mPlay = mSound.play(mMelody, 1, 1, 1, 0, 1);
}
flag++;// Переменная Флаг увеличиваеться на 1 с каждым нажатием кнопки
if (score != null)
score.setText("" + correct);
if(flag<hints.length)
{
textView.setText(name + hints[flag]);
}else{
textView.setText("");
}
if (flag < questions.length) {
tv.setText(questions[flag]);// Массиву questions передается значение переменной flag+1, выборка из массива индексов(Данных) при каждом щелчке кнопки
rb1.setText(opt[flag * 4]);//Массиву opt передается значение переменной flag+1, после чего происходит выборка из массива индексов(Данных) при каждом щелчке кнопки, и умножает на 4 для выбора нужного индекса
rb2.setText(opt[flag * 4 + 1]);//+ 1 Cмещение на необходимый индекс в массиве opt
rb3.setText(opt[flag * 4 + 2]);
rb4.setText(opt[flag * 4 + 3]);
marks = correct;
} else if (correct > wrong) {
Intent in = new Intent(getApplicationContext(), ResultActivity.class);
startActivity(in);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
mPlay = mSound2.play(mMelody, 1, 1, 1, 0, 1);
} else {
Intent in = new Intent(getApplicationContext(), WrongActivity.class);
startActivity(in);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
mPlay = mSound.play(mMelody, 1, 1, 1, 0, 1);
}
radio_g.clearCheck();//Обновление зажатой Radio кнопки
}
});
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", flag);
Log.d(LOG_TAG, "onSaveInstanceState");
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
flag=savedInstanceState.getInt("correct");
Log.d(LOG_TAG, "onRestoreInstanceState");
}
}
Answer the question
In order to leave comments, you need to log in
outState.putInt("count"
savedInstanceState.getInt("correct")
Corrected and did the same with arrays, still does not work, when the screen is rotated, it resets to the very beginning. What am I doing wrong?
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("flag", flag);
outState.putInt("correct", correct);
outState.putInt("marks", marks);
outState.putInt("wrong", wrong);
outState.putStringArray("answers", answers);
outState.putStringArray("opt", opt);
outState.putStringArray("questions", questions);
Log.d(LOG_TAG, "onSaveInstanceState");
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
flag = savedInstanceState.getInt("flag");
correct = savedInstanceState.getInt("correct");
marks = savedInstanceState.getInt("marks");
wrong = savedInstanceState.getInt("wrong");
answers = savedInstanceState.getStringArray("anwers");
opt = savedInstanceState.getStringArray("opt");
questions = savedInstanceState.getStringArray("questions");
Log.d(LOG_TAG, "onRestoreInstanceState");
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question