我想爲Android編碼一個計時器,但我遇到處理程序的問題。此行:爲什麼此代碼拋出NullPointerException?
handler.post(new Runnable(){
...正在觸發NullPointerException。爲什麼?
public class HomeFragment extends Fragment {
private int stunde,minute,sekunde;
private TextView textfield;
private Button buttonStart,buttonStop;
private Handler handler;
private boolean Running = true;
private Runnable runnable;
private Thread thread;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
buttonStart =(Button) rootView.findViewById(R.id.button1);
buttonStop = (Button) rootView.findViewById(R.id.button2);
buttonStop.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
thread.stop();
}
});
textfield = (TextView) rootView.findViewById(R.id.startZeit);
buttonStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Running = true;
runnable = new Runnable(){
@Override
public void run() {
while(Running){
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
e.printStackTrace();
}
handler.post(new Runnable(){
@Override
public void run(){
sekunde+=1;
if(sekunde == 60){
minute +=1;
sekunde = 0;
}if(minute == 60){
stunde +=1;
}
textfield.setText(String.format("%02d",stunde)+" : "+String.format("%02d", minute)+" : "+String.format("%02d",sekunde));
}
});
}
}
};
thread = new Thread(runnable);
thread.start();
handler = new Handler();
}
});
return rootView;
}
}`
我做到了,位於「thread.start();」之下。 - 你能告訴我在哪裏我需要初始化它嗎? – user3057253
只需移動這一行:handler = new Handler();到另一個地方。在onCreateView開始的時候做好。或者更好的是把它放在onCreate方法中。 –
感謝Emil,現在他告訴我java.lang.UnsupportedOperationException在thread.stop(); – user3057253