Saad
Saad

Reputation: 28586

How to read fql response in android

I've been going though the following: https://developers.facebook.com/docs/howtos/androidsdk/3.0/run-fql-queries/#step2

which has the following code (I changed the fql query for simplicity):

queryButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String fqlQuery = "SELECT name FROM user WHERE uid IN " +
                "(SELECT uid2 FROM friend WHERE uid1 = me()LIMIT 2)";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);
        Session session = Session.getActiveSession();
        Request request = new Request(session,
            "/fql",                         
            params,                         
            HttpMethod.GET,                 
            new Request.Callback(){         
                public void onCompleted(Response response) {
                    Log.i(TAG, "Result: " + response.toString());
                }                  
        }); 
        Request.executeBatchAsync(request);                 
    }
});

looking specifically at the Log.i, response.toString() returns something in this format:

Result: {Response:  responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[{"name":"John Doe"},{"name":"Jake Josh"}]}}, error: null, isFromCache:false}

now my assumption was that response was a json obj so I tried something like this:

JSONObject json=new JSONObject(response);

but this isn't working, so I'm not really sure how to read the response I'm getting, strictly speaking I just want to loop over the names, but can't figure out how to actually read the response

Upvotes: 1

Views: 1925

Answers (2)

Pratik Sharma
Pratik Sharma

Reputation: 13415

Try this :

public static final void parseUserFromFQLResponse( Response response )
{
    try
    {
        GraphObject go  = response.getGraphObject();
        JSONObject  jso = go.getInnerJSONObject();
        JSONArray   arr = jso.getJSONArray( "data" );

        for ( int i = 0; i < ( arr.length() ); i++ )
        {
            JSONObject json_obj = arr.getJSONObject( i );

            String name   = json_obj.getString( "name" );

            //...

        }
    }
    catch ( Throwable t )
    {
        t.printStackTrace();
    }
}

Make a call like this:

public void onCompleted(Response response) {
     Log.i(TAG, "Result: " + response.toString());
     parseUserFromFQLResponse(response);
} 

Upvotes: 2

dokkaebi
dokkaebi

Reputation: 9190

From the source for GraphObject and for Response, it looks like you can do:

JSONObject data = response.getGraphObject().getInnerJSONObject();

Upvotes: 1

Related Questions