How to hide two wrong answers in a quiz? - java

Like in "Who wants to be a millionaire". When a user press a 50/50 help button I want two wrong answers to hide, therefor to setText to "" for two buttons, BUT not "the answer" one. But I don't know how to do that. I'm using sqlite prepopulated database with questions and answers. My 50/50 help button is bPolaPola. Here's my game class:
public class NeogranicenoPetGresaka extends SwarmActivity implements OnClickListener{
MyCount brojacVremena = new MyCount(16000, 1000);
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4, bPolaPola;
TextView question, netacniOdg, score, countdown;
int brojacPogresnihOdgovora = 0;
int brojacTacnihOdgovora = 0;
public static String tacanOdg;
Runnable mLaunchTask = new Runnable() {
public void run() {
nextQuestion();
brojacVremena.start();
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
brojacVremena.cancel();
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
brojacVremena.cancel();
brojacTacnihOdgovora = brojacTacnihOdgovora + 5;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,1200);
}
else{
brojacVremena.cancel();
brojacPogresnihOdgovora++;
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.neograniceno);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "myriad.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKvizaN);
netacniOdg = (TextView) findViewById(R.id.tvBrojPitanjaN);
question = (TextView) findViewById(R.id.tvPitanjeN);
bOdgovor1 = (Button) findViewById(R.id.bOdgovorN1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovorN2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovorN3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovorN4);
bPolaPola = (Button) findViewById(R.id.bPolaPolaN);
score = (TextView) findViewById(R.id.tvSkor2N);
countdown = (TextView) findViewById(R.id.tvCountdownN);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bPolaPola.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
netacniOdg.setTypeface(dugmad);
question.setTypeface(pitanje);
score.setTypeface(dugmad);
countdown.setTypeface(dugmad);
nextQuestion(); //startuje prvo pitanje!
brojacVremena.start(); //startuje brojac vremena
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
brojacPogresnihOdgovora++;
}
#Override
public void onTick(long millisUntilFinished) {
countdown.setText("" + millisUntilFinished / 1000);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override public void onStop() {
super.onStop();
brojacVremena.cancel();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void nextQuestion() {
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
tacanOdg = c.getString(2);
if(brojacPogresnihOdgovora < 5){
question.setText(c.getString(1));
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
netacniOdg.setText("" + brojacPogresnihOdgovora);
score.setText("Score: " + brojacTacnihOdgovora);
}
else{
brojacVremena.cancel();
Intent i = new Intent(getApplicationContext(), Rezultat.class);
i.putExtra("noviRezultat", brojacTacnihOdgovora);
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,4000);
SwarmLeaderboard.submitScore(6863, brojacTacnihOdgovora);
}
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
OK, as jazzbassrob pointed I need to be more specific. I need to setText to my bPolaPola button to "", empty String, but my main problem is that I don't know after collections shuffle where my answers will end up, so I don't know which buttons to setText to. How to know where my answers end up after shuffle?
I actually did not try anything cause in this specific situation I really don't know where to start.

How about running a query which will find the correct option even before the user clicks on one, then you find the correct button out of the four options. After this, use setText="" on any random two buttons other than the one which points to the correct answer.

Related

radioGroup.setOnCheckedChangeListener isn't working properly

i have a problem with radioGroup.setOnCheckedChangeListener and i dont know to fix it
I have a fragment that is used to gather data and create a new instance of payment class.
the problem that i am facing is when i try to reselect the teacher after choosing how many hours have been teached the total doesnt get updated, i know that the code responsible for updating the total is tied to the spinner but i tried to create an independent "setOnCheckedChangeListener" on the radio group but it still fails to update the total.
here is a screenshot of the UI so u can better understand what am talking about
here is the code for java class responsible for this part :
public class addPaymentFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
private RadioGroup radioGroup;
private RadioButton radioButton;
private SchoolViewModel schoolViewModel;
private NumberPicker numberPicker;
private Button addPayment;
private Subject dummySubject, subject;
private Dialog dialog;
private RadioGroup radioGroup0;
private TextView datePickerTV, totalPaymentTV;
private String date;
private int hoursTeached, teacherFee;
private Payment payment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
addPayment = v.findViewById(R.id.btn_add_payment);
totalPaymentTV = v.findViewById(R.id.tv_total_payment);
radioGroup0 = v.findViewById(R.id.rg_select_subject);
datePickerTV = v.findViewById(R.id.tv_date_picker);
radioGroup = v.findViewById(R.id.rg_add_payment);
numberPicker = v.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(10);
hoursTeached = 0;
teacherFee = 0;
date = new String();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
}
});
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int hours) {
if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
#Override
public void onChanged(Teacher teacher) {
teacherFee = teacher.getFee();
hoursTeached = hours;
totalPaymentTV.setText(teacherFee * hours + " DA");
}
});
}
}
});
datePickerTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickADate();
}
});
schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
#Override
public void onChanged(TeacherWithSubjects teacherWithSubjects) {
if (teacherWithSubjects.subjects.size() > 1) {
openDialog(teacherWithSubjects.subjects, radioGroup0);
} else {
subject = teacherWithSubjects.subjects.get(0);
}
}
});
}
});
schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
#Override
public void onChanged(List<Teacher> teachers) {
addRadioButtons(teachers, radioGroup);
}
});
addPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
return;
}
if (subject == null) {
Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
return;
}
if (date.isEmpty()) {
Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
return;
}
if(hoursTeached == 0){
Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
return;
}
SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
int totalPayment = hoursTeached*teacherFee;
payment = new Payment(crossRef,date,totalPayment);
}
});
return v;
}
private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
for (Teacher i : teachers) {
//instantiate...
RadioButton radioButton = new RadioButton(getContext());
//set the values that you would otherwise hardcode in the xml...
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton.setLayoutParams(params);
//label the button...
radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton.setMinWidth(250);
radioButton.setBackgroundResource(R.drawable.custom_checkbox);
radioButton.setElevation(16);
radioButton.setGravity(Gravity.CENTER);
radioButton.setText(i.getTeacherName());
radioButton.setPadding(50, 100, 50, 100);
radioButton.setButtonDrawable(R.drawable.custom_checkbox);
radioButton.setId(i.getTeacherId());
//add it to the group.
radioGroup.addView(radioButton);
}
}
void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_teached_subject_dialog);
dialog.setCancelable(false);
radioGroup = dialog.findViewById(R.id.rg_select_subject);
Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
//populate the checkBox
for (int i = 0; i < subjects.size(); i++) {
RadioButton radioButton1 = new RadioButton(dialog.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
params.bottomMargin = 25;
params.leftMargin = 20;
params.rightMargin = 20;
params.topMargin = 20;
radioButton1.setLayoutParams(params);
radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
radioButton1.setMinWidth(250);
radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
radioButton1.setElevation(16);
radioButton1.setGravity(Gravity.CENTER);
radioButton1.setId(i);
radioButton1.setText(subjects.get(i).getSubjectName());
radioButton1.setPadding(50, 100, 50, 100);
radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
//add it to the group.
radioGroup.addView(radioButton1);
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
dummySubject = subjects.get(i);
Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
}
});
confirmSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (dummySubject == null) {
Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
} else {
subject = dummySubject;
dummySubject = null;
dialog.dismiss();
}
}
});
cancelSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dummySubject = null;
dialog.dismiss();
}
});
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.show();
}
void pickADate() {
DatePickerDialog datePickerDialog = new DatePickerDialog(
getContext(), this,
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
);
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
date = day + "/" + (month + 1) + "/" + year;
datePickerTV.setText(date);
}
}
Sorry if my question is so clear and please let me know if i need to provide any more information and thanks!

