
[英]AsyncTask doInbackground returns arraylist value but in onPostExecute arraylist is 0
[英]AsyncTask returns null in OnPostExecute
我正在尝试将文本从服务器上的.txt转换为字符串(feed_str)我的代码:
public class getFeedData extends AsyncTask<String, Integer, String>
{
@Override
protected String doInBackground(String... params)
{
String feed_str = null;
try
{
// Create a URL for the desired page
URL url = new URL("http://www.this.is/a/server/file.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((feed_str = in.readLine()) != null)
{
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
}
catch (MalformedURLException e)
{
System.out.println("AsyncError: " + e);
}
catch (IOException e)
{
System.out.println("AsyncError: " + e);
}
catch (NullPointerException e)
{
System.out.println("AsyncError: " + e);
}
return feed_str;
}
@Override
protected void onPostExecute(String feed_str)
{
super.onPostExecute(feed_str);
System.out.println("onPostExecute " + feed_str);
}
使用此代码,logcat应该输出类似以下内容: "onPostExecute text from server"
而不是输出"onPostExecute null"
任何想法如何解决?
顺便说一句:已使用浏览器检查了该URL,并显示了文本,因此该URL并非问题。
直到feed_str == null
该循环才会退出。 因此,它的最后一个值为null,即返回的值。
while ((feed_str = in.readLine()) != null)
{
// str is one line of text; readLine() strips the newline character(s)
}
如果您要返回该字符串,则还需要保留一个“总计”字符串。
String entireFeed = "";
while ((feed_str = in.readLine()) != null)
{
entireFeed += feedStr + "\n";
// whatever else you're doing
}
...
return entireFeed;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.