AsyncTask:无法从publishProgress更新UI。错误:只有创建视图层次结构的原始线程才能触及其视图。

时间:2015-11-28 13:58:58

标签: java android android-asynctask

Developer.Android说PublishProgress驻留在UI线程中,因此我应该能够从发布进度中改变UI。

然而,我收到此错误:

android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图

关于本准则:

致电活动

public class AttendanceOperations extends AppCompatActivity {

TextView remaningTimeTV;
databaseTimeTableClass aDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attendance_operations);



    Calendar c = Calendar.getInstance();
    int minute = c.get(Calendar.MINUTE);
    int hours = c.get(Calendar.HOUR);

    remaningTimeTV = (TextView)findViewById(R.id.remaningTime);
    aDB = new databaseTimeTableClass(this);

    String currentClass = aDB.attendanceSubjectView(hours, minute);

    TextView newClass = (TextView)findViewById(R.id.nextclass);
    newClass.setText(currentClass);

    new timerForUpComing(remaningTimeTV).execute();

}}

异步类

public class timerForUpComing extends AsyncTask <Void, Integer, Void>{

public boolean a = true;
public int differenceMinute;
public int currentMinute;

TextView timeView;

public timerForUpComing(TextView timeRem)
{
    this.timeView=timeRem;
}

@Override
protected Void doInBackground(Void... params) {



    while (a)
    {
        Calendar c = Calendar.getInstance();
        currentMinute = c.get(Calendar.SECOND);
        differenceMinute = 60 - currentMinute;
        Log.d("d ", String.valueOf(differenceMinute));
        publishProgress(differenceMinute);
        try {
           Thread.sleep(999);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(differenceMinute==1)
            a = false;
    }

   return null;
}


public void publishProgress(int remaining)
{
    timeView.setText(String.valueOf(remaining));

} }

我通过Constructor将TextView fromm class AttendanceOperations传递给timeForUpComing,因此我可以从PublishProgress更新它。

这似乎并没有起作用。

1 个答案:

答案 0 :(得分:1)

  

Android说PublishProgress驻留在UI线程中,因此我应该可以从发布进度中更改UI。

AsyncTask有自己的publishProgress()方法。您没有实施 publishProgress()。您致电 publishProgress()。您实施 onProgressUpdate(),在onProgressUpdate()中,您可以更新您的用户界面。

the documentation中介绍了这一点。

所以,改变:

public void publishProgress(int remaining)
{
    timeView.setText(String.valueOf(remaining));

}

为:

@Override
public void onProgressUpdate(Integer... remaining) {
    timeView.setText(remaining.toString());
}

此外,this sample app演示了AsyncTask的使用,包括调用publishProgress()和实施onProgressUpdate()