I don't understand this error message, any help would be helpful

I tried to build my app, and this error message was produced.
Unexpected character '=' (code 61) (expected a name start character)
at [row,col {unknown-source}]: [41,21]
I have cleaned my code and tried to clean my code and inspected my code and i can't find anything wrong my code, and help would be gratefully recieved.
This is my MainActivity.
package com.michaeldoughty.android.football_quiz;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import
androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.*;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity
{
// to answer true for the question
private Button mTrueButton;
// to answer false for the question
private Button mFalseButton;
// to get the next question
private ImageButton mNextButton;
// to cheat
private Button mCheatButton;
// to hold the questions
private TextView mQuestionTextView;
// whether the user is a cheater
private boolean mIsCheater;
// a key used for the onSaveInstanceState
private final String KEY_INDEX = "index";
// An ActivityResultLauncher for the CheatActivity
ActivityResultLauncher<Intent> cheatActivityResultLauncher =
registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>()
{
#Override
public void onActivityResult (ActivityResult
result)
{
//checking if there is a result code from the
returned intent
if (result.getResultCode () == RESULT_OK)
{
// to check is there is any data in the
returned intent
if (result.getData() == null)
{
return;
}
// setting that the user is a cheater
mIsCheater = true;
}
}
});
// an array of Question objects
private Question [] mQuestionBank = new Question []
{
new Question (R.string.question_euro, true),
new Question (R.string.question_world_cup, false),
new Question (R.string.question_premier_league,
false),
new Question (R.string.question_england, true),
new Question (R.string.question_fa_cup, false),
new Question (R.string.question_league_cup, true)
};
// the index of the current question being displayed
private int mCurrentIndex = 0;
// to hold the percentage of correct answers
private double percentage = 0;
// to hold the amount of correct answers
private double correct = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// to check if there is a value of mCurrentIndex in the
savedInstanceState
if (savedInstanceState != null)
{
mCurrentIndex = savedInstanceState.getInt (KEY_INDEX,
0);
}
// to create the mQuestionTextView
mQuestionTextView = (TextView) findViewById
(R.id.question_text_view);
mQuestionTextView.setOnClickListener(new
View.OnClickListener()
{
#Override
public void onClick(View view)
{
// update the mCurrrentIndex
mCurrentIndex++;
// enable the mTrueButton and mFalseButton
mTrueButton.setEnabled (true);
mFalseButton.setEnabled (true);
if (mCurrentIndex < 6)
{
// call the updateQuestion method
updateQuestion();
}
else
{
displayPercentage ();
mCurrentIndex = 0;
updateQuestion();
}
}
});
// call the updateQuestion method
updateQuestion ();
// to create the mTrueButton
mTrueButton = (Button) findViewById (R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// call the checkAnswer method
checkAnswer (true);
// disable the mTrueButton and mFalseButton
mTrueButton.setEnabled (false);
mFalseButton.setEnabled (false);
}
});
// to create the mFalseButton
mFalseButton = (Button) findViewById (R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// call the checkAnswer method
checkAnswer (false);
// disable the mTrueButton and mFalseButton
mTrueButton.setEnabled (false);
mFalseButton.setEnabled (false);
}
});
// to create the mNextButton
mNextButton = (ImageButton) findViewById
(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// update the mCurrrentIndex
mCurrentIndex++;
// enable the mTrueButton and mFalseButton
mTrueButton.setEnabled (true);
mFalseButton.setEnabled (true);
if (mCurrentIndex < 6)
{
// call the updateQuestion method
updateQuestion();
}
else
{
displayPercentage ();
mCurrentIndex = 0;
updateQuestion();
}
}
});
// to create the mCheatButton
mCheatButton = (Button) findViewById (R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean answerIsTrue = mQuestionBank
[mCurrentIndex].isAnswerTrue ();
Intent intent = CheatActivity.newIntent
(MainActivity.this, answerIsTrue);
cheatActivityResultLauncher.launch (intent);
}
});
}
/**
The onSaveInstanceState method saves savedInstanceState when
the activity is stopped.
#param savedInstanceState, the bundle of the activity.
*/
#Override
public void onSaveInstanceState (Bundle savedInstanceState)
{
// call the super's constructor
super.onSaveInstanceState (savedInstanceState);
// to add the mCurrentIndex to the bundle
savedInstanceState.putInt (KEY_INDEX, mCurrentIndex);
}
/**
The updateQuestion method updates the question.
*/
public void updateQuestion ()
{
// get the next question
int question = mQuestionBank [mCurrentIndex].getTextResId
();
// to display the next question
mQuestionTextView.setText (question);
}
/**
The checkAnswer method checks the user's answer, to see if
its correct or not
#param userPressedTrue, the user's answer.
*/
public void checkAnswer (boolean userPressedTrue)
{
// getting the correct answer
boolean answerIsTrue = mQuestionBank
[mCurrentIndex].isAnswerTrue ();
// the message in the toast
int messageResId = 0;
// checking the user's answer and setting the right meassge
if (userPressedTrue == answerIsTrue)
{
messageResId = R.string.correct_toast;
correct++;
}
else
{
messageResId = R.string.incorrect_toast;
}
// displaying the meessage in a toast
Toast toast;
toast = Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT);
toast.setGravity (Gravity.TOP|Gravity.CENTER, 0, 0);
toast.show ();
}
/**
The displayPercentage displays the percentage of correct
answers the user had guessed.
*/
public void displayPercentage ()
{
// working out the percentage
percentage = (correct / mQuestionBank.length) * 100;
DecimalFormat df = new DecimalFormat("#.00");
// displaying the percentage as a toast
Toast.makeText(this, "You have guessed " +
df.format(percentage) + "%!", Toast.LENGTH_SHORT).show ();
// to set the correct and percentage back to zero
correct = 0;
percentage = 0;
}
}
Here is my CheatActivity
// an extra key for the intent which tells the CheatActivity
what the answer is
private static final String EXTRA_ANSWER_IS_TRUE =
"com.michaeldoughty.android.football_quiz_answer_is_true";
// an extra key for the intent which tells the MainActivity if
the user has cheated
private static final String EXTRA_ANSWER_IS_SHOWN =
"com.michaeldoughty.android.football_quiz_answer_shown";
// if the answer is true or not
private boolean mAnswerIsTrue;
// to hold the correct answer
private TextView mAnswerTextView;
// a button to show the correct answer
private Button mShowAnswerButton;
// to create an intent to create a CheatActivity
public static Intent newIntent (Context packageContext,
boolean answerIsTrue)
{
Intent intent = new Intent (packageContext,
CheatActivity.class);
intent.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return intent;
}
public static boolean wasAnswerShown (Intent result)
{
return result.getBooleanExtra (EXTRA_ANSWER_IS_SHOWN,
false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
// to get the mAnswerIsTrue
mAnswerIsTrue = getIntent ().getBooleanExtra
(EXTRA_ANSWER_IS_TRUE, false);
// to create the mAnswerTextView
mAnswerTextView = findViewById (R.id.answer_text_view);
// to create the mShowAnswerButton
mShowAnswerButton = findViewById (R.id.show_answer_button);
mShowAnswerButton.setOnClickListener(new
View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (mAnswerIsTrue)
{
mAnswerTextView.setText (R.string.true_button);
}
else
{
mAnswerTextView.setText
(R.string.false_button);
}
setAnswerShownResult (true);
}
});
}
/**
The setAnswerShownResult creates an Intent, to send the
isAnswerShown to the MainActivity.
#param isAnswerShown, whether the user has cheated or not.
*/
private void setAnswerShownResult (boolean isAnswerShown)
{
Intent data = new Intent ();
data.putExtra (EXTRA_ANSWER_IS_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
}
Here is my Question class
package com.michaeldoughty.android.football_quiz;
public class Question
{
// to hold the text res id of the question
private int mTextResId;
// to hold if the answer is true or false
private boolean mAnswerTrue;
/**
Constructor
*/
public Question (int textResId, boolean answerTrue)
{
mTextResId = textResId;
mAnswerTrue = answerTrue;
}
public int getTextResId()
{
return mTextResId;
}
public void setTextResId(int textResId)
{
mTextResId = textResId;
}
public boolean isAnswerTrue()
{
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue)
{
mAnswerTrue = answerTrue;
}
}

Android Application MainActivity keeps Resetting Information

I am working on a simple application that passes a parcelable from one activity to another. In MainActivity, I have a LinkedList that holds the information taken from the parcelable. However, each time i return to MainActivity, the Object previously stored in the LinkedList (Parcelable) is deleted. What am I doing wrong? I have spent literally the past 3 days trying to figure out why it isn't saving anything but the logic looks solid. So I updated to use startActivityForResult and now the Parcelable in MainActivity is NULL.
public class MainActivity extends Activity {
int tasks;
final static String TASK_KEY = "newTask";
final static String INDEX_KEY = "LLIndex";
Task t;
ScrollView scrollView;
LinearLayout taskHolder;
LinkedList<Task> taskList = new LinkedList<Task>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("In onCreate", "here");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvCounter = (TextView) findViewById(R.id.textView1);
taskHolder = (LinearLayout) findViewById(R.id.linearScroll);
//Checks for parcelable
if(getIntent().hasExtra(Create.TASK_KEY)){
Log.d("Task", "You've got mail!");
Task t = (Task)getIntent().getExtras().getParcelable(Create.TASK_KEY);
taskList.add(t);
addNewTask(t);
}
Log.d("LL size", Integer.toString(tasks));
tasks = taskList.size();
tvCounter.setText(Integer.toString(tasks) + " " + getApplicationContext().getResources().getString(R.string.tv_task));
Button plusButton = (Button) findViewById(R.id.button1);
plusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Create.class);
startActivity(i);
}
});
}
void addNewTask(Task t) {
tasks++;
Log.d("In addNewTask method", t.toString());
LinearLayout newTaskLayout = new LinearLayout(getApplicationContext());
newTaskLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newTaskLayout.setLayoutParams(params);
//int bottom = (int) getResources().getDimension(R.dimen.margin_bottom);
//int left = (int) getResources().getDimension(R.dimen.margin_left);
//params.setMargins(left, 0, 0, bottom);
TextView tvTitle = new TextView(getApplicationContext());
TextView tvDate = new TextView(getApplicationContext());
TextView tvTime = new TextView(getApplicationContext());
tvTitle.setTextColor(Color.BLACK);
tvDate.setTextColor(Color.BLACK);
tvTime.setTextColor(Color.BLACK);
tvTitle.setTypeface(tvTitle.getTypeface(), Typeface.BOLD);
tvTitle.setText(t.getName());
tvDate.setText(t.getDate());
tvTime.setText(t.getTime());
newTaskLayout.addView(tvTitle);
newTaskLayout.addView(tvDate);
newTaskLayout.addView(tvTime);
//params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//params.setMargins(0, 0, 0, 0);
//tvDate.setLayoutParams(params);
//tvTime.setLayoutParams(params);
//tvTitle.setTextSize(getResources().getDimension(R.dimen.size_of_text));
taskHolder.addView(newTaskLayout);
final int index = ((ViewGroup) newTaskLayout.getParent()).indexOfChild(newTaskLayout);
newTaskLayout.setOnClickListener(new View.OnClickListener() {//bind listener
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this,Display.class);
i.putExtra(TASK_KEY, taskList.get(index));
i.putExtra(INDEX_KEY, index);
startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==1){
Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show();
Log.d("Task", "You've got mail!");
if(getIntent().hasExtra(Create.TASK_KEY)){
Task t = (Task)getIntent().getExtras().getParcelable(Create.TASK_KEY);
taskList.add(t);
addNewTask(t);
}
Log.d("LL size", Integer.toString(tasks));
tasks = taskList.size();
tvCounter.setText(Integer.toString(tasks) + " " + getApplicationContext().getResources().getString(R.string.tv_task));
}
else{
Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
}
}
}
Create Class:
public class Create extends Activity{
private int year;
private int month;
private int day;
private String name, date, time, priority;
final static String TASK_KEY = "newTask";
static final int PICK_CONTACT_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
final Calendar cal = Calendar.getInstance();
//Current Date
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
final EditText etTitle = (EditText) findViewById(R.id.editText1);
final EditText etDate = (EditText) findViewById(R.id.editText2);
final EditText etTime = (EditText) findViewById(R.id.editText3);
final RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
//int selectedId = rg.getCheckedRadioButtonId();
//final RadioButton radioSelected = (RadioButton) findViewById(selectedId);
Button save = (Button) findViewById(R.id.button1);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get checked radio button
RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
// TODO Auto-generated method stub
name = etTitle.getText().toString();
date = etDate.getText().toString();
time = etTime.getText().toString();
priority = (String) rb.getTag();
Task t = new Task(name, date, time, priority);
Log.d("task", t.toString());
Intent i = new Intent(Create.this, MainActivity.class);
i.putExtra(TASK_KEY, t); //Puts new Task object into Intent to send
setResult(1,i);
finish();
}
});
etDate.setKeyListener(null);
etTime.setKeyListener(null);
final DatePickerDialog.OnDateSetListener datePick = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
private void updateLabel() {
// TODO Auto-generated method stub
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
etDate.setText(sdf.format(cal.getTime()));
}
};
etDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Do whatever
new DatePickerDialog(Create.this, datePick, cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show();
}
});
etTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar curTime = Calendar.getInstance();
int hour = curTime.get(Calendar.HOUR_OF_DAY);
int minute = curTime.get(Calendar.MINUTE);
TimePickerDialog tp;
tp = new TimePickerDialog(Create.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String am_pm;
String minuteStr;
Log.d("hour", Integer.toString(selectedHour));
if (selectedHour == 0){
selectedHour = 12;
am_pm = "AM";
}else if(selectedHour == 12){
selectedHour = 12;
am_pm = "PM";
}else if(selectedHour > 12) {
selectedHour -= 12;
am_pm = "PM";
}else{
am_pm = "AM";
}
if(selectedMinute < 10){
minuteStr = "0" + Integer.toString(selectedMinute);
}else{
minuteStr = Integer.toString(selectedMinute);
}
etTime.setText( selectedHour + ":" + minuteStr + " " + am_pm);
}
}, hour, minute, false);//Yes 24 hour time
tp.setTitle("Set Time");
tp.show();
}
});
}
}
If I understand the question correctly, you have a list of messages in MainActivity, and you're starting the Create intent to create a new message. Then, on save, you're starting a new MainActivity with the new message to add to the list.
The problem with this approach is that a new MainActivity instance will be created each time, with a new (empty) LinkedList in it.
I would look at using startActivityForResult() to run the Create activity, and use setResult() and finish() within Create to return the new message.
You should also look at saving the contents of the list within 'onSaveInstanceState', to handle the destruction and recreation of your MainActivity (e.g. when the user rotates their device).

