I have an array of text views called plans and an array of integers called months, the text views are clickable and I want to take the value of one of the months' values inside OnClick Listener method but it shows either an error (when I initialize the months with a variable) or always zero (when I initialize the months with fixed size)
package //...
Import //...
public class saving_consultation extends AppCompatActivity {
private TextView[] plans;
private TextView firstplan;
private TextView altplan1;
private TextView altplan2;
private TextView altplan3;
int[] months; // months of all plans
int month; // used to select a month
private int N; // total number of plans and months
private int i;
// rest of the variables
protected void onCreate(Bundle savedInstanceState) {
firstplan = (TextView) findViewById(R.id.first_plan);
altplan1 = (TextView) findViewById(R.id.plan1);
altplan2 = (TextView) findViewById(R.id.plan2);
altplan3 = (TextView) findViewById(R.id.plan3);
N = 4;
months = new int[N];
plans = new TextView[N];
plans[0] = firstplan;
plans[1] = altplan1;
plans[2] = altplan2;
plans[3] = altplan3;
// some code
somebutton.setOnClickListener(new View.OnClickListener() {
// some code
for (i = 0; i < N; i++) {
plans[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(saving_consultation.this)
.setTitle("title")
.setMessage("msg")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
month = months[i];
// other code that adds to a database, works perfectly fine without using the month array
Toast.makeText(getApplicationContext(), "SUCCESS", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
} // End catch
}}) // End yes dialog
.setNegativeButton(android.R.string.no, null).show();
}}); // End plans OnClick()
} // End for loop
}}); // End outter OnClick()
} // End OnCreat()
} // End class
I tried to putmonth = months[i] after the for loop directly but it always takes the last index, I don't know how to fix this
Related
I'm coding a quiz app. When I clicked the score button to see if it worked, it showed I got 0 out of 5 right. I put in all the correct answers, but my code didn't tally anything up. What am I missing? I'm not sure what else to add and could really use the guidance as I am a new coder. I appreciate any help you can give.
int correctAnswers = 0;
// Start score
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void answers(View view) {
RadioButton q1 = (RadioButton) findViewById(R.id.yes_radio_button);
Boolean q1RightAnswer = q1.isChecked();
if (q1RightAnswer) {
correctAnswers += 1;
}
CheckBox q2Box1 = (CheckBox) findViewById(R.id.box1_checkbox);
boolean q2Box1RightAnswer = q2Box1.isChecked();
CheckBox q2Box2 = (CheckBox) findViewById(R.id.box2_checkbox);
boolean q2Box2WrongAnswer = q2Box2.isChecked();
CheckBox q2Box3 = (CheckBox) findViewById(R.id.box3_checkbox);
boolean q2Box3RightAnswer = q2Box3.isChecked();
if (q2Box1RightAnswer)
if (q2Box3RightAnswer) {
correctAnswers += 1;
}
if (q2Box2WrongAnswer) {
correctAnswers += 0;
}
RadioButton q3 = (RadioButton) findViewById(R.id.shuri_radio_button);
Boolean q3RightAnswer = q3.isChecked();
if (q3RightAnswer) {
correctAnswers += 1;
}
RadioButton q5 = (RadioButton) findViewById(R.id.two_radio_button);
Boolean q5RightAnswer = q5.isChecked();
if (q5RightAnswer) {
correctAnswers += 1;
}
EditText q4 = (EditText) findViewById(R.id.wakanda);
String q4RightAnswer = q4.getText().toString();
if (q4RightAnswer.equals(correctAnswers)) {
correctAnswers += 1;
} else {
// incorrect, do nothing
}
}
/**
* This method is called when the score button is clicked.
*/
public void submitScore(View view) {
Button nameField = (Button) findViewById(R.id.score);
String score = nameField.getText().toString();
// Show score message as a toast
Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
// Exit this method early because there's nothing left to do
return;
}
}
This will never be true
q4RightAnswer.equals(correctAnswers)
You need to compare matching types, not Strings to integers.
Assuming that's what you're trying to do, either parse the string or convert the int to a String.
You'll get zero printed if none of the checkboxes are marked or answers() is never called. For example, what's the difference between the answers method and the submitScore method? Both take a View parameter, so which one is actually assigned to the click event?
I would suggest doing something like
RadioButton q1, q3, q5;
EditText q4;
Checkbox qBox1, qBox2;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1 = (RadioButton) findViewById(R.id.yes_radio_button);
// assign other views here
submit = (Button) findViewById(R.id.score);
submit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int correctAnswers = 0;
if (q1.isChecked()) correctAnswers += 1;
// TODO: check other inputs
String q4Text = q4.getText().toString();
if (q4Text.equals(String.valueOf(correctAnswers)) {
correctAnswers += 1;
}
// Toast correct answers
}
});
}
Basically, define all views as class level variables, then immediately set them after a content view is available, then only calculate the score when the button is clicked (in other words, wait for user input). Also, reset the score each time the button is clicked.
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.
What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?
Question Class
// This file contains questions from QuestionBank
class Question{
// array of questions
private String mQuestions [] = {
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
// method returns number of questions
int getLength(){
return mQuestions.length;
}
// method returns question from array textQuestions[] based on array index
String getQuestion(int a) {
return mQuestions[a];
}
}
Main Activity.java
public class MainActivityextends AppCompatActivity {
private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
private int mQuestionNumber = 1; // current question number
//initialising navigation buttons
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
mQuestionText = (TextView) findViewById(R.id.txtQuestion);
// receive the current question number from last activity by Intent
Intent intent = getIntent();
currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking against total number of questions the user has attempted instead of total number of questions from Question Class
if (mQuestionNumber < currentQuestionNumber) {
updateQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// i want it to loop backwards from here
}
});
// logic to update question from array
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mQuestionNumber++;
}
}
}
I would suggest to do this:
1) Rename updateQuestion method to nextQuestion
2) Create a method to decrease the mQuestionNumber like this:
private void prevQuestion(){
if(mQuestionNumber > 0){
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
mQuestionNumber--;}
}
Here's a solution accounting for bounds
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
showNextQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
showPreviousQuestion();
}
});
private void showNextQuestion() {
showQuestion(1);
}
private void showPreviousQuestion() {
showQuestion(-1);
}
private void showQuestion(int increment) {
int newQuestionNumber = mQuestionNumber + increment;
if (newQuestionNumber >= 0 && newQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionNumber = newQuestionNumber;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
}
It can be done by just adding a flag to mention the move,
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(true);
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateQuestion(false);
}
});
And the method would look like:
private void updateQuestion(boolean forward) {
if(forward && mQuestionNumber < mQuestionLibrary.getLength())
mQuestionNumber++
else if (mQuestionNumber>1)
mQuestionNumber--;
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
I would change the following methodes:
would remove mQuestionNummer++; from update question.
You can increment mQuestions directly in the onClickMethode of NextButton.
So you can implement your solution simply by decrement mQuestion-- in onClick of previous Button.
Code would look like this:
public class MainActivityextends AppCompatActivity {
private QuestionLibraryBeginner mQuestionLibrary = new
QuestionLibraryBeginner();
private int mQuestionNumber = 1; // current question number
//initialising navigation buttons
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
// receive the current question number from last activity by Intent
Intent intent = getIntent();
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionNumber++;
updateQuestion();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// i want it to loop backwards from here
if(mQuestionNumber > 0){
mQuestionNumber--;
updateQuestion();
}
else
{}//don't do anything to prevent IndexOutOfBounds
}
});
// logic to update question from array
private void updateQuestion() {
if (mQuestionNumber < mQuestionLibrary.getLength()) {
mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
}
}
}
You need to don't mess logic of your application with view logic, decouple them.
Just make class Question able to provide previous and next questions. Also according to oop principles (solid, grasp) fetch information from class and make decision outside is wrong, make class to do it's work. Oop it's about telling classes to do things, not work instead of them.
class Questions {
private int index = 0;
private String[] mQuestions;
//better to don't hardcode and provide questions in constructor
public Question(String[] questions) {
this.questions = questions;
}
//we don't need this method
int getLength(){
return mQuestions.length;
}
//provide human readable information about current position in question list
// when you want to provide this information to user introduce label field in activity
public String currentPosition() {
int questionPosition = index + 1;
int questionsLength = mQuestions.length;
return String.format("current question number is %d from %d" , questionPosition, questionsLength);
}
//return next question when available, if next not available returns last question from array
public String next() {
int lastIndex = mQuestions.length - 1;
if(index < lastIndex) {
index++;
}
return mQuestions[index];
}
//return current question
public String current() {
return mQuestions[index];
}
//return previous question when available, if previous not available returns first question from array
public String previous() {
int firstIndex = 0;
if(index > firstIndex) {
index--;
}
return mQuestions[index];
}
}
And how to use it in Activity:
public class MainActivity extends AppCompatActivity {
//better to don't hardcode here, but provide this class from
//constructor of MainActivity just like questions array provide
// to constructor in Questions class
private Questions questions = new Questions(new String[]{"q1","q2"});
private Button mPrevious;
private Button mNext;
private TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beginner_review);
mPrevious = (Button) findViewById(R.id.previous);
mNext = (Button) findViewById(R.id.next);
Intent intent = getIntent();
//when create Activity populate question field with first question
mQuestionText.setText(questions.current());
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQuestionText.setText(questions.next());
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQuestionText.setText(questions.previous());
}
});
}
}
p.s. you may improve this code further in way to introduce Observer pattern, Activity is a view, Questions is model.
I want to calculate square root by inputing string. I try to use Math.sqrt(string) but it doesn't work. Do you have any idea how to calculate this?
I really have no idea how to use it with this library.
public class MainActivity extends ActionBarActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide,R.id.buttonSqr,R.id.tan,R.id.cos,
R.id.sin,R.id.open_bracket,R.id.close_bracket};
// TextView used to display the output
private EditText txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric=true;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
private boolean firstTime = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (EditText) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
//Find and set OnClickListener to numeric buttons.
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
firstTime = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
//Find and set OnClickListener to operator buttons, equal button and decimal point button.
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
Log.d("dsfds",txtScreen.getText().toString());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
firstTime = true;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
//firstTime = false;
}
}
});
//delete
findViewById(R.id.btndel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (txtScreen.getText().toString().length() > 1) {
//remove string
String screen_new = txtScreen.getText().toString().substring(0, txtScreen.getText().toString().length() - 1);
txtScreen.setText(screen_new);
} else {
txtScreen.setText("");
}
lastNumeric = false;
stateError = false;
lastDot = false;
//firstTime = false;
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
//firstTime = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
//Logic to calculate the solution
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
//if (lastNumeric && !stateError) {
if ((firstTime || lastNumeric) && !stateError){
// Read the expression
String txt = txtScreen.getText().toString();
Log.d( txt, "error");
txt = txt.replaceAll("x", "*").replaceAll("รท", "/");
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}
First convert your String into a number using a DecimalFormat object and it's parse function then compute your square root.
DecimalFormat df=new DecimalFormat();
sq=java.lang.Math.sqrt(df.parse(myString).doubleValue());
private void setHighScore(){
SharedPreferences.Editor scoreEdit = gamePrefs.edit();
DateFormat dateForm = new SimpleDateFormat("MM/dd/yy");
String dateOutput = dateForm.format(new Date());
String scores = gamePrefs.getString("highScores", "");
if(scores.length() > 0) {
List<Score> scoreStrings = new ArrayList<Score>();
String[] exScores = scores.split("\\|");
for(String eSc : exScores){
String[] parts = eSc.split(" - ");
scoreStrings.add(new Score(parts[0], Integer.parseInt(parts[1])));
}
Score newScore = new Score(dateOutput, score);
scoreStrings.add(newScore);
Collections.sort(scoreStrings);
StringBuilder scoreBuild = new StringBuilder("");
for (int x = 0; x < scoreStrings.size(); x++){
if(x >= 10) break;
if(x > 0) scoreBuild.append("|");
scoreBuild.append(scoreStrings.get(x).getScoreText());
}
scoreEdit.putString("highScores", scoreBuild.toString());
scoreEdit.commit();
}else{
scoreEdit.putString("highScores", ""+dateOutput+ " - " + score);
scoreEdit.commit();
}
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture,long countDownInterval){
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Times Up!");
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
setHighScore();
Intent intent = new Intent(getApplicationContext(), score_screen.class);
startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished){
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Left: " + millisUntilFinished/1000);
}
}
public class score_screen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_screen);
TextView scoreView = (TextView)findViewById(R.id.scoreView);
ImageButton home = (ImageButton)findViewById(R.id.home);
SharedPreferences scorePrefs = getSharedPreferences(Game.GAME_PREFS, 0);
String[] savedScores = scorePrefs.getString("highScores", "").split("\\|");
StringBuilder scoreBuild = new StringBuilder("");
for(String score : savedScores) {
scoreBuild.append(score+"\n");
}
scoreView.setText(scoreBuild.toString());
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ColorMatch.class);
startActivity(intent);
}
});
}
}
I am trying to save a highscore from my gamescreen after my timer is up. I am able to do this just fine and then when I re access my ArrayList for a second time the last score is resaved and I can't figure out why this is happening.
For example,after one game is finished with a score of 3170, it takes me to the high score screen where I see only one instance of the score. Then if I play a new game, or open my Highscores screen from the Main menu, I now see two instances of the same score. (3170) My guess is that it is double committing the score, but I cannot find a second .commit() in my highscore screen.
Actually you may not be saving the high score to preferences twice. I think the problem lies in that you are appending the high score.
Instead of appending the high score, you need to insert the high score into some position in the array. Java arrays are a fixed size though, so you may want to consider using an ArrayList or LinkedList.
In a method I didn't post, (OnDestroy()) I had a second instance of the method setHighScore() to store the score if someone backed out. When I removed this it stopped double writing making me believe that the problem was finish() references onDestroy() to close the activity.
First off, apologies, I'm new to all this and I'm struggling with Android / Java. Ive spent days looking stuff up and I KNOW I'm doing something stupid but would appreciate someone to tell me why / where I'm going wrong.
The app is a simple quiz, puts a picture up, use a spinner to select the answer, press a button to submit, get a toast message to verify and add a score. I know the code is horrendous and a hack but I lack the knowledge to do it more elegantly (part of the reason I'm here). I am trying to place a while loop, using the variable sflags that will be counting up from 0 to 26. When I place it, I can never seem to place it correctly so it works. I suspect some of the code gets broken when I try and wrap it.
Here's the (terrible) code :
public class MainActivity extends Activity implements TextWatcher {
private static final String TAG = "MainActivity";
private EditText mName;
private EditText mEmail;
private ListView countrieslist;
private String comments;
private int score = 0;
private int sflags = 0;
private String emailok;
private String answer;
private String flags;
private Spinner spinnerct;
private Object countries;
// private AdapterView<ListAdapter> spinnerct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countries = getResources().getStringArray(R.array.flagnames);
mName = (EditText) findViewById(R.id.name);
mEmail = (EditText) findViewById(R.id.email);
mEmail.addTextChangedListener(this);
}
#Override
public void afterTextChanged(Editable s) {
emailok = s.toString();
String sub_but = getString(R.string.sub_but);
boolean valid = emailok.length() > 0 &&
emailok.toLowerCase().indexOf(sub_but) == -1;
View view = findViewById(R.id.imageButton1);
boolean isVisible = view.getVisibility() == View.VISIBLE;
if (isVisible == valid) {
// No animation required if both values are true or both values are
// false
return;
}
Animation anim;
if (valid) {
view.setVisibility(View.VISIBLE);
// Create a new animation object
anim = AnimationUtils.makeInAnimation(this, true);
} else {
// Create a new animation object
anim = AnimationUtils.makeOutAnimation(this, true);
view.setVisibility(View.INVISIBLE);
}
// Tell the view it's time to start animating
view.startAnimation(anim);
}
public void thequiz(View view) {
setContentView(R.layout.activity_quiz);
Toast.makeText(
this.getApplicationContext(),
"Thanks ! Now try to identify the flags of these European Countries!",
Toast.LENGTH_LONG
).show();
sflags = 0;
score = 0;
// LinearLayOut Setup
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// ImageView Setup
ImageView imageView = new ImageView(this);
// Constructing the filename using "flag" + the item number from
// variable loop
// using GetIndentifier to return resource to a string
// while loop start here?
//while (sflags<27){
// display correct flag
imageView.setImageResource(
this.getResources().getIdentifier("drawable/flag" + sflags, null, this.getPackageName())
);
// setting image position
imageView.setLayoutParams(
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
);
// =================================================================
// creating spinner object
final Spinner spinnerct = new Spinner(this);
// Now to populate spinner with contents of array flagnames[]
ArrayAdapter<String> spinnercountry = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.flagnames)
);
spinnerct.setAdapter(spinnercountry);
// creating button
Button myButton = new Button(this);
myButton.setText("Submit Answer");
myButton.setBackgroundColor(Color.rgb(250, 200, 250));
// ===================================================================
// adding view to layout
linearLayout.addView(imageView);
linearLayout.addView(spinnerct);
linearLayout.addView(myButton);
// Show layout
setContentView(linearLayout);
// OnclickListener to see when button is clicked
//=========================================================
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
answer = spinnerct.getSelectedItem().toString();
Toast.makeText(
MainActivity.this,
"You selected " + answer,
Toast.LENGTH_SHORT
).show();
// now check the answer is right by calling checkanswer()
//=======================================================
boolean tester = false;
checkanswer(tester); // jumps to procedure, returns boolean
if (tester = true) {
score = score + 1;
Toast.makeText(
MainActivity.this,
"Well done, correct answer! Your Score is " + score + " out of 27",
Toast.LENGTH_LONG
).show();
}
//========================================================
if (tester != true) {
Toast.makeText(
MainActivity.this,
"Sorry wrong answer! ",
Toast.LENGTH_SHORT
).show();
}
//=========================================================
sflags = sflags + 1;
}
});
};
// sendSMS();
// sendEmail();
// }
//=======================================================
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
//========================================================
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
//=========================================================
public void checkanswer(boolean Isitright) {
if (sflags == 0 && answer == "Estonia") {
Isitright = true;
}
}
//=======================================================
}