Reputation: 1340
Im writing code to display a counter that increments by 1 every second.
The app is getting forced closed before running with the error -
thread exiting with uncaught exception and No package identifier when getting value for resource number
public class MainActivity extends Activity {
Handler hand = new Handler();
TextView ti;
int i =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ti = (TextView) findViewById(R.id.textView);
hand.postDelayed(run, 1000);
}
Runnable run = new Runnable() {
@Override
public void run() {
i++;
ti.setText(i);
}
};
}
What wrong am I doing ?
Upvotes: 0
Views: 3132
Reputation: 3621
If you need a precise timer, you should calculate a difference, from when started a timer, increment a variable in every call is not a accurate solution, here is the code, if you want a precise timer
private long startTime;
private final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.textView);
startTime = System.currentTimeMillis();
handler.post(new Runnable() {
@Override
public void run() {
long diff = System.currentTimeMillis() - startTime;
textView.setText(Long.toString(diff / 1000));
handler.postDelayed(this, 1000);
}
});
}
Upvotes: 1
Reputation: 2737
The method textView.setText(int id)
takes an int as parameter. For e.g. R.string.app-name
. When you pass i
as parameter, it will check for id i
in strings.xml
. TextView
also provides an overloaded method setText(CharSequence text)
, which you can use here.
textView.setText(""+i);
or textView.setText(String.valueOf(i));
Upvotes: 1
Reputation: 369
ti.setText(i)
is trying to resolve a resource by the value of i.
Try ti.setText(String.valueOf(i));
instead.
Upvotes: 1