java - Android 应用程序在解析 JSON 时不断失败

标签 java android json

我的应用程序调用 FourSquare API。该调用发生在我的 getResponse() 函数中,并且每次我执行 new Explore().execute();

时都会调用该函数

现在,我可以从 API 获取一个字符串...但是当我将该字符串传递给 displayResults() 函数时,它变为 null(我在下面有一个代码注释来准确显示在哪里)。因为这个字符串变成了 null,所以我无法解析 JSON。是什么导致了这个问题?

public TextView mBusinessName;
public TextView mCategorie;
public WebView mLocationView;

private class Explore extends AsyncTask<Void, String, String>{

    String resp = "";

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(Void... String) {
        //I get a complete JSON string and assign to resp HERE.
        resp = getResponse();
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        //pass resp to display results
        displayResults(resp);
    }
}

public String getResponse(){
    String clientSecret = getResources().getString(R.string.client_secret);
    String clientID = getResources().getString(R.string.client_id);
    String url = "https://api.foursquare.com/v2/venues/explore?ll="
            + mLatitude + "," + mLongitude
            + "&limit=" + 5
            + "&radius=" + mRadius
            + "&query=" + mTerm
            + "&oauth_token="
            + "&client_secret="+ clientSecret
            + "&client_id="+ clientID
            + "&v=20150610";

    String getResponseString = "";
    try{
        URL searchUrl = new URL(url);
        HttpURLConnection httpsClient =
                (HttpURLConnection) searchUrl.openConnection();

        BufferedReader reader = new BufferedReader(new InputStreamReader(httpsClient.getInputStream()));
        try{
            getResponseString = "";
            while((getResponseString = reader.readLine()) != null){
                Log.d("Response ==== ", getResponseString);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                try{
                    reader.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }

    return getResponseString;
}

public void displayResults(String resp){

    //HERE is where it fails. The String resp becomes null/empty
    // have tried logging resp, the log doesn't show up at all
    // because of this, JSON string can not be parsed!!!!
    try {
        JSONObject json = new JSONObject(resp);
        JSONArray items = json.getJSONObject("response")
                .getJSONArray("groups").getJSONObject(0)
                .getJSONArray("items");

        //randomize items
        JSONObject item = items.getJSONObject(getRandomIndex(items.length()-1));

        String name = item.getJSONObject("venue").optString("name");
        String categorie = item.getJSONObject("venue").getJSONArray("categories").getJSONObject(0).getString("name");

        String latitude = item.getJSONObject("venue").getJSONObject("location").optString("lat");
        String longitude = item.getJSONObject("venue").getJSONObject("location").optString("lng");
        String image = "http://maps.google.com/maps/api/staticmap?center="
                + latitude + "," + longitude
                + "&markers=size:tiny%color:red%7C" + latitude + "," + longitude
                +"&zoom=17&size=375x225&sensor=false";

        mLocationView.loadUrl(image);
        mBusinessName.setText(name);
        mCategorie.setText(categorie);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

编辑:变量resp在函数displayResults()内变为空/空。我不知道这是怎么发生的。

最佳答案

您的 getResponse() 方法不执行任何操作。您需要更改它,以便它实际上返回完整的字符串。

try{
        StringBuilder sb = new StringBuilder();
        getResponseString = "";
        while((getResponseString = reader.readLine()) != null){
            Log.d("Response ==== ", getResponseString);
            sb.append(getResponseString);
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        if(reader != null){
            try{
                reader.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

return sb.toString();

关于java - Android 应用程序在解析 JSON 时不断失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30794461/

相关文章:

android - 如何在 Android OpenGL 中加载网格

json - 将 Firebase 中的数据序列化为 Flutter 的 Dart 对象的最佳方法是什么?

javascript - Angular JS 和 Symfony2

java - 分配变量然后在参数中使用变量?

java - Java中的快速整数除法

java - Hibernate ManyToMany 与 JoinTable 删除传播

java - java 中的 nextFloat 问题

android - 从具有多个相关条目的多个SQL表中检索数据

android - 在加载 ListView 时更新划掉的项目

javascript - Vue.js 排除设置文件被捆绑