bufferedReader reader.readline直接返回null

时间:2016-03-22 10:42:30

标签: java json android-studio bufferedreader

我正在使用bufferedReader,奇怪的是,在我这样做之后

reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

EDIT3: BufferedReader阅读器本身已知完全加载且正确,但需要的reader.readline直接返回null

有人能解释我的错误或为什么会这样吗?

编辑:我从网址获取json,这是

  

{ “体育”:[{ “运动”:{ “ID”: “1”, “名称”: “瑜伽”, “等级”: “1.6”}},{ “运动”:{ “ID” “2”, “名称”: “网球”, “等级”: “3.6”}},{ “运动”:{ “ID”: “3”, “名称”: “zwemmen”, “等级”:” 4.7 “}}],” 视图 “:{” 名称 “:” SportData”, “显示”: “PAGE_1”, “路径”: “管理/内容/数据/视图/ SportData”, “根”: “体育” , “孩子”: “运动”, “网页”:空, “页”:空, “计数”:3, “限制”:空}}

所以当我调试这个时,我得到了关注......

running bufferedReader running reader.readline

EDIT2:这是完整的代码,

@Override
    protected Void doInBackground(String... type) {
        URL_STRING = "my json_url";
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            try
            {
                URL url;
                StringBuilder stringBuilder;
                    url = new URL(URL_STRING);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    stringBuilder = new StringBuilder();
                    while ((line =reader.readLine()) != null)
                    {
                        stringBuilder.append(line+"\n");
                    }
                    result =  stringBuilder.toString();
                }
                catch (Exception e)
                {
                }
        }
        return null;
    }

1 个答案:

答案 0 :(得分:1)

您的代码没有意义。你永远地追加同一条线。你的循环应该是:

while ((line = reader.readLine()) != null)
{
    stringBuilder.append(line+"\n");
}

我也想知道你是否在同一个套接字上创建了两个BufferedReaders,这也没有意义。