【发布时间】:2021-01-18 17:33:46
【问题描述】:
我的 AsyncTask 没有执行 doInBackground,preExecute 正在运行,我用 Toast 对其进行了测试。
我也在运行另一个异步任务,但是当我启动这个时,我取消了那个,它仍然无法工作。
它没有抛出任何错误,这仍然发生在我身上。
这是我的代码,任何帮助将不胜感激。
部分代码被截断。我只是展示了重要的部分。
如果我的英语有任何错误,请见谅。
// AsyncTask
package com.test.testing;
//imports
public class Update_Score extends AsyncTask<Void, Void, Void> {
String result="vvv",
name,
score,
lastTest,
maximum;
ProgressBar loading;
TextView text;
Context context;
@Override
protected Void doInBackground(Void... voids) {
String strUrl="http://test.tk/updatesomething.php";
while (result=="vvv") {
try {
URL url = new URL(strUrl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
//output
OutputStream output = httpConnection.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));
String post_data= URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("score","UTF-8")+"="+URLEncoder.encode(score,"UTF-8")+"&"
+URLEncoder.encode("lastTest","UTF-8")+"="+URLEncoder.encode(lastTest,"UTF-8");
writer.write(post_data);
writer.flush();
writer.close();
output.close();
//input
InputStream input = httpConnection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(input,"iso-8859-1"));
result="";
String line="";
while ((line=reader.readLine())!=null){
result += line;
}
reader.close();
input.close();
httpConnection.disconnect();
} catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) {
e.printStackTrace();
}
}
new AlertDialog.Builder(context).setMessage("updateEnd").create().show();
return null;
}
}
// Calling AsyncTask
package com.test.testing;
//imports
public class Final_Score extends AppCompatActivity {
public TextView score;
public ProgressBar loading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final__score);
initVar();
String totalMark =getIntent().getStringExtra("TOTAL_MARKS"),
name =getIntent().getStringExtra("NAME") ,
lastTest =getIntent().getStringExtra("TESTNUM"),
maximum =getIntent().getStringExtra("MAX");
boolean forced=getIntent().getBooleanExtra("FORCED",false);
if(forced){
new AlertDialog.Builder(this).setMessage("Time Up").setTitle("").create().show();
}
score.setText(totalMark);
Update_Score update=new Update_Score(name,totalMark,lastTest,loading,this,score,maximum);
update.execute();
}
}
提前致谢。
【问题讨论】:
-
您的代码没有 Update_Score 构造函数。还要确保您在清单中具有 INTERNET 权限。
-
我有没有显示的构造函数,因为在问题中添加太多代码会给我一个错误,我还添加了互联网权限。
-
尝试从
doInBackground方法中移除while循环。 -
new AlertDialog.Builder(context).setMessage("updateEnd").create().show()把它从doInBackground中拿出来,在onPostExecute中做UI的事情。 -
正如@blackapps 指出的,不应在 doInBackground 方法中调用 AlertDialog,我很惊讶您没有从中崩溃,因为这需要在 UI 线程中执行跨度>
标签: java android android-asynctask