2

我正在尝试将文本从位于服务器上的 .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 不是问题。

4

1 回答 1

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;
于 2013-02-19T17:30:51.257 回答