I'm trying to add mod this so that each time a player guesses the flag on the first attempt, increment a counter. This value will then be displayed at the end when 10 flags is completed. So far i've only gotten it to display the number of guesses and correct answer percentage.
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class FlagQuizGame extends Activity
{
// String used when logging error messages
private static final String TAG = "FlagQuizGame Activity";
private List<String> fileNameList; // flag file names
private List<String> quizCountriesList; // names of countries in quiz
private Map<String, Boolean> regionsMap; // which regions are enabled
private String correctAnswer; // correct country for the current flag
private int totalGuesses; // number of guesses made
private int correctAnswers; // number of correct guesses
private int guessRows; // number of rows displaying choices
private Random random; // random number generator
private Handler handler; // used to delay loading next flag
private Animation shakeAnimation; // animation for incorrect guess
private TextView answerTextView; // displays Correct! or Incorrect!
private TextView questionNumberTextView; // shows current question #
private ImageView flagImageView; // displays a flag
private TableLayout buttonTableLayout; // table of answer Buttons
private int counter;
// called when the activity is first created
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); // call the superclass's method
setContentView(R.layout.main); // inflate the GUI
fileNameList = new ArrayList<String>(); // list of image file names
quizCountriesList = new ArrayList<String>(); // flags in this quiz
regionsMap = new HashMap<String, Boolean>(); // HashMap of regions
guessRows = 1; // default to one row of choices
random = new Random(); // initialize the random number generator
handler = new Handler(); // used to perform delayed operations
counter = 0;
// load the shake animation that's used for incorrect answers
shakeAnimation =
AnimationUtils.loadAnimation(this, R.anim.incorrect_shake);
shakeAnimation.setRepeatCount(3); // animation repeats 3 times
// get array of world regions from strings.xml
String[] regionNames =
getResources().getStringArray(R.array.regionsList);
// by default, countries are chosen from all regions
for (String region : regionNames )
regionsMap.put(region, true);
// get references to GUI components
questionNumberTextView =
(TextView) findViewById(R.id.questionNumberTextView);
flagImageView = (ImageView) findViewById(R.id.flagImageView);
buttonTableLayout =
(TableLayout) findViewById(R.id.buttonTableLayout);
answerTextView = (TextView) findViewById(R.id.answerTextView);
// set questionNumberTextView's text
questionNumberTextView.setText(
getResources().getString(R.string.question) + " 1 " +
getResources().getString(R.string.of) + " 10");
resetQuiz(); // start a new quiz
} // end method onCreate
// set up and start the next quiz
private void resetQuiz()
{
// use the AssetManager to get the image flag
// file names for only the enabled regions
AssetManager assets = getAssets(); // get the app's AssetManager
fileNameList.clear(); // empty the list
try
{
Set<String> regions = regionsMap.keySet(); // get Set of regions
// loop through each region
for (String region : regions)
{
if (regionsMap.get(region)) // if region is enabled
{
// get a list of all flag image files in this region
String[] paths = assets.list(region);
for (String path : paths)
fileNameList.add(path.replace(".png", ""));
} // end if
} // end for
} // end try
catch (IOException e)
{
Log.e(TAG, "Error loading image file names", e);
} // end catch
correctAnswers = 0; // reset the number of correct answers made
totalGuesses = 0; // reset the total number of guesses the user made
quizCountriesList.clear(); // clear prior list of quiz countries
// add 10 random file names to the quizCountriesList
int flagCounter = 1;
int numberOfFlags = fileNameList.size(); // get number of flags
while (flagCounter <= 10)
{
int randomIndex = random.nextInt(numberOfFlags); // random index
// get the random file name
String fileName = fileNameList.get(randomIndex);
// if the region is enabled and it hasn't already been chosen
if (!quizCountriesList.contains(fileName))
{
quizCountriesList.add(fileName); // add the file to the list
++flagCounter;
} // end if
} // end while
loadNextFlag(); // start the quiz by loading the first flag
} // end method resetQuiz
// after the user guesses a correct flag, load the next flag
private void loadNextFlag()
{
// get file name of the next flag and remove it from the list
String nextImageName = quizCountriesList.remove(0);
correctAnswer = nextImageName; // update the correct answer
answerTextView.setText(""); // clear answerTextView
// display the number of the current question in the quiz
questionNumberTextView.setText(
getResources().getString(R.string.question) + " " +
(correctAnswers + 1) + " " +
getResources().getString(R.string.of) + " 10");
// extract the region from the next image's name
String region =
nextImageName.substring(0, nextImageName.indexOf('-'));
// use AssetManager to load next image from assets folder
AssetManager assets = getAssets(); // get app's AssetManager
InputStream stream; // used to read in flag images
try
{
// get an InputStream to the asset representing the next flag
stream = assets.open(region + "/" + nextImageName + ".png");
// load the asset as a Drawable and display on the flagImageView
Drawable flag = Drawable.createFromStream(stream, nextImageName);
flagImageView.setImageDrawable(flag);
} // end try
catch (IOException e)
{
Log.e(TAG, "Error loading " + nextImageName, e);
} // end catch
// clear prior answer Buttons from TableRows
for (int row = 0; row < buttonTableLayout.getChildCount(); ++row)
((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();
Collections.shuffle(fileNameList); // shuffle file names
// put the correct answer at the end of fileNameList
int correct = fileNameList.indexOf(correctAnswer);
fileNameList.add(fileNameList.remove(correct));
// get a reference to the LayoutInflater service
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
// add 3, 6, or 9 answer Buttons based on the value of guessRows
for (int row = 0; row < guessRows; row++)
{
TableRow currentTableRow = getTableRow(row);
// place Buttons in currentTableRow
for (int column = 0; column < 3; column++)
{
// inflate guess_button.xml to create new Button
Button newGuessButton =
(Button) inflater.inflate(R.layout.guess_button, null);
// get country name and set it as newGuessButton's text
String fileName = fileNameList.get((row * 3) + column);
newGuessButton.setText(getCountryName(fileName));
// register answerButtonListener to respond to button clicks
newGuessButton.setOnClickListener(guessButtonListener);
currentTableRow.addView(newGuessButton);
} // end for
} // end for
// randomly replace one Button with the correct answer
int row = random.nextInt(guessRows); // pick random row
int column = random.nextInt(3); // pick random column
TableRow randomTableRow = getTableRow(row); // get the TableRow
String countryName = getCountryName(correctAnswer);
((Button)randomTableRow.getChildAt(column)).setText(countryName);
} // end method loadNextFlag
// returns the specified TableRow
private TableRow getTableRow(int row)
{
return (TableRow) buttonTableLayout.getChildAt(row);
} // end method getTableRow
// parses the country flag file name and returns the country name
private String getCountryName(String name)
{
return name.substring(name.indexOf('-') + 1).replace('_', ' ');
} // end method getCountryName
// called when the user selects an answer
private void submitGuess(Button guessButton)
{
String guess = guessButton.getText().toString();
String answer = getCountryName(correctAnswer);
++totalGuesses; // increment the number of guesses the user has made
// if the guess is correct
if (guess.equals(answer))
{
++correctAnswers; // increment the number of correct answers
// display "Correct!" in green text
answerTextView.setText(answer + "!");
answerTextView.setTextColor(
getResources().getColor(R.color.correct_answer));
disableButtons(); // disable all answer Buttons
// if the user has correctly identified 10 flags
if (correctAnswers == 10)
{
// create a new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.reset_quiz); // title bar string
// set the AlertDialog's message to display game results
builder.setMessage(String.format("%d %s, %.02f%% %s",
totalGuesses, getResources().getString(R.string.guesses),
(1000 / (double) totalGuesses),
getResources().getString(R.string.correct)));
builder.setCancelable(false);
// add "Reset Quiz" Button
builder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
resetQuiz();
} // end method onClick
} // end anonymous inner class
); // end call to setPositiveButton
// create AlertDialog from the Builder
AlertDialog resetDialog = builder.create();
resetDialog.show(); // display the Dialog
} // end if
else // answer is correct but quiz is not over
{
// load the next flag after a 1-second delay
handler.postDelayed(
new Runnable()
{
#Override
public void run()
{
loadNextFlag();
}
}, 1000); // 1000 milliseconds for 1-second delay
} // end else
} // end if
else // guess was incorrect
{
// play the animation
flagImageView.startAnimation(shakeAnimation);
// display "Incorrect!" in red
answerTextView.setText(R.string.incorrect_answer);
answerTextView.setTextColor(
getResources().getColor(R.color.incorrect_answer));
guessButton.setEnabled(false); // disable the incorrect answer
} // end else
} // end method submitGuess
// utility method that disables all answer Buttons
private void disableButtons()
{
for (int row = 0; row < buttonTableLayout.getChildCount(); ++row)
{
TableRow tableRow = (TableRow) buttonTableLayout.getChildAt(row);
for (int i = 0; i < tableRow.getChildCount(); ++i)
tableRow.getChildAt(i).setEnabled(false);
} // end outer for
} // end method disableButtons
// create constants for each menu id
private final int CHOICES_MENU_ID = Menu.FIRST;
private final int REGIONS_MENU_ID = Menu.FIRST + 1;
// called when the user accesses the options menu
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
// add two options to the menu - "Choices" and "Regions"
menu.add(Menu.NONE, CHOICES_MENU_ID, Menu.NONE, R.string.choices);
menu.add(Menu.NONE, REGIONS_MENU_ID, Menu.NONE, R.string.regions);
return true; // display the menu
} // end method onCreateOptionsMenu
// called when the user selects an option from the menu
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// switch the menu id of the user-selected option
switch (item.getItemId())
{
case CHOICES_MENU_ID:
// create a list of the possible numbers of answer choices
final String[] possibleChoices =
getResources().getStringArray(R.array.guessesList);
// create a new AlertDialog Builder and set its title
AlertDialog.Builder choicesBuilder =
new AlertDialog.Builder(this);
choicesBuilder.setTitle(R.string.choices);
// add possibleChoices's items to the Dialog and set the
// behavior when one of the items is clicked
choicesBuilder.setItems(R.array.guessesList,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
// update guessRows to match the user's choice
guessRows = Integer.parseInt(
possibleChoices[item].toString()) / 3;
resetQuiz(); // reset the quiz
} // end method onClick
} // end anonymous inner class
); // end call to setItems
// create an AlertDialog from the Builder
AlertDialog choicesDialog = choicesBuilder.create();
choicesDialog.show(); // show the Dialog
return true;
case REGIONS_MENU_ID:
// get array of world regions
final String[] regionNames =
regionsMap.keySet().toArray(new String[regionsMap.size()]);
// boolean array representing whether each region is enabled
boolean[] regionsEnabled = new boolean[regionsMap.size()];
for (int i = 0; i < regionsEnabled.length; ++i)
regionsEnabled[i] = regionsMap.get(regionNames[i]);
// create an AlertDialog Builder and set the dialog's title
AlertDialog.Builder regionsBuilder =
new AlertDialog.Builder(this);
regionsBuilder.setTitle(R.string.regions);
// replace _ with space in region names for display purposes
String[] displayNames = new String[regionNames.length];
for (int i = 0; i < regionNames.length; ++i)
displayNames[i] = regionNames[i].replace('_', ' ');
// add displayNames to the Dialog and set the behavior
// when one of the items is clicked
regionsBuilder.setMultiChoiceItems(
displayNames, regionsEnabled,
new DialogInterface.OnMultiChoiceClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked)
{
// include or exclude the clicked region
// depending on whether or not it's checked
regionsMap.put(
regionNames[which].toString(), isChecked);
} // end method onClick
} // end anonymous inner class
); // end call to setMultiChoiceItems
// resets quiz when user presses the "Reset Quiz" Button
regionsBuilder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int button)
{
resetQuiz(); // reset the quiz
} // end method onClick
} // end anonymous inner class
); // end call to method setPositiveButton
// create a dialog from the Builder
AlertDialog regionsDialog = regionsBuilder.create();
regionsDialog.show(); // display the Dialog
return true;
} // end switch
return super.onOptionsItemSelected(item);
} // end method onOptionsItemSelected
// called when a guess Button is touched
private OnClickListener guessButtonListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
submitGuess((Button) v); // pass selected Button to submitGuess
} // end method onClick
}; // end answerButtonListener
} // end FlagQuizGame
Create another variable that keeps track of the attempts on the current question. Each time the correct answer is guessed, if number of guesses = 1, increment another counter of how many answers were correctly guessed in one try. Also, after each correct answer, reset the current guesses counter back to 0.
Related
I am creating an application consists of two drop down spinners(Example:Spinner A and Spinner B). By clicking button i want to get subtracted value from spinner A and B with that final subtracted value i want to create table rows with inside edit text fields.i had written some code. When i clicks the button no error was prompting but there was no table creation happening.This is what i did below when user clicks button please help me with this where i did them mistake
get_sheet = (Button)findViewById(R.id.button_get_sheet);
get_sheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner_from_date_text = from_Date.getSelectedItem().toString();
spinner_from_month_text = from_month.getSelectedItem().toString();
spinner_from_year_text = from_year.getSelectedItem().toString();
spinner_to_date_text = to_Date.getSelectedItem().toString();
spinner_to_month_text = to_month.getSelectedItem().toString();
spinner_to_year_text = to_year.getSelectedItem().toString();
from_date.setText(spinner_from_date_text+"/"+spinner_from_month_text+"/"+spinner_from_year_text);
to_date.setText(spinner_to_date_text+"/"+spinner_to_month_text+"/"+spinner_to_year_text);
int value_from = Integer.valueOf(spinner_from_date_text);
int value_to = Integer.valueOf(spinner_to_date_text);
int result_table = value_to-value_from;
sheet.setColumnStretchable(5, true);
for(int i=0;i<result_table;i++)
{
sheet_row = new TableRow(MainActivity.this);
sheet_row.setLayoutParams(new LayoutParams(android.widget.TableRow.LayoutParams.WRAP_CONTENT,android.widget.TableRow.LayoutParams.WRAP_CONTENT));
for(int j=0 ;j<5;j++)
{
edt_text = new EditText(MainActivity.this);
edt_text.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
edt_text.setBackgroundResource(R.drawable.edt);
}
sheet_row.addView(edt_text);
}
sheet.addView(sheet_row);
I am developing a simple questionnaire-like app which includes lots of radio buttons joined into groups and spinners. I have multiple activities (6); some of them having RBs and some Spinners to let the user answer the questions.
The following step, which I have trouble with, is how to fetch lots of selections (of all the radio buttons/choices) and possibly do that in a for loop (so I don't have to initialize each new variable 30+ times in a row for just one activity). I've already assigned IDs to all of the views, but am having a hard time how to actually fetch the selection, initialize a new var corresponding to the selection (let's say radio button 1 in radio group 1 gives me a new variable with a value of 1) and then make the variables available to all of the activities (should I use global when initializing?).
My failed attempt on generating 10 variables for the first "page"
public void goTo2(View v) {
checkRB();
Intent intent1 = new Intent(Vprasalnik1.this, Vprasalnik2.class);
startActivity(intent1);
finish();
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
RadioButton "vRB" + i; //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Put variables into array like a
int size = 9;
RadioButton[] views = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
views[i] = (RadioButton)findViewByID(...);//For example
}
}
Or make a structure :
public class Choise
{
int mRadioButtonChoise;
int mSpinnerChoise;
}
And use something like this:
...
Choise c = new Choise();
c.mRadioButtonChoise = yourRadioButtonID;
c.mSpinnerChoise = youtSpinnerChoiseID;
...
Using a variable to identify a resource:
RadioButton[] rb = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
int id = context.getResources().getIdentifier("vRB" + i, "id", context.getPackageName())
rb[i] = (RadioButton)findViewByID(id);
}
}
If you have an array of RadioButtons then you can get all the values at the same time, however initializing them will have to be manual.
RadioButton rb[];
boolean rbc[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbc=new boolean[200];
rb=new RadioButton[200]();
rb[0]=(RadioButton)findViewById(R.id.rb1);
rb[1]=(RadioButton)findViewById(R.id.rb2);
rb[2]=(RadioButton)findViewById(R.id.rb3);
rb[3]=(RadioButton)findViewById(R.id.rb4);
// many more.
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
rbc[i]=rb.isChecked(); //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Then before starting your intent add all relevant data to it.
So I've managed to cramp up the radio buttons activity, so that it finally works. If anyone is interested - I've used tags in xml code to properly assign values (1, 2 and 3 for each group of buttons) and managed to get an output in my testToast. At least I didn't have to initialize all of the variables manually - I've been saving the values into an ArrayList and then appended to them via StringBuilder.
Thanks to everyone who tried to help - it turned out I've needed a bit more research, testing and teasing my half-awake brain.
btn = (Button) findViewById(R.id.v3_btn1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 1; i <= 36; i++)
{
tmpRGid = "radioGroup_v3q" + i;
tmp2RGid = getResources().getIdentifier(tmpRGid, "id", getPackageName());
RGid = (RadioGroup) findViewById(tmp2RGid);
selectedOption = RGid.getCheckedRadioButtonId();
RBid = (RadioButton) findViewById(selectedOption);
addToIDList.add((String)RBid.getTag());
}
String testToast = "";
StringBuilder builder = new StringBuilder();
builder.append("Vaša izbira (");
for (int z=0; z < addToIDList.size(); z++) {
testToast = addToIDList.get(z);
builder.append(testToast + ", ");
}
builder.setLength(builder.length() - 2);
builder.append(") je bila shranjena.");
Toast.makeText(Vprasalnik3.this, builder, Toast.LENGTH_LONG).show();
I have two arrays :
String []myExpressions = {"20+10","50+50","25+25","10+15"};
String []answers = {"30#","100#","50#","25#"};
When the user clicks the generate button it generates an expression from the array myExpressions and displays it in text-field. Then I require the user to enter the answer using the buttons provided. The answer is displayed in a EditText. When the user enters an answer they should enter a #(like a submit button) and if is the correct answer it should display correct in a text-field. So if the position in the expression array is 1, the correct answer is in the answer array in the same position. How would i check if they are in the same position?
For example: myExpressions[1] correct answer to this is answers[1].
Here is my code:
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
final String []myExpressions = {"20+10","50+50","25+25","10+15"};
final String []answers = {"30#","100#","50#","25#"};
final TextView displayExpression = (TextView) findViewById(R.id.expression);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
displayExpression.setText(myExpressions[random]);
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
// storing the existing number into editText and current text is set
//to current button value
//display.setText(number+btn.getText().toString());
//the total in the editText
}
if (v.getId()== R.id.hash_button){
String userAns = display.getText().toString();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
For starters arrays in Java Begin at Index 0 so therefore , to compare the first items of the Array you should be using something like this to check if things are equal:
EditText myAnswer = (EditText) findViewById(R.id.myAnswer);
String answer = myAnswer.getText().toString();
// Notice my loop starts at 0 because the first index of an array is 0
for(int i = 0 ; i < answers.length; i++)
{
if(answers[i].equals(answer))
{
// Congratulate the User for getting it Right
}
}
It seems as though you have a little bit of a shaky logic. IMHO you should be using a multidimensional Array.
With a multidimensional Array you can essentially set up keys and values.
This is how I think your application should be configures
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5", "9"},
{"20 * 3","60"},
{"99 - 9","90"}};
// Fetch your random question, since we know our questions are the first item in out Array we can use the index [x][0] depending on the index you pull from
String question = multiArray[0][0];
// To do this randomly
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(4) ;
String question = multiArray[random][0];
// Get the Answer from yout EditText
String answer = myAnswer.getText().toString();
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(mutliArray[i][1])
{
// We have found the answer, Congratulate the User
}else{
// Tell them how bad they are since they can't solve simple equations!
// ....joking obviously we would be nice and let them know its not the answer
}
}
In this line
int random = ranGenerate.nextInt(4) ;
why don't you make random an instance variable inside your class? This way you would preserve the index, and you would know which index to use to compare the answer.
I have two identical views with a number of editTexts. In one, pre-defined answers are populated in the editTexts (but not shown to the user). In the second, the user starts with all blank editTexts, and then fills them out in an attempt to make them the same as the pre-defined answers.
So I want to loop through the user's view, checking it against the pre-defined one, until an inequality is found, in which case the method will return false.
My code is below. Inside the onCreate I have a buttonListener (when the user is ready to check answers)
btnSolution.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkAnswer() == true){
Toast.makeText(getBaseContext(), "all good!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getBaseContext(), "no good", Toast.LENGTH_LONG).show();
}
}
});
the checkAnswer() method is then defined as follows
public boolean checkAnswer() {
final int ROW_COUNT = 15;
final int COL_COUNT = 10;
final String ROWS[] = {"R1","R2","R3","R4","R5","R6","R7","R8","R9","R10","R11","R12","R13","R14","R15"};
final String COLS[] = {"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10"};
for(int i=0; i<ROW_COUNT; i++) {
for(int j=0; j<COL_COUNT; j++) {
String a = ROWS[i];
String b = COLS[j];
int editTextBaseId = getResources().getIdentifier("box" + a + b, "id", getPackageName());
int editTextAnswerId = getResources().getIdentifier("boxA" + a + b, "id", getPackageName());
EditText editTextBase = (EditText)findViewById(editTextBaseId);
EditText editTextAnswer = (EditText)findViewById(editTextAnswerId);
String textBase = editTextBase.getText().toString();
String textAnswer = editTextAnswer.getText().toString();
if(textBase.equals(textAnswer)) {
}
else {
return false;
}
}
}
return true;
}
Unfortunately when I try and run this I am getting a crash and the following error in my LogCat
12-17 00:05:02.075: E/SKIA(16370): FimgApiStretch:stretch failed
Any obvious errors?
That's not an error itself. I guess you're using a Samsung as your target device, if so, don't worry about it.
In the other hand, maybe it's better to compare only the strings. All those findViewById are inneficient.
Looking at your code:
EditText editTextAnswer = (EditText)findViewById(editTextAnswerId);
Do you have both views in the same layout, and the one with the answers is hidden? I mean, if you have the view with blank editTexts as the content of your activity, you can't find the editText with the answer as it's in other xml (assuming you did it as a different xml).
I have an activity that generates and displays a GridLayout of custom ImageButtons called MapCells (It's a game map, surprise.) The MapCells are randomly generated and contain some variables that relate to terrain type as well as looking different (the image). What happens when I run my code is that I get my lovely random map, and when I click on the cells they should toast up their id on the screen (a diagnostic aid) as well as getting their stored variables and setText-ing them to some TextViews in the same activity. How it actually works when I click on the MapCells is that they toast the unique id (as expected) and have their unique appearances, but the terrain values that display are of the last MapCell that was generated in all cases. I thought this was the result of my 'for' loop creating all of the MapCells as the variable q (visible in commented out code) which I was just overwriting every loop, so I rewrote it to the code below, however, I am getting the same problem. Other questions I have looked at seemed to indicate that giving them the ids would solve this. Any ideas?
package com.<redacted>
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MapScreen extends Activity implements OnClickListener{
private static int dimen = 110; //the side length of map cells
private int currentFood;
private String currentName;
private MapCell[] storage = new MapCell[18];//keep the cells in here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_screen); //the xml
//It's Randy the randomizer!
Random randy = new Random();
//Generate 6 random MapCells per row for use in our map.
//MapCell q; -this is old and unused now
for(int i=0; i<=5; i++){
//q = new MapCell(randy.nextInt(4), this); //create and randomize
//q.setId(i); //issue identity
storage[i] = new MapCell(randy.nextInt(4), this); //shove it in the array
storage[i].setId(i);
storage[i].setOnClickListener((OnClickListener) this);
//q.setOnClickListener((OnClickListener) this);
((TableRow)findViewById(R.id.mapRow01)).addView(storage[i], dimen, dimen); //add cell to display
}
for(int j=0; j<=5; j++){
//q = new MapCell(randy.nextInt(4), this);
//q.setId(j+6);
//storage[q.getId()] = q; //shove it in the array
//q.setOnClickListener((OnClickListener) this);
storage[j+6] = new MapCell(randy.nextInt(4), this); //shove it in the array
storage[j+6].setId(j+6);
storage[j+6].setOnClickListener((OnClickListener) this);
((TableRow)findViewById(R.id.mapRow02)).addView(storage[j+6], dimen, dimen); //add cell to display
}
for(int k=0; k<=5; k++){
//q = new MapCell(randy.nextInt(4), this);
//q.setId(k+12);
//storage[q.getId()] = q; //shove it in the array
//q.setOnClickListener((OnClickListener) this);
storage[k+12] = new MapCell(randy.nextInt(4), this); //shove it in the array
storage[k+12].setId(k+12);
storage[k+12].setOnClickListener((OnClickListener) this);
((TableRow)findViewById(R.id.mapRow03)).addView(storage[k+12], dimen, dimen); //add cell to display
}
}
public void displayCell(MapCell view){
//get the cell name view and then set its text to be the name of the clicked cell
try{ //we need to try in case it feeds in a non-MapCell view
currentName = storage[view.getId()].getName();
((TextView)findViewById(R.id.mapDisplayName)).setText(currentName);
currentFood = storage[view.getId()].getFood();
((TextView)findViewById(R.id.mapDisplayFood)).setText(String.valueOf(currentFood));
Toast.makeText(this, "Cell " + String.valueOf(view.getId()), Toast.LENGTH_SHORT).show(); //diagnostic line
}
catch (Exception x){
//frowny time
Toast.makeText(this, "Something Broke on cell " + String.valueOf(view.getId()) + " :(", Toast.LENGTH_SHORT).show();
}
}
public void onClick(View v){//when we click a MapCell
displayCell((MapCell)v);// feed it in
}
}
That's the relevant class. I can show you MapCell if you ask, but it's just an ImageButton with a few added variables along for the ride with getters. These variables are set by switch case using the random integer provided in the constructor.
As I see nothing wrong with your code, I'll take a shot in the dark. In your MapCell class, is the variable that holds terrain values defined using the static modifier?