从AsyncTask更改TextView

时间:2014-02-24 03:11:29

标签: android multithreading android-asynctask

以下代码将作为计时器。当我的应用程序根本不加载XML视图时,我正在测试AsynchTask。我的代码应该可以工作,但视图没有打开。我后来做了一些测试并将TextView变量“显示”移动了一下,最终得到了显示的视图,但按下开始按钮不起作用...任何人都可以告诉我如何让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]

1 个答案:

答案 0 :(得分:6)

您的asyncTask无法更新doInBackground方法上的UI。为此,您需要从publishProgress致电doInBackground并更新TextView

    public class timer extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        while(true){
            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;
                }

                this.publishProgress(milli+":"+secs+":"+mins+":"+hours);
            }
        }
    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        TextView display = (TextView) findViewById(R.id.textView1);
                 display.setText(values[0]);
    }

}