我在应用程序中打开一个新 fragment ,我想计算价格并每秒打印它(通过 asyncTask),但是当我运行应用程序时停止工作。 你能帮我找出问题所在吗?
public class RandomDrive extends Fragment {
private Chronometer chronometer;
private Button start;
private Button stop;
private TextView price;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_random_drive, container, false);
chronometer = (Chronometer) v.findViewById(R.id.chronometer);
price = v.findViewById(R.id.see_price);
class SyncTaskCounter extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
double price = 0;
while (!isCancelled()) {
price = price + 0.05;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
printPrice(price);
}
return null;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}
final SyncTaskCounter asyncTaskCount;
asyncTaskCount = new SyncTaskCounter();
start = (Button) v.findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
asyncTaskCount.execute();
}
});
stop = (Button) v.findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chronometer.stop();
asyncTaskCount.cancel(true);
}
});
return v;
}
public void printPrice(double price1) {
price.setText("the price is: " + price1 + " shekel");
}
}
问题出在 asyncTask 中,因为当我在没有 asyncTask 的情况下运行该函数并仅在最后计算价格时 - 应用程序运行。
最佳答案
在 Android 上,您必须在 UI 线程上运行所有 UI 代码。 AsyncTask 中的代码在其他线程中执行,因此无法调用 UI 方法。
为此,您应该使用 Handler(代码将在 UI 线程中调用): https://developer.android.com/reference/android/os/Handler
final Handler h=new Handler();
h.postDelayed(new Runnable() {
public void run() {
printPrice(price);
price = price + 0.05;
h.postDelayed(this, 1000); // call for next update
}
}, 1000);
我必须使用AsyncTask,那么你应该从方法更新UI:onProgressUpdate https://developer.android.com/reference/android/os/AsyncTask
class SyncTaskCounter extends AsyncTask<Void, Double, Void> {
@Override
protected Void doInBackground(Void... voids) {
double price = 0;
while (!isCancelled()) {
price = price + 0.05;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(price); // this instructs to call onProgressUpdate from UI thread.
}
return null;
}
@Override
protected void onProgressUpdate(Double... price) {
printPrice(price[0]); // this is called on UI thread
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}
关于java - 当我按下激活 fragment 中的异步任务的按钮时,应用程序停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54270535/