简体   繁体   English

解析JSON时,Android应用不断失败

[英]Android app keeps failing when parsing JSON

My app makes a call to FourSquare API. 我的应用程序调用了FourSquare API。 The call happens in my getResponse() function, and that function gets called every time I do new Explore().execute(); 该调用发生在我的getResponse()函数中,并且每次执行new Explore().execute();时都会调用该函数Explore().execute();

Now, I am able to get a string from the API... But when I pass that string to displayResults() function, it becomes null (I have a code comment below to show exactly where). 现在,我可以从API中获取字符串了……但是当我将该字符串传递给displayResults()函数时,它变为null(下面有一个代码注释以显示确切位置)。 And because this string becomes null, I can not parse the JSON. 而且由于此字符串变为null,所以无法解析JSON。 What is causing this issue? 是什么导致此问题?

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

EDIT: The variable resp becomes null/empty inside the function displayResults() . 编辑:变量resp在函数displayResults()变为null / empty。 I don't know how this is happening. 我不知道这是怎么回事。

Your getResponse() method does nothing. 您的getResponse()方法不执行任何操作。 You need to change it so that it actually returns the complete string. 您需要对其进行更改,以便它实际上返回完整的字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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