Reputation: 31
When I try to run the code it just crashes. Before I was using:
myTextView.setText(Counter)
Which was working but now when I try to make it easier and more efficient it does not work by using a method. Why?
I am trying to make a tycoon app and so I want to use a method so it is easier to display the amount of money the user has when they are playing the game. In the method, it would be much cleaner to make calculations.
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Counter = Counter(Counter);
Display(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
Bundle store = new Bundle();
store.putInt("count", Counter);
}
public int Counter(int Counter) {
Counter++;
return Counter;
}
public void Display(int Counter) {
myTextView.setText(Counter);
}
}
Upvotes: 1
Views: 60
Reputation: 774
just use myTextView.setText(Counter+"");
setText(int)
- > this method finds string from resource.
Upvotes: 0
Reputation: 11642
Above all the answer are correct, that if we give String value to the textView it will work fine, so giving int value to the text view is wrong.? Answer is No
Then what the root cause? The reason is, if you set int value, it will consider as the resource id (see the API), so it will try to find the relevant resource. mostly it will not find any value, it will give resource not found exception.
How we can solve this issue, If you are sure that the value is not the resource is, just convert int value to string, and set it to the TextView it will work fine.
Upvotes: 0
Reputation: 53
To set text on TextView you have to use setText() method And this method takes string as a parameter So You have to parse int to string
Upvotes: 0
Reputation: 1571
you have a mistake in your code probably in this:
public void Display(int Counter) {
myTextView.setText(Counter);
}
Try change to:
public void Display(int Counter) {
myTextView.setText(String.ValueOf(Counter));
}
Upvotes: 1