我目前很困惑。我在onPostExecute()中编写的一些行不会被调用。这是我的AsyncTask代码:
public class GuestInfoTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params) {
StringBuilder stringBuilder = new StringBuilder();
try
{
URL url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int charRead;
char[] charBuffer = new char[500]; // download 500 characters at a time
while(true)
{
charRead = inputStreamReader.read(charBuffer);
if(charRead <= 0)
break;
stringBuilder.append(String.valueOf(charBuffer), 0, charRead);
}
return stringBuilder.toString();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s != null)
{
// THIS DOES NOT GET CALLED!
System.out.println("Successfully retrieved guest info with response: " + s);
// TODO: parse the data here
// THIS DOES NOT GET CALLED ALSO!
System.out.println("TEST: " + s);
// BUT THIS GETS CALLED
// alert dialog the response here
new AlertDialog.Builder(GuestInfoActivity.this)
.setTitle("Guest Info")
.setMessage("Message: " + s)
.setPositiveButton("OK", null)
.show();
}
else
{
System.out.println("Failed to retrieve guest info! Double check your server address and/or network connection!");
new AlertDialog.Builder(GuestInfoActivity.this)
.setTitle("Error")
.setMessage("Failed to retrieve guest info! Double check your server address and/or network connection!")
.setPositiveButton("OK", null)
.show();
}
// disable the progressbar after
mProgressDialog.dismiss();
}
}
我有一个button
,点按后会执行上面的AsyncTask
。现在任务完成后,我成功地在屏幕上看到了AlertDialog
,但没有看到我printLines
。我也尝试了Log.i()
,但结果相同。
为什么会这样?我的结局有什么问题吗?对于它的价值,我使用的是Android Studio 1.51和模拟器API 19
编辑:我想我已经缩小了罪魁祸首。如果我键入Log.d(“tag”,“test”),则会在日志中成功显示。但是如果我键入Log.d(“tag”,s),其中s
是onPostExecute的结果,我在日志中看不到它。输出onPostExecute结果字符串似乎有问题吗?
答案 0 :(得分:2)
您指向的行是System.out.println
命令。它们肯定会被调用,但您看不到它们,因为字符串显示在默认系统输出(sysout
)中,而不是您在Android Studio中看到的控制台。
要在控制台(logcat)中查看这些消息,您可以使用Log
类(http://developer.android.com/reference/android/util/Log.html)中的一种方法。
因此,请尝试:
,而不是System.out.println("TEST: " + s)
Log.i("tag", "TEST: " + s)
请记住Log.i
正在信息级别打印消息,因此您需要检查控制台(logcat)是否显示该级别的消息。其他级别是:
Log.v("tag", "TEST: " + s) // VERBOSE
Log.d("tag", "TEST: " + s) // DEBUG
Log.w("tag", "TEST: " + s) // WARNING
Log.e("tag", "TEST: " + s) // ERROR