Application always calls onCreate() when the phone is locked and unlocked

Is there any way to save the state of the application because the application calls onCreate() everytime the android phone is locked. When I unlocked it, the app calls the onCreate() method and start again.. BTW my app is like text twist. When I unlock the screen a new word is shown, instead of the current one.. The score is also reset as well as the time.. How can I work on this? Please help.. It's still unanswered..
This is the whole code of my activity..
public class friend extends Activity {
//score
ScoreHandler scHandler;
Score sc;
int totalScore;
//words
//DatabaseHelper dbHelp;
DBHelper dbHelp;
public String randomWord;
//speech
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
//shake
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
//timer
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private TextView timeText;
private final long startTime = 180 * 1000;
private final long interval = 1 * 1000;
private long timeLeft;
private int gameScore;
private TextView shuffleView;
TextView scoreView;
//Animation
Animation myFadeInAnimation;
Animation myFadeOutAnimation;
Animation leftToRight;
//sliding
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
Context context;
static final String STATE_SCORE = "currentScore";
static final String STATE_WORD = "currentWord";
static final String STATE_TIME = "currentTime";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
} else {
// Probably initialize members with default values for a new instance
}
setContentView(R.layout.friend);
leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);
ImageButton next = (ImageButton) findViewById(R.id.nextround_game);
next.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, friend1.class);
startActivity(intent);
}
});
ImageButton giveUp = (ImageButton) findViewById(R.id.surrender_game);
giveUp.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, GameOverActivity.class);
startActivity(intent);
}
});
//score
//timer
timeText = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
timeText.setText(timeText.getText() + String.valueOf(startTime/1000));
countDownTimer.start();
timerHasStarted = true;
this.removeAll();
dbHelp = new DBHelper(this);
randomWord = dbHelp.random();
System.out.println(randomWord);
String wordCaps = randomWord.toUpperCase();
final String finalWord = shuffle(wordCaps);
shuffleView = (TextView) findViewById(R.id.jumble);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/American Captain.ttf");
shuffleView.setTypeface(type);
shuffleView.setText(finalWord);
//shake
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
//String str = (String) stringList.remove(selectedWord);
String wordOutput = shuffle(finalWord);
TextView tv = (TextView) findViewById(R.id.jumble);
tv.setText(wordOutput);
}
});
//speech
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timeText.setText("0:00");
playSound(R.raw.clock_whistle);
ImageView timeIsUp = (ImageView) findViewById(R.id.time_is_up);
timeIsUp.startAnimation(leftToRight);
}
#Override
public void onTick(long millisUntilFinished) {
long minutes = (millisUntilFinished / (1000*60)) % 60;
long seconds = (millisUntilFinished / 1000) % 60 ;
timeLeft = millisUntilFinished/1000;
timeText.setText("" + minutes + ":" + seconds );
if (timeLeft <= 10) {
playSound(R.raw.clock_beep);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
System.out.println(""+text.get(0));
String spoken = text.get(0);
if(dbHelp.exists(spoken)){
if(dbHelp.isLongest(spoken)){
Toast.makeText(getApplicationContext(), "You have guessed the longest word! ", Toast.LENGTH_SHORT).show();
}
gameScore = text.get(0).length()*10;
scoreView = (TextView) findViewById(R.id.scoreView);
scoreView.setText(""+gameScore);
scHandler = new ScoreHandler(this);
scHandler.addScore(new Score(1,gameScore));
int cumulativeScore = scHandler.accumulateScores();
scoreView.setText(""+cumulativeScore);
playSound(R.raw.correct);
WordGuessedHandler guessedWord = new WordGuessedHandler(this);
guessedWord.addGuessedWord(new Words(1,spoken));
ImageView img = (ImageView) findViewById(R.id.awesome);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
img.startAnimation(myFadeInAnimation);
img.startAnimation(myFadeOutAnimation);
}else{
playSound(R.raw.poweng);
ImageView image = (ImageView) findViewById(R.id.wrong);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
image.startAnimation(myFadeInAnimation);
image.startAnimation(myFadeOutAnimation);
}
}
}
}
}
public String shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
return output.toString();
}
#Override
public void onBackPressed()
{
Intent inMain=new Intent(friend.this, MainActivity.class);
inMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inMain);
countDownTimer.cancel();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE,gameScore);
savedInstanceState.putLong(STATE_TIME,timeLeft);
savedInstanceState.putString(STATE_TIME,randomWord);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
}
//sliding menu onChange
#Override
public void onContentChanged()
{
super.onContentChanged();
mOpenButton = (Button) findViewById( R.id.button_open );
mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer);
/* GridView gridView;
ArrayList ArrayofName = new ArrayList();
WordHandler db = new WordHandler(this);*/
TextView txt = (TextView) findViewById(R.id.text);
txt.setText("Hello There!");
GridView gridview = (GridView) findViewById(R.id.gridView1);
WordGuessedHandler guessed = new WordGuessedHandler(this);
List <WordGuessed> guessedList = guessed.getAllWordGuessed();
List<String> wordsList = new ArrayList<String>();
for(WordGuessed wg:guessedList){
wordsList.add(wg.getWord());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, wordsList);
gridview.setAdapter(adapter);
}
public void playSound(int sound) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.setLooping(false);
mp.setVolume(1,1);
mp.start();
}
public void removeAll()
{
ScoreHandler scHandler = new ScoreHandler(this);
// db.delete(String tableName, String whereClause, String[] whereArgs);
// If whereClause is null, it will delete all rows.
SQLiteDatabase db = scHandler.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
db.delete("scores_table", null, null);
db.close();
}
}
This question answers your question.
https://developer.android.com/training/basics/activity-lifecycle/index.html
Please use the onPause() and onResume() methods in your main Activity to solve this problem. If both method aren't defined, your app will go to the next methods in the lifecycle, which will be onCreate() and other methods. Read more here.
It is also possible to save your current instance by using onSaveInstance(Bundle b) and onRestoreInstance(Bundle b)
PS: someone has asked it earlier, and wrote a small example to use the onSaveInstance and onRestoreInstance (if you want to use it) here.

