简体   繁体   中英

bufferedReader.readLine does not work within IF in Android

I am writing Android. The app should read line of a file from web, and shows the message on the textView. I use bufferedReader. It works fine when I have bufferedReader.readLine() inside a while loop. But it does not work when I have it in a IF statement (shows nothing, although there's something I see in debug mode).

    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection urlConnection = null;
        String result = "";

        try {
            URL url = new URL("http://www.tc.umn.edu/~yang4131/jtest.json");
            urlConnection = (HttpURLConnection) url.openConnection();

            int code = urlConnection.getResponseCode();
            if(code==HttpURLConnection.HTTP_OK){ // 200

                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                if (in != null) {

                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                    String line = "";


                    /*
                    if((line = bufferedReader.readLine()) != null)
                        result += line;
                    if((line = bufferedReader.readLine()) != null)
                        result += line;
                    if((line = bufferedReader.readLine()) != null)
                        result += line;
                    */

                    while ((line = bufferedReader.readLine()) != null)
                        result += line;

                }
                in.close();
            }
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            urlConnection.disconnect();
        }
        return result; // this return statement is needed, no matter what
    }

I replicated this thing in pure Java in Eclipse, with a local file. It works fine. I really have no idea.

Solved.

Adding result += "\\n\\n\\n\\n"; after the concatenation will make the content appear. I think this has something to do with UI, perhaps my textView is blocked for few lines or whatnot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM