我的应用程序调用了FourSquare API。该调用发生在我的getResponse()函数中,并且每次我执行新的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 - 解析JSON时,Android应用不断失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30794461/

10-09 05:28