2
下面的代碼將用作定時器。當我的應用程序不加載XML視圖時,我正在測試AsynchTask。我的代碼應該可以工作,但視圖不會打開。我後來做了一些測試,並將TextView變量「display」稍微移動一下,最終得到了顯示的視圖,但按下開始按鈕不起作用......任何人都可以告訴我如何讓TextView更新,正常運行?謝謝!從AsyncTask更改TextView
整個佈局沒有顯示....
public class MainActivity extends Activity {
timer tim = new timer();
boolean running = true;
int milli = 0;
int secs = 0;
int mins = 0;
int hours = 0;
ArrayList<Lap> laps = new ArrayList<Lap>();
TextView display = (TextView) findViewById(R.id.textView1); //whats going on?
LinearLayout lapsView = (LinearLayout) findViewById(R.id.lapsView);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
Button b1 = (Button) findViewById(R.id.start);
b1.setOnClickListener(startTimer);
Button b2 = (Button) findViewById(R.id.stop);
b2.setOnClickListener(stopTimer);
}
catch(Exception e1){
}
}
@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;
}
private OnClickListener startTimer = new OnClickListener() {
public void onClick(View v) {
if(!running){
startWatch();
}
else if(running){
try{
tim.execute(""); //start the task
}
catch(Exception e1){
Toast.makeText(MainActivity.this, "Error starting: "+e1, Toast.LENGTH_LONG).show();
}
}
}
};
private OnClickListener stopTimer = new OnClickListener() {
public void onClick(View v) {
if(running){
stopWatch();
}
}
};
public void startWatch(){
running = true;
}
public void stopWatch(){
running= false;
}
public class timer extends AsyncTask<String, Void, String> {
////NOT WORKING!!!!
@Override
protected String doInBackground(String... params) {
while(true){
while(!running){
///Do Nothing...
}
while(milli < 1000 && running){
running = true;
milli++;
try{
Thread.sleep(1);
}
catch(Exception e1){
System.out.println(e1);
}
if(milli == 1000){
milli = 0;
secs++;
}
if(secs == 60){
secs = 0;
mins++;
}
if(mins == 60){
hours++;
mins = 0;
}
display.setText(milli+":"+secs+":"+mins+":"+hours);
}
}
}
}
}
調試錯誤....
Thread [<1> main] (Suspended (exception RuntimeException))
<VM does not provide monitor information>
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2053
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2154
ActivityThread.access$700(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 146
ActivityThread$H.handleMessage(Message) line: 1260
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 137
ActivityThread.main(String[]) line: 4949
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 511
ZygoteInit$MethodAndArgsCaller.run() line: 1043
ZygoteInit.main(String[]) line: 810
NativeStart.main(String[]) line: not available [native method]
那麼,我該怎麼做呢? – Greg
我的答案有樣品代碼.. –
它的工作原理!謝謝你太多了! – Greg