This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 6 years ago.
I am following a beginner's android development course on Udacity and have seemed to come across a simple error, though I cannot for the life of me figure it out or how to search for it.
There is just a number with an increment and decrement button on the sides to change it. The problem comes either when I call the displayQuantity method or when it tries to set the text of the quantityTextView. The value of quantity does change, but the app closes before it changes on the screen.
public void increment (View view){
quantity = quantity + 1;
displayQuantity(quantity);
}
public void decrement (View view){
quantity = quantity - 1;
displayQuantity(quantity);
}
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(quantity);
}
Change to
quantityTextView.setText(Integer.toString(quantity));
TextView.setText() is overloaded. The version that takes an integer expects a resource identifier for a string resource (e.g. R.string.something), but the value you are passing doesn't correspond to any such resource.
Related
In my app, I want a counter from 0 to 8 to decide the number of players in a game.
Below there are 8 possible fields to write a name inside, which are all set to invisible. If the players-counter is set to 3 players, there should be the first 3 fields visible. Depending on the actual number of the counter, the visibility of the fields changes (1player = first field, 5 players = first 5 fields).
When the +1 (player) button is clicked, a certain method is activated. I tried to run a for-loop everytime the button is clicked. In this for-loop from 0 to "whatever amount" (max. 8 players) the actual fields should be found with "findById" and set to visible.
I tried it with a string resource (.xml) and I can get the text of the resource but with my thought process, I have to update the string resource to every number of the field (if 3 players: "field_" + "1", "field_" + "2", "field_" + "3").
How can I get and (most importantly) set/update a string resource for this specific purpose?
(Switch is too inefficient and I can't use a string with the findViewBy Id()-method by updating the String (not string resource) like mentioned before.
Please help, and accept the fact that I'm new to Android Studio for one week!)
You can use "getIdentifier" which takes a String parameter. So you can set the type as "id" in the second parameter of this method. This method returns the id of the view you want, but beware, it will throw a "FATAL EXCEPTION" if the id of the View doesn't exist. With this id, you can use findViewById to fetch the TextView and change its visibility. The "getIdentifier" method can be called from the "getResources()" method.
Below you can see what it would be like to make visible a TextView that has the id "textView1":
int id = getResources().getIdentifier("textView1", "id", getPackageName());
TextView textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
Below you can see how you would make 8 TextView with id 1 to 8 visible:
TextView textView;
for (int i = 1; i <= 8; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
So, just put the limit at i <= x , with x being the limit of players who will play:
TextView textView;
for (int i = 1; i <= totalPlayers; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
Do you just want to make some EditTexts visible and others not? Personally I'd keep it simple, do the lookups once (in onCreate or wherever) and store the references in a list. Then when you need to display n fields, you can just iterate over the list and set the first n to VISIBLE and the rest to INVISIBLE.
I feel like it's fine to just list all the EditText IDs (R.id.field_1 etc) and generate your list of actual Views from that, but if that repetition bothers you, there's a few things you could do. Like:
set a tag attribute on each field in the XML, and use findViewWithTag to look them up, generating the lookup strings programmatically, like "field_" + i
do a similar thing with the resource ID, like in #Moises's answer
lookup their containing layout, use getChildCount and [getChildAt] to iterate over the views in that layout, and use isInstance to collect all the EditTexts in order3
create and add the EditTexts in code - you probably don't want to do this, but you could!
I'm not really sure what you mean about the string resource or what you're trying to do - I'd honestly just make a list of R.id.field_1 etc, iterate over that to do findViewById on each and store those in a new list, and you're done. Also my Java's a bit rusty so sorry no example code!
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
OUT OF MEMORY ERROR ON THE LINE THAT ADDS THE OBJECT TO THE ArrayList - LAST LINE
I want every time I click the button saveScore, the name of the first team selected from the first spinner, the name of the second team selected from the second spinner, the score from the first editText and the score from the second editText to be the arguments of my class object.
teamOneScore & teamTwoScore are two EditText where I enter the score for each team selected from the spinners and arrList is my ArrayList of objects .
I have a class - TeamsViewModel with 4 members of type String: team1Name, team2Name, team1Score, team2Score.
saveScore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean resultAddTeamOneScore = addTeamOneScore(weakActivity, teamOneScore.getText().toString().trim(), teamTwoScore.getText().toString().trim());
boolean resultAddTeamTwoScore = addTeamTwoScore(weakActivity, teamTwoScore.getText().toString().trim(),teamOneScore.getText().toString().trim());
if (resultAddTeamOneScore && resultAddTeamTwoScore) {
dialog.dismiss();
}
/** save the teams selected from the spinner */
String selectedT1 = teamOneSpinnerSelected(teamOneSpinner);
String selectedT2 = teamTwoSpinnerSelected(teamTwoSpinner);
while (!selectedT1.equals(selectedT) {
/** add to the ArrayLists of objects the teams selected and their's score*/
arrTeam.add(new TeamsViewModel(selectedT1, teamOneScore.getText().toString().trim(), selectedT2, teamTwoScore.getText().toString().trim()));
}
}
});
Change
while (selectedT1 != selectedT2)
to
while (! selectedT1.equals(selectedT2))
The condition (selectedT1 != selectedT2) may be always true, although the two Strings have identical content, and you have an endless loop leading to the OutOfMemoryError. In Java Strings must not be compared using != or ==, always use equals().
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Good day everyone, so i am writing a quiz app and score is based on what the user selects. I used radio buttons, check box and edit text tags for answering questions. When the user clicks a radio button, or a check box, the score updates, but when the user enters the correct text in the EditText field, the score does not update. I used an if else statement to check if the string entered matches an answer.
public void startFinalScreen(View v) {
EditText text = (EditText) findViewById(R.id.edit_text_view_answer);
int questionNineScore = getIntent().getIntExtra("GNS", 0);
int finalScore = questionNineScore;
String answer = "William Shakespeare";
if (text.getText().toString() == answer) {
qNineScore = qNineScore + 1;
}
finalScore = qNineScore;
}
I used .getIntent() to get score from a previous activity. After i do this, the score does not add +1 even after typing the correct answer.
Instead of
text.getText().toString() == answer
use
if (text.getText().toString().equals(answer)) {
qNineScore = qNineScore + 1;
}
This question already has answers here:
Why does the division of two integers return 0.0 in Java? [duplicate]
(6 answers)
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
In this block of code which is inside a broadcast receiver I have a calculation.
My goal is to get a battery bar with the correct amount of Green inside it. So for the Green I have an image which is essentially a block of solid green. I am not sure if this is the best way to do this but I decided to resize the block using this calculation:
(Height of Block) * (Battery Level/100)
The actual code:
BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 100);
percentageView.setText(String.valueOf(level)+"%");
int height_val = (363) * (level / 100); //<-- That's the int which always returns 0
Log.e("MyTag", String.valueOf(height_val).toString());
Log.e("MyTAgg", String.valueOf(363 * (level/100)));
bar.requestLayout();
bar.getLayoutParams().height= height_val;
}
};
And it is inside a class. It's registered in the class not in the manifest. My Text View shows me the battery percentage but my Tags always show me that my calculations returns 0. Please do help me understand. Why does this calculation return 0?
Thank you.
I am new to Android application development and am trying to find a way to proceed through a series of screens that take in user input. I'm making a small math game where the user would answer basic two integer addition problems. So far the main menu is created. It has a New Game button which launches my GameActivity and it runs just fine for one math problem. However, after the user inputs their answer to the simple math problem, I would like to be able to continue on to another math problem once the user had answered the current problem and the method would return a correct/incorrect value. Initially I thought of doing something like a basic FOR loop from within the GameActivity :
for(int i = 0; i < 10; i++){ gameMethod(); }
gameMethod() is a JAVA method that simply generates 2 random numbers, adds them to get the correct answer and then prompts the user using an EditText field to type in their guess. It displays the random numbers and answer using TextView boxes created in an XML layout file.
Each call to the gameMethod would, at least I think, just re-input the randomized numbers into the TextView fields displayed on the screen each iteration. I really don't care what the previous numbers were so I figured I would just overwrite them. I wan't able to get the code to do that though. I put in a Log.d() statement or two and found that the FOR loop was in fact running through correctly 10 times, but it was not waiting for user input before firing off its next gameMethod().
In doing some looking around, I found the startActivityForResult() and wondered if this was a more appropriate way of approaching this. So in this way, I foresee having three Activities, the Main menu which calls the GameActivity which would then iterate through, say 10 times, each iteration calling yet another activity GameScreenActivity which would actually put the numbers on the screen, read in user input and then return 1 for a correct answer and 0 for an incorrect answer. So far in reading up on StarActivityForResult() I'm getting somewhat confused by the process and wondered if this was even a plausible path to be exploring.
Again, I'm very new at this Android programming and appreciate any and all help that I can get.
Thank you.
Sorry for not including the gameMethod() initially, I've added it below.
// Create and initialize arrays of integers
int[] a = {0,1,2,3,4,5,6,7,8,9,10};
int[] b = {0,1,2,3,4,5,6,7,8,9,10};
// Creates random number generator
Random randy = new Random();
// Generates two random values to add
int r1 = randy.nextInt(10);
int r2 = randy.nextInt(10);
// Calculates correct answer
int an = a[r1] + a[r2];
// Displays 1st number
TextView number1 = (TextView) findViewById(R.id.firstNumber);
number1.setText(Integer.toString(a[r1]));
// Displays 2nd number
TextView number2 = (TextView) findViewById(R.id.secondNumber);
number2.setText(Integer.toString(b[r2]));
// Displays correct answer
TextView answer1 = (TextView) findViewById(R.id.answerNumber);
//hide answer until user puts in theirs
answer1.setVisibility(View.INVISIBLE);
answer1.setText(Integer.toString(an));
//hide the answer place holder value
TextView uAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber);
uAnswerDisplay.setVisibility(View.INVISIBLE);
//Get the EditText field that the user will input their answer to
EditText inputText = (EditText) findViewById(R.id.userInput);
//set up a listener to run once the ENTER key is hit after their answer has been entered
inputText.setOnKeyListener(new EditText.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
//only go on the ENTER key when pressed DOWN
if((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
EditText innerInputText = (EditText) findViewById(R.id.userInput); //get the EditText box reference
TextView innerUAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber); //get the TextView box that the answer will go in
String inputString = innerInputText.getText().toString(); //capture the user's input
int uAnswer = Integer.parseInt(inputString); //parse user answer to an integer
int cAnswer = Integer.parseInt((((TextView) findViewById(R.id.answerNumber)).getText()).toString());
innerUAnswerDisplay.setText(Integer.toString(uAnswer)); //display the string after converting from integer
//change colors of text based on correctness
if (uAnswer == cAnswer){ innerUAnswerDisplay.setTextColor(Color.GREEN); } //green for correct
else { innerUAnswerDisplay.setTextColor(Color.RED); } //red for incorrect
innerUAnswerDisplay.setVisibility(View.VISIBLE); //make the user input answer visible
TextView innerAnswer1 = (TextView) findViewById(R.id.answerNumber);
innerAnswer1.setVisibility(View.VISIBLE); //hide answer until user puts in theirs
} //end of if
return false; //return false
} //end of onKey
}); //end of setOnKeyListener
Sorry for all the edits, I couldn't get the edits to include the code and post correctly so I broke it up into chunks and added a little at a time.
From what you say, I'd consider two ways of letting the user answer questions:
have an onclick listener on the input EditText that triggers a new loop;
have a dialog activity that gets started in the beginning of the loop, which prompts the user for a new answer, your game activity would receive the answer via its onActivityResult.