Reputation: 79
I am just a beginner in android development. I came by this error, when i try to set the text using ".setText()"
for a text view it says it may produce null pointer exception. I am stuck and don't know what to do!
Please please please Help Me Out guys!
Thanks in advance!!!
private void runTimer()
{
final TextView timeView = (TextView) findViewById(R.id.display_time);
final Handler handler =new Handler();
handler.post(new Runnable(){
@Override
public void run() {
int hours = seconds/3600;
int minutes = (seconds%3600)/60;
int secs = seconds%60;
String time = String.format(Locale.US,"%d:%02d:%02d",
hours, minutes, secs);
timeView.setText(time);//this is where i am getting the warning!
if (running) {
seconds++;
}
handler.postDelayed(this,1000);
}
});
}
Upvotes: 0
Views: 5286
Reputation: 801
Make sure you call runTimmer() after setContentView or if in fragment in onViewCreated()
Make sure id: display_time is actually the real id of the TextView you want to use, check the xml file.
Only the Ui Thread can make changes to the views, so you need to call runOnUiThread(new Runnable());
Upvotes: 0
Reputation: 325
Check R.id.display_time
if it is pointing to the TextView
in the same layout. as your activity.
Upvotes: 1
Reputation: 60081
Perhaps you could wrap a check around it as below, for the peace of mind.
private void runTimer()
{
final TextView timeView = (TextView) findViewById(R.id.display_time);
final Handler handler =new Handler();
handler.post(new Runnable(){
@Override
public void run() {
int hours = seconds/3600;
int minutes = (seconds%3600)/60;
int secs = seconds%60;
String time = String.format(Locale.US,"%d:%02d:%02d",
hours, minutes, secs);
if (timeView != null) {
timeView.setText(time);//this is where i am getting the warning!
}
if (running) {
seconds++;
}
handler.postDelayed(this,1000);
}
});
}
In the event that timeView
is null for any reason (your activity ended?), no NPE will be thrown.
Upvotes: 1