我在我的应用程序中打开一个新片段,我想计算价格并每秒打印一次(通过 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 的情况下运行该函数并仅在最后计算价格时 - 应用程序运行。
繁星coding
相关分类