gpt4 book ai didi

java - 异步任务 : Can't update UI from publishProgress. 错误 : Only the original thread that created a view hierarchy can touch its views.

转载 作者:行者123 更新时间:2023-11-30 01:44:12 26 4
gpt4 key购买 nike

Developer.Android 说 PublishProgress 驻留在 UI 线程中,因此我应该能够从 Publish Progress 更改 UI。

但是,我得到这个错误:

android.view.ViewRootImpl$CalledFromWrongThreadException: 只有创建 View 层次结构的原始线程可以触及它的 View

关于这段代码:

通话 Activity

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 从类 AttendanceOperations 传递到 timeForUpComing,因此我可以从 PublishProgress 更新它。

这似乎不起作用。

最佳答案

Android says PublishProgress resides in UI Thread and thus I should be able to alter the UI from Publish Progress.

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()

关于java - 异步任务 : Can't update UI from publishProgress. 错误 : Only the original thread that created a view hierarchy can touch its views.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33972161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com