AsyncTask在OnPostExecute中返回null

时间:2013-02-19 17:24:30

标签: android android-asynctask

我正在尝试将位于服务器上的.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"

任何想法如何解决?

顺便说一下:用浏览器检查了网址,显示的是文字,所以网址不是问题。

1 个答案:

答案 0 :(得分:4)

此循环在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;