我创建了一个程序,它将通过 PHP 连接到数据库并回显响应。然后我的 android 程序向 PHP 文件发出请求并读取回显。
public class Read_Author extends AsyncTask<String, Void, String> {
String authorName = "";
@Override
public String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/scripts/read_information.php");
HttpResponse response = httpclient.execute(httppost);
authorName = String.valueOf(EntityUtils.toString(response.getEntity()));
String myStr = "ANSWER";
Log.v(myStr, authorName);
}
catch(Exception e){
}
return authorName;
}
public String returnAuthor(){
return authorName;
}
我成功检索回显字符串并将其放入作者姓名字符串变量中。但是,当我随后尝试从我的主要 Activity 中调用 return author 时,我没有收到任何错误,但代码没有运行。
我在我的主要 Activity 中调用了一个名为“readValue”的函数,在该函数中,执行函数被读取,然后应该发生的是 returnauthor 函数应该运行。但相反,没有任何反应 主要 Activity 代码:
public void returnAuthor(){
loadAuthor.execute();
String a = loadAuthor.returnAuthor();
Log.v("HIT ME", a);
}
如果有人对为什么会发生这种情况以及如何解决它有任何建议,我们将不胜感激!
最佳答案
您似乎对AsyncTask
有误解。 AsyncTask
的结果可能不会立即可用,因为后台任务可能尚未完成。
您需要重写AsyncTask
中的onPostExecute
方法,以便在后台任务完成后执行某些任务。
在执行AsyncTask
之前先显示一个progressDialog
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
progressDialog.setCancelable(false);
progressDialog.show();
然后在onPostExecute:
@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
Log.d("author", result);
}
关于Java 代码在调用类函数后不会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443715/