2

I'm trying to get text from a .txt located on a server to a string (feed_str) My code:

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);
  }

With this code the logcat should output something like: "onPostExecute text from server" but instead of that it outputs "onPostExecute null"

Any ideas how to fix?

Btw: The url has been checked with a browser and the text was displayed so the url isn't the problem.

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 に答える