I use the debugger to find that the value of townHallLvl stays 1 at the end
Please help
int townHallLvl = 1;
public void addTownHall(View v){
if (townHallLvl == 11) {
Toast.makeText(this, "You can't have more than Town Hall lvl 11!!!", Toast.LENGTH_SHORT).show();
return;
}
add(townHallLvl);
TextView townHallText = (TextView) findViewById(R.id.town_hall_lvl);
townHallText.setText(String.valueOf(townHallLvl));
}
public int add(int lvl){
int ans = lvl + 1;
return ans;
}
townHallLvl = add(townHallLvl);
You probably missed to assign back the value to townHallLvl.
Related
I've got a [DONE] button that's supposed to check 2 entries's results. One of them is an [EditText--inputType:number] and the other is a [TextView] that increments when a certain button is pressed.
What I'm trying to do is check whether the EditText has an integer or is null, and check the contents of the TextView. if they both are greater than Zero. I add them up and send the total to my main activity. Here's the code i have so far.
public void returnbtn(View view) {
// Initialize insert textView
EditText insertcountBtn = findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
// get added int stuff from the insert textField
int insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
// convert counter textView to int.
Integer givencountInt = Integer.parseInt(givencountString);
if (givencountInt <= 0 && insertcountInt <= 0){
Total = 0;
} else if (givencountInt > 0 && insertcountInt <= 0) {
Total = givencountInt;
} else if (givencountInt <= 0 && insertcountInt > 0) {
Total = insertcountInt;
} else if (givencountInt > 0 && insertcountInt > 0){
// Add Counter textView and Insert textView to an Int Total
Total = givencountInt + insertcountInt;
}
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
// Pass the current number to the push-up Counter activity.
beginPushup.putExtra(TOTAL_DONE, Total);
// Start mainActivity.
startActivity(beginPushup);
}
The problem i'm having is with either textView or EditText i'm not sure. All i know is that if i fill them both and click done it adds them up and transfers the total to mainActivity as expected. If I add values to EditText and leave TextView with 0 it also does what it's meant to do. But if I increment TextView and leave EditText blank, it does not transfer my TextView integer and crashes app.
Could i be detecting the editText wrong, because i think that's the reason.
If so what's the right way?
----- First && Second Answer Edits -----
int insertcountInt;
String insertcountString =
String.valueOf(insertcountBtn.getText());
try {
insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
if (insertcountInt <= 0 || insertcountString == " ") Total =
givencountInt;
if (insertcountInt > 0 ) Total = givencountInt +
insertcountInt;
} catch (NumberFormatException e) {
insertcountInt = 0;
}
Good news is no more crash, but unless I fill the EditText with something, I'm not receiving my Integer in mainActivity. This is getting interesting. * I think it's a play of the if statements which I've restructures, but no luck so far. *
----- Updated Working Code For Any Future Requests -----
public void filledChecker() {
// Initialize insert textView
EditText insertcountBtn =
findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
int insertcountInt = 0;
int givencountInt = 0;
// get added int stuff from the insert textField
if (!TextUtils.isEmpty(insertcountBtn.getText()) &&
TextUtils.isDigitsOnly(insertcountBtn.getText())) {
insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
}
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
if (!TextUtils.isEmpty(givencountString) &&
TextUtils.isDigitsOnly(givencountString)) {
givencountInt = Integer.parseInt(givencountString);
}
if (insertcountInt <= 0) {
Total = givencountInt;
}
if (insertcountInt > 0) {
Total = givencountInt + insertcountInt;
}
}
public void returnbtn(View view) {
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
filledChecker();
Integer current_Id = getIntent().getIntExtra(GIVEN_ID, 0);
// Pass the current number to the push-up Counter activity.
if (current_Id == 1) beginPushup.putExtra(TOTAL_P_DONE,
Total);
if (current_Id == 2) beginPushup.putExtra(TOTAL_S_DONE,
Total);
if (current_Id == 3) beginPushup.putExtra(TOTAL_C_DONE,
Total);
if (current_Id == 4) beginPushup.putExtra(TOTAL_SQ_DONE,
Total);
beginPushup.putExtra(GIVEN_ID, current_Id);
// Start mainActivity.
startActivity(beginPushup);
}
I As you can see I ended up dividing the if-logic from the Intent to Transfer to main Activity. This way they're both simple. And using the Do Not Repeat Yourself i did the same thing to the rest of my other buttons as you can see with all the if's in [returnbtn] method. I also simplified the if statement aside from the ones i was helped with. I ended up needing 2 if statements to manage getting a total from the 2 entries. Thanks again for the help everyone. Ohh the try-except didn't seem necessary so i deprecated them. as the app gets more complex i'll add them if necessary.
As the other answer explained, the issue with your code is that when the EditText is blank then parsing "null" is causing exception. So you just have to insure that if content is null then just use 0(Zero) value. You can try this:
public void returnbtn(View view) {
// Initialize insert textView
EditText insertcountBtn = findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
int insertcountInt = 0;
int givencountInt = 0;
// get added int stuff from the insert textField
if (!TextUtils.isEmpty(insertcountBtn.getText()) && TextUtils.isDigitsOnly(insertcountBtn.getText())) {
insertcountInt = Integer.parseInt(insertcountBtn.getText().toString());
}
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
if (!TextUtils.isEmpty(givencountString) && TextUtils.isDigitsOnly(givencountString)) {
givencountInt = Integer.parseInt(givencountString);
}
if (givencountInt <= 0 && insertcountInt <= 0){
Total = 0;
} else if (givencountInt > 0 && insertcountInt <= 0) {
Total = givencountInt;
} else if (givencountInt <= 0 && insertcountInt > 0) {
Total = insertcountInt;
} else if (givencountInt > 0 && insertcountInt > 0){
// Add Counter textView and Insert textView to an Int Total
Total = givencountInt + insertcountInt;
}
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
// Pass the current number to the push-up Counter activity.
beginPushup.putExtra(TOTAL_DONE, Total);
// Start mainActivity.
startActivity(beginPushup);
}
TextUtils is a class provided in Android Framework.
This will check for if the content is not empty and also digits only. You can obviously omit the digit check if you are sure that only number will be the input of your edit text.
Because when your EditText is empty, it has no numerical value.
You can do
Integer.parseInt(insertcountBtn.getText().toString());
when the input is blank; there's no Integer value there, because there's nothing at all, so it's going to throw a NumberFormatException.
You can do the following to make sure it has a value (default will be 0 on failure):
int insertedcountInt;
try {
insertedCountInt = Integer.parseInt(insertcountBtn.getText().toString());
} catch (NumberFormatException e) {
insertedCountInt = 0;
}
The issue here is you are defining editText to check for only interger: you did not put the conditional statement for the cases like if String was entered, if editText is blank, it contains String. Hence, you may want to put something like;
String editTextString = String.valueOf(insertcountBtn.getText());
if (editTextString == "") {
//do something
}
Alternatively,
String editTextString = insertcountBtn.getText().toString();
if (editTextString == "") {
//do something
}
I'm trying to get different ID with for. What I have is a CardView with diferent IDs for each card and I would like to get data when clicked.
I have done this:
public void setToggleEvent(final GridLayout mainGrid) {
for ( int i = 0; i < mainGrid.getChildCount(); i++){
count = i;
final CardView cardView = (CardView)mainGrid.getChildAt(i);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cardView.getCardBackgroundColor().getDefaultColor() == -1) {
for (int f = 0; f < mainGrid.getChildCount(); f++){
if (f == count) {
int index = f;
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
}
}
//canvi color de fons
cardView.setCardBackgroundColor(Color.parseColor("#FF6F00"));
foodData = foodName.toString();
selectedVegetables.add(foodData);
} else {
cardView.setBackgroundColor(Color.parseColor("#FFFFFF"));
Toast.makeText(VegetablesActivity.this, "Food Selected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Each card has a ID called: food0, food1, food2....
As you can see in the code I did this to get the IDs:
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
and then:
foodData = foodName.toString();
selectedVegetables.add(foodData);
But when I run it says that foodName is null ( java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference)
and is in this line where the error shows up
foodName.getText();
Any idea?
Sorry for my bad english, it's not my native lenguage, hope everyone could understand this.
I surprised! this is not actually logical!
foodName = findViewById(resID);
int resID not provide you like this: "R.id.exampleId" type of id.
resID Only provide you a integer value.
How can I get to iterate through this ArrayList algorithm so that I can change the background of an imageView every time I input a code... E.g. Code = "123456" | Background_1 shows, Code = "123456" | Background_2 shows ...
enter = (ImageButton) findViewById(R.id.enter);
input = (EditText) findViewById(R.id.editText2);
punch_back_1 = (ImageView) findViewById(R.id.imageView6);
punch_back_2 = (ImageView) findViewById(R.id.imageView7);
punch_back_3 = (ImageView) findViewById(R.id.imageView8);
punch_back_4 = (ImageView) findViewById(R.id.imageView9);
final ArrayList<ImageView> array_image = new ArrayList<>();
array_image.add(punch_back_1);
array_image.add(punch_back_2);
array_image.add(punch_back_3);
array_image.add(punch_back_4);
enter.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
String code = input.getText().toString();
int i = 0;
if (code.equals("123456")) {
i++;
array_image.get(i).setImageResource(R.drawable.punch_front);
Toast.makeText(getApplication(), "Awarded 1 new punch", Toast.LENGTH_LONG).show();
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
input.setText(" ");
}
return false;
}
});
I've tried this both:
for (int i = 0; i < 4; i++)
{
if (code.equals("123456"))
{
array_image.get(i).setImageResource(R.drawable.punch_front);
Toast.makeText(getApplication(), "Awarded 1 new punch", Toast.LENGTH_LONG).show();
}
}
int i = 0;
while (i < i)
{
array_image.get(i).setImageResource(R.drawable.punch_front);
Toast.makeText(getApplication(), "Awarded 1 new punch", Toast.LENGTH_LONG).show();
i++;
}
Which, if I am not mistaken does the same thing.
The below line of code eventually worked for me. onTouch Action_UP was my culprit. Using input.setText(null); did the same effect I wanted and preserved my sanity...
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = input.getText().toString();
if (code.equals("123456") && index < array_image.size()) {
array_image.get(index).setImageResource(R.drawable.punch_front);
index++;
Toast.makeText(getApplication(), "Awarded " + index + " new punch", Toast.LENGTH_LONG).show();
input.setText(null);
}
}
});
EDIT: I seem to have misunderstood your question. It looks as if you want to have the image appear only once per fire event.
Doing this would require you do two things.
Keep count of the index at which you'll be changing.
Increment the index after use.
Also, you'll need to insure you do not go out of bounds as well of course.
First create a counter for the index as a member.
private int index = 0;
Next you'll want to do what you were doing before almost. In your event listener:
if(code.equals("123456") && index < array_image.size())
{
array_image.get(index).setImageResource(R.drawable.punch_front);
index++;
}
This should keep track of the current index, increment its position for the next event, and after you've gone through your items in the array, it shouldn't give you any exception errors when you go out of bounds and try to fire the event again.
Below is the code I use. Its working til 3 clicks only the succeeding clicks doesn't add "continuously" like the normal scoring in a game. Another problem is that I don't know how to save the score after the time is up. I am thinking of using the data (saved score) for displaying the best score at the end of every game. Any suggestion will be highly appreciated.
MainActivity.java
//CALCULATE SCORE
//declare a boolean variable for score
private int optionTxtView = 0 ;
private int addClick = 0 ;
private void calculate(){
x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
z = x + y;
score.setText(Integer.toString(z));
}
private void calculate2(){
x = Integer.parseInt(score2.getText().toString().replaceAll("\\s",""));
y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
z = x + y;
score.setText(Integer.toString(z));
}
private void calculate3(){
x = Integer.parseInt(score2.getText().toString().replaceAll("\\s",""));
y = Integer.parseInt(score3.getText().toString().replaceAll("\\s",""));
z = x + y;
score.setText(Integer.toString(z));
}
//search
public void viewWord(View view)
{
String s1= search.getText().toString();
String s2= dbHelper.getData(s1);
if(optionTxtView == 0){
//display the score on textview1
tv2.setText(s2);
optionTxtView = 1;
}
else{
if(optionTxtView == 1){
//display the score on textview2
tv3.setText(s2);
optionTxtView = 0;
}
}
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
text.clearComposingText();
//clicks = calculate to be use
if(addClick == 0){
calculate();
score2.setText(score.getText());
addClick = 1;
text.clearComposingText();
}
else{
if(addClick == 1){
calculate();
score2.setText(score.getText());
addClick = 2;
text.clearComposingText();
}
else{
if(addClick == 2){
calculate2();
score2.setText(score.getText());
addClick = 3;
text.clearComposingText();
}
else{
if(addClick == 3){
calculate3();
score3.setText(score.getText());
addClick = 2;
text.clearComposingText();
}
}
}
}
}
to save the scoer you can use SharedPrefrences:
to save your score:
(gameData is the string to later use to get the sharedPrefrences)
SharedPreferences myData= getSharedPreferences("gameData", 0);
SharedPreferences.Editor editor = myData.edit();
editor.putInt("gameScore", myGameScore);
editor.commit;
to load your score:
SharedPreferences myData= getSharedPreferences("gameData", 0);
int myScore = myData.getInt(gameScore, 0);
after doing so, "myScore" will contain the score that you save (or 0 for default value if you didn't save any score before).
about the first part of your question - I didn't andestood what you asked...
so I believe I am overthinking this but I want to double check.
I am getting my TextView from my EditText widget.
addMileage.setOnClickListener(new OnClickListener() {
#Override
public void OnClick(View v) {
if (isErase) {
nextMileage.setText(mileageInput.getText().toString());
} else {
nextMileage.setText("");
}
isErase = !isErase;
}
How can I take what the user enters in the EditText then automatically take the number entered and + 3500. Then display in TextView?
int result=Integer.parseInt(mileageInput.getText().toString())+3500;
nextMileage.setText(result+"");
You can do like this
onClick
String s = your_editText.getText().toString();
if (!s.trim().equals("")
{
int i = Integer.parseInt(s);
int sum = i + 3500;
your_textView.setText(" " + sum);
}
else
your_textView.setText("Please enter the number");
Assuming the code you have works (you didn't say it doesn't work), you can edit the if body as
if (isErase) {
String mileageStr = (Integer.parseInt(mileageInput.getText().toString()) + 3500) + "";
nextMileage.setText(mileageStr);
}
Integer.parseInt() allows you to convert a string to an integer quickly.