1

I am trying to parse JSONObject returned from facebook graph API in java. I want to fetch some user data and friends' data through graph api. The graph I am trying to parse is this:

{
  "id": "985453561536987",
  "first_name": "abc",
  "last_name": "xyz",
  "name": "abc xyz",
  "birthday": "03/17/1995",
  "gender": "male",
  "friends": {
    "data": [
      {
        "first_name": "Div",
        "last_name": "Tol",
        "gender": "female",
        "id": "150534786284567"
      }
    ],
    "paging": {
      "next": "https://graph.facebook.com/v2.4/985363151536997/friends?fields=first_name,last_name,about,birthday,gender&access_token=CAANEU8qO1HYBAJG4ZCYtc5lLuZBv3zKWe6qRN3Oy5iYtijFsQwplDH2AFe2YiXS1lZCXtxnYZBXLhBo6N65KEmW3wuNKxXiZCCVgFpg8r3elkqgCRFZBZAIgscoZCtxezk08fpiPnYqujCdMY4ZB3d88vqcDZCnpon9TjPZBE2Irzlrcqn8gzPZB8nvRu2ZBoLt6Y1yGlovgt0K18uYBbyj8GpNZCX&limit=25&offset=25&__after_id=enc_AdBfWxVZCaZAlL5ZBGlZAQjMZC2M5m4uQMNSQPfwNfsxC9TwgQzgK55kQEVGeZBEJMoyXfvySnZAOwaHCGvmgj5Ngzut6D9"
    },
    "summary": {
      "total_count": 533
    }
  },
}

I am getting NullPointerException while trying to parse the JSONObject For parsing above information I do following:

public void graphActivity(AccessToken accessToken) {

        //used is graph request code from graph api explorer
        GraphRequest request = GraphRequest.newMeRequest(
                accessToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        // Insert your code here
                        try {

                            //getting error in following code where object.getString("first_name");
                            //is written
                            //null pointer exception

                            //userVO.setId(object.getString("id");
                            userVO.setUserFirstName(object.getString("first_name"));
                            userVO.setUserLastName(object.getString("last_name"));
                            userVO.setUserName(object.getString("name"));
                            userVO.setUserBirthday(object.getString("birthday"));
                            userVO.setUserGender(object.getString("gender"));


                            JSONObject friendsJsonObject = object.getJSONObject("friends");

                            JSONArray data = friendsJsonObject.getJSONArray("data");

                            String userString = "USER::\n"
                                    + "id: " + userVO.getId() + "\n"
                                    + "fn: " + userVO.getUserFirstName() + "\n"
                                    + "ln: " + userVO.getUserLastName() + "\n"
                                    + "un: " + userVO.getUserName() + "\n"
                                    + "gen: " + userVO.getUserGender() + "\n"
                                    + "bday: " + userVO.getUserBirthday() + "\n";

                            Log.d(TAG, userString);
                            friendList = new ArrayList();
                            int length_list = data.length();
                            for (int i = 0; i < length_list; i++) {
                                JSONObject dataObj = data.getJSONObject(i);
                                //friendVO.setFriendId(dataObj.getString("id"));

                                friendVO.setFriendFirstName(dataObj.getString("first_name"));
                                friendVO.setFriendLastName(dataObj.getString("last_name"));
                                friendVO.setFriendName(dataObj.getString("name"));
                                friendVO.setFriendBirthday(dataObj.getString("birthday"));
                                friendVO.setFriendGender(dataObj.getString("gender"));
                                friendList.add(friendVO);

                                String friendString = "FRIEND::\n"
                                        + "id: " + friendVO.getFriendId() + "\n"
                                        + "fn: " + friendVO.getFriendFirstName() + "\n"
                                        + "ln: " + friendVO.getFriendLastName() + "\n"
                                        + "un: " + friendVO.getFriendName() + "\n"
                                        + "gen: " + friendVO.getFriendGender() + "\n"
                                        + "bday: " + friendVO.getFriendBirthday() + "\n";

                                Log.d(TAG, friendString);




                            }


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

                    }
                });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,first_name,last_name,name,birthday,about,gender,website,friends{first_name,last_name,name,about,birthday,gender}");
        request.setParameters(parameters);
        request.executeAsync();
    }

Note: I am new to JSON parsing. Your help would be very useful, not just for this question but also for JSON Parsing. Thank you for reading. :)

EDIT: errorlog:

10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ java.lang.NullPointerException
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at com.wordpress.toknowtoshare.fbintegrationexample.MainActivity$2.onCompleted(MainActivity.java:190)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:300)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at com.facebook.GraphRequest$5.run(GraphRequest.java:1364)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5021)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
10-24 16:31:13.050    5266-5266/com.wordpress.toknowtoshare.fbintegrationexample W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
2
  • 1
    can you post the error log? Commented Oct 24, 2015 at 10:43
  • @muilpp yes, I edited my question with log. Commented Oct 24, 2015 at 11:05

5 Answers 5

4

try this code:

GraphRequest request = GraphRequest.newMeRequest(
            loginResult.getAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(
                 final JSONObject object,
                 GraphResponse response) {
                 // Application code
                 final JSONObject jsonObject = response.getJSONObject();
                 String first_name = "";
                 String last_name = "";
                 try {
                      first_name = jsonObject.getString("first_name");
                      last_name =  jsonObject.getString("last_name"); 
                      JSONObject friends = jsonObject.getJSONObject("friends");
                      JSONArray data = friends.getJSONArray("data");
                      JSONObject objectdata = data.getJSONObject(0);
                      String friend_first_name = objectdata.getString("first_name");
                      String friend_last_name = objectdata.getString("last_name");
                 } catch (JSONException e) {
                      e.printStackTrace();
                 }});
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the method fromJson from the class com.google.gson.Gson for converting your json to java object instead of using all the setters. A tutorial here . This will simplify your code and probably resolve the problem.

Comments

0

Basically GraphResponse contains the reponse JSONObject you are expecting so before the line userVO.setUserFirstName(object.getString("first_name"));
Please add following lines and check

JSONObject responseJSONObject = response.getJSONObject();
if(null != responseJSONObject){
  userVO.setUserFirstName(object.getString("first_name"));
  //your code
}

2 Comments

So I need to use graph response and convert it to responseJSONObject instead of JSONObject ??
I am refering docs developers.facebook.com/docs/android/graph so that what I feel....alternatively you can check the error using reponse object
0

Please try the below method. I have used the same in one of my project and working fine

public Map<String, String> getGraphData(String fbGraph) {
        Gson gson = new Gson();//.toJson(fbGraph);
        Map<String, String> fbProfile = gson.fromJson(fbGraph, new TypeToken<Map<String, String>>(){}.getType());//fromJson(gson, new TypeToken<Map<String, String>>(){}.getType());
        return fbProfile;
    }

Comments

0

java.lang.NullPointerException is occurring at object.getString("first_name"); because JSONObject returned by GraphRequest is null.

As you are calling GraphRequest asynchronously using request.executeAsync(); will be executed asynchronously in a separate thread, i.e. your code underneath this line is not blocked.

so in order avoid the problem of NPE you can surround your code within following :

if(object!=null) { 
  //your code 
} 
else {
  Toast.makeText(this, "Please Try Again ",Toast.LENGTH_SHORT).show();
}

For parsing JSON data use following JSON Parser :

  1. GSON - Getting Started with GSON
  2. Jackson - Getting Started with Jackson

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.