Reputation: 33
public class MainActivity extends ActionBarActivity {
Handler myHandler;
Runnable myRunnable;
TextView tv;
int no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHandler.post(myRunnable);
}
public void initialize(){
no = 10;
tv = (TextView) findViewById(R.id.textView1);
myRunnable = new Runnable() {
@Override
public void run() {
tv.setText(Integer.toString(no));
no--;
if(no != 0)
myHandler.postDelayed(myRunnable, 1000);
}
};
}
}
I tried forcing the Orientation to portrait to run this code but it failed again.
Whenever i try a handler to basically change the view text after every second i get this error.
Am new to Android development a college student so bear with my mistakes if any.
Thank you in advance.
The logs are below.
10-04 04:22:35.750: E/AndroidRuntime(2123):FATAL EXCEPTION: main
10-04 04:22:35.750: E/AndroidRuntime(2123):java.lang.RuntimeException: Unable to start activity ComponentInfo{we.funnycorps.handlerpractise/we.funnycorps.handlerpractise.MainActivity}: java.lang.NullPointerException
10-04 04:22:35.750: E/AndroidRuntime(2123):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-04 04:22:35.750: E/AndroidRuntime(2123):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
Upvotes: 0
Views: 3127
Reputation: 1413
you have not used the initialize()
function in oncreate ,below code use ,you will get the expected result.
public class Dummycls extends Activity {
Handler myHandler;
Runnable myRunnable;
TextView tv;
int no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
//myHandler.post(myRunnable);
}
public void initialize(){
no = 10;
tv = (TextView) findViewById(R.id.pinchTitleText);
myHandler=new Handler();
myRunnable = new Runnable(){
public void run() {
tv.setText(Integer.toString(no));
no--;
if(no != 0)
myHandler.postDelayed(myRunnable, 1000);
//handler.postDelayed(r, 1000);
}
};
myHandler.post(myRunnable);
}
}
Upvotes: 2
Reputation: 14398
initialize myHandler
as
Handler myHandler = new Handler();
i.e. replace
Handler myHandler;
to
Handler myHandler = new Handler();
And call initialize()
method before myHandler.post(myRunnable);
as
initialize();
myHandler.post(myRunnable);
Upvotes: 1
Reputation: 258
myHandler is not being initialised, and since the initialize() method isn't being called in your onCreate(), myRunnable is also not initialised before you try to post it.
Upvotes: 0