How to save points after popup close and avoid repetition from SQLite?

I have 36 imageButtons and with each one I call the same popup in which I set random question from sqlite database. When user answers question by clicking one of the 4 possible solutions it closes and goes back to my 36 buttons. Now here I have 2 problems:
I use this code to avoid repeating questions. In activity scope:
LinkedList mAnsweredQuestions = new LinkedList();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
and in my question method:
mAnsweredQuestions.add(c.getLong(0));
But this does not work when my activity resumes after popup question close. It's like it loads my activity from scratch. I use this in my other game and it works fine in "normal" activity, but for some reason after popup it does not.
2.I need for each imageButton press to launch this popup activity and after each correct answer to save different number of points. I used startActivityForResult in my other game to start activity and save result, but in that case I was starting different activities with each button. Now I have to start the same activity, and save back different results. How can I do that?
Here's my popup question class:
public class Pitanja_Cigle extends Activity{
public static String tacanOdg;
int counter = 0;
Button b1, b2, b3, b4;
TextView question;
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
Intent i = new Intent("rs.androidaplikacije.toplo_hladno.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,1200);
}
else{
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,2200);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.pitanja_cigle);
InicirajVariable();
nextQuestion();
}
private void nextQuestion() {
counter++;
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getPitanjaCigle(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
tacanOdg = c.getString(2);
Collections.shuffle(labels);
question.setText(c.getString(1));
b1.setText(labels.get(0).option);
b1.setTag(labels.get(0));
b1.setOnClickListener(clickListener);
b2.setText(labels.get(1).option);
b2.setTag(labels.get(1));
b2.setOnClickListener(clickListener);
b3.setText(labels.get(2).option);
b3.setTag(labels.get(2));
b3.setOnClickListener(clickListener);
b4.setText(labels.get(3).option);
b4.setTag(labels.get(3));
b4.setOnClickListener(clickListener);
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
}
private void InicirajVariable() {
Typeface naslov = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
question = (TextView) findViewById(R.id.tvPitanjeCigle);
b1 = (Button) findViewById(R.id.bOdgCigle1);
b2 = (Button) findViewById(R.id.bOdgCigle2);
b3 = (Button) findViewById(R.id.bOdgCigle3);
b4 = (Button) findViewById(R.id.bOdgCigle4);
b1.setTypeface(dugmad);
b2.setTypeface(dugmad);
b3.setTypeface(dugmad);
b4.setTypeface(dugmad);
question.setTypeface(naslov);
}
}

Categories