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的:的NullPointerException當處理程序,用於更新進度
了java.lang.RuntimeException:無法實例活動ComponentInfo {com.zxy.handlerpbtest/com.zxy.handlerpbtest.MainActivity}:JAVA。 lang.NullPointerException
你加入這個活動androidMenifest? –
將按鈕和進度條放入onCreate –
ContentView中,而活動的創建沒有通過findViewById()方法獲得初始化,因此需要在onCreate()活動中全局/ localy聲明它並進行初始化。 – Ajinkya