java - 我在 AsyncTask 的 doInBackground () 中收到错误
问题描述
我在位于 asyncTask 的 doInBackground () 部分的 AsyncHttpClient 部分中收到错误。我怎样才能摆脱错误?错误接收行如下所示。
错误:执行doInBackground()时出错
public class BackgroundTask2 extends AsyncTask<String,Void,String> {
protected Void doInBackground(String... params) {
Bundle veri = getIntent().getExtras();
sorguYil = veri.getString("yil");
sorguAy = veri.getString("tarih");
sorguAy2 = sorguAy.replace(" ", "");
sorgu = "ehliyet" + sorguYil + sorguAy2;
s = kelimeGetir(sorgu); // I am getting the error here
return s;}
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
if (aVoid.equals("internet")){
Toast.makeText(sorularActivity.this, "Lütfen internet bağlantınızı kontrol edin!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(),SinavSecimiActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}else if (aVoid.equals("onay")){
progressDialog.dismiss();
}
}
kelimeGetir(高粱)
private String kelimeGetir(String sorgu) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("sorgu", sorgu);
client.post("https://www....php", params, new TextHttpResponseHandler()
//****ERROR {
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
fnDu = "internetEr";
}
public void onSuccess(int statusCode, Header[] headers, String responseString) {
try {
txtSoruSayisi.setText(soruSayisi + " / 50");
JSONObject object = new JSONObject(responseString);
JSONArray array = object.getJSONArray("soruVeri");
JSONObject sorular = array.getJSONObject(sayac);
} catch (JSONException e) {
e.printStackTrace();
}
}
fnDu = "onay";
});
return fnDu;
}
错误 在此处输入图像描述
解决方案
正如@Uday Nayak 所说,您无法在 doInBackground 方法上访问 UI 元素,它会导致崩溃(它使用不同的线程运行)。但如果你必须这样做,把它包起来
runOnUiThread(() -> {
// to UI access
});
或创建处理程序以访问主线程以显示您的吐司
推荐阅读
- react-native - 如何在 React Native 中优化图像并查看最新的 iPhone 机型
- c# - 通过 SceneManager 加载菜单
- r - 使用变量向量重命名数据框
- django - Django:通过表单向另一台服务器发送发布请求
- java - 如何在我的 lambda 函数中传递多个 get 参数?
- python - 是否有可以对有限状态机进行时间逻辑模型检查的 Python 包?
- android - 监听应用程序通知设置的变化
- json - 期望一个大小为 2 但集合大小为 0 的集合?
- android - body_loc_args 中的 FCM 格式日期
- node.js - 如何卸载间接依赖