public class MainActivity extends Activity {
Button button = (Button)findViewById(R.id.btn);
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateHandler.post(updateThread);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Handler updateHandler = new Handler(){
public void handleMessage(Message msg) {
bar.setProgress(msg.arg1);
updateHandler.post(updateThread);
};
};
Runnable updateThread = new Runnable() {
int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("------------");
i = i+10;
Message msg = updateHandler.obtainMessage();
msg.arg1 = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateHandler.sendMessage(msg);
if (i==100) {
updateHandler.removeCallbacks(updateThread);
}
}
};
}
Logcat:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.zxy.handlerpbtest/com.zxy.handlerpbtest.MainActivity}: java.lang.NullPointerException