3

How i can fetch all of user Photo albums from facebook. i tried like this with this Url https://graph.facebook.com/me/albums?access_token=xxxx

i am using this code, i was mention this permissions also "user_photos".

Bundle parameters = new Bundle();
parameters.putString("format", "json");
parameters.putString("method", "user_photos");
parameters.putString(TOKEN, facebook.getAccessToken());

JSONObject response = null;        
try {

    response = Util.parseJson(Album_Url);        
    JSONArray array = obj.optJSONArray("data");
    for(int i = 0; i<array.length(); i++){                  
    JSONObject main_obj = array.getJSONObject(i);
    String album = main_obj.getString("name");                          
    }        
} catch (JSONException e1) {             
    e1.printStackTrace();
} catch (FacebookError e1) {             
    e1.printStackTrace();
}

but i am getting this in the log cat 09-12 14:27:42.990: W/System.err(12189): org.json.JSONException: Value https of type java.lang.String cannot be converted to JSONObject.

i tried like this also

try {

        Bundle parameters = new Bundle();
        parameters.putString("format", "json");
        parameters.putString(TOKEN, facebook.getAccessToken()) ;       
        String response = null;
        try {
            response = Util.openUrl(Album_Url, "GET", parameters);
        } catch (MalformedURLException e) {      
            e.printStackTrace();
        } catch (IOException e) {        
            e.printStackTrace();
        }
        JSONObject obj = Util.parseJson(response);   
        JSONArray array = obj.optJSONArray("data");
        for(int i = 0; i<array.length(); i++){                  
            JSONObject main_obj = array.getJSONObject(i);
            String album =  main_obj.getString("name");                         
        }        
    } catch (JSONException e1) {             
        e1.printStackTrace();
    } catch (FacebookError e1) {             
        e1.printStackTrace();
    }   

i am getting this error 09-12 14:42:36.920: W/System.err(12259): com.facebook.android.FacebookError: Malformed access token

Charles
  • 50,943
  • 13
  • 104
  • 142
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166

1 Answers1

6

In the onCreate() method, I am calling this Asynctask:

private class getAlbumsData extends AsyncTask<Void, Void, Void> {

    LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);

    @Override
    protected void onPreExecute() {

        // SHOW THE PROGRESS BAR (SPINNER) WHILE LOADING ALBUMS
        linlaHeaderProgress.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {

        // CHANGE THE LOADING MORE STATUS TO PREVENT DUPLICATE CALLS FOR
        // MORE DATA WHILE LOADING A BATCH
        loadingMore = true;

        // SET THE INITIAL URL TO GET THE FIRST LOT OF ALBUMS
        URL = "https://graph.facebook.com/" + initialUserID
                + "/albums&access_token="
                + Utility.mFacebook.getAccessToken() + "?limit=10";

        try {

            HttpClient hc = new DefaultHttpClient();
            HttpGet get = new HttpGet(URL);
            HttpResponse rp = hc.execute(get);

            if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String queryAlbums = EntityUtils.toString(rp.getEntity());

                JSONObject JOTemp = new JSONObject(queryAlbums);

                JSONArray JAAlbums = JOTemp.getJSONArray("data");

                if (JAAlbums.length() == 0) {
                    stopLoadingData = true;
                    Runnable run = new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "No more Albums", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    };
                    Albums.this.runOnUiThread(run);

                } else {
                    // PAGING JSONOBJECT
                    if (JOTemp.has("paging"))   {
                        JSONObject JOPaging = JOTemp.getJSONObject("paging");

                        if (JOPaging.has("next")) {
                            String initialpagingURL = JOPaging
                                    .getString("next");

                            String[] parts = initialpagingURL.split("limit=10");
                            String getLimit = parts[1];

                            pagingURL = "https://graph.facebook.com/"
                                    + initialUserID + "/albums&access_token="
                                    + Utility.mFacebook.getAccessToken()
                                    + "?limit=10" + getLimit;

                        } else {
                            stopLoadingData = true;
                            Runnable run = new Runnable() {

                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(),
                                            "No more Albums",
                                            Toast.LENGTH_SHORT).show();
                                }
                            };
                            Albums.this.runOnUiThread(run);
                        }
                    } else {
                        stopLoadingData = true;
                        Runnable run = new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "No more Albums",
                                        Toast.LENGTH_SHORT).show();
                            }
                        };
                        Albums.this.runOnUiThread(run);

                    }

                    getAlbums albums;

                    for (int i = 0; i < JAAlbums.length(); i++) {
                        JSONObject JOAlbums = JAAlbums.getJSONObject(i);

                        if (JOAlbums.has("link")) {

                            albums = new getAlbums();

                            // GET THE ALBUM ID
                            if (JOAlbums.has("id")) {
                                albums.setAlbumID(JOAlbums.getString("id"));
                            } else {
                                albums.setAlbumID(null);
                            }

                            // GET THE ALBUM NAME
                            if (JOAlbums.has("name")) {
                                albums.setAlbumName(JOAlbums
                                        .getString("name"));
                            } else {
                                albums.setAlbumName(null);
                            }

                            // GET THE ALBUM COVER PHOTO
                            if (JOAlbums.has("cover_photo")) {
                                albums.setAlbumCover("https://graph.facebook.com/"
                                        + JOAlbums.getString("cover_photo")
                                        + "/picture?type=normal"
                                        + "&access_token="
                                        + Utility.mFacebook
                                                .getAccessToken());
                            } else {
                                albums.setAlbumCover("https://graph.facebook.com/"
                                        + JOAlbums.getString("id")
                                        + "/picture?type=album"
                                        + "&access_token="
                                        + Utility.mFacebook
                                                .getAccessToken());
                            }

                            // GET THE ALBUM'S PHOTO COUNT
                            if (JOAlbums.has("count")) {
                                albums.setAlbumPhotoCount(JOAlbums
                                        .getString("count"));
                            } else {
                                albums.setAlbumPhotoCount("0");
                            }

                            arrAlbums.add(albums);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        // SET THE ADAPTER TO THE LISTVIEW
        lv.setAdapter(adapter);

        // CHANGE THE LOADING MORE STATUS
        loadingMore = false;

        // HIDE THE PROGRESS BAR (SPINNER) AFTER LOADING ALBUMS
        linlaHeaderProgress.setVisibility(View.GONE);
    }

}

For the sake of completeness, here is what I use to fetch the Paging URLS for a never ending list:

private class loadMoreAlbums extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // SHOW THE BOTTOM PROGRESS BAR (SPINNER) WHILE LOADING MORE ALBUMS
        linlaProgressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... params) {

        // SET LOADING MORE "TRUE"
        loadingMore = true;

        // INCREMENT CURRENT PAGE
        current_page += 1;

        // Next page request
        URL = pagingURL;
        // Log.e("NEW URL", URL);

        try {

            HttpClient hc = new DefaultHttpClient();
            HttpGet get = new HttpGet(URL);
            HttpResponse rp = hc.execute(get);

            if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String queryAlbums = EntityUtils.toString(rp.getEntity());
                // Log.e("RESULT", queryAlbums);

                JSONObject JOTemp = new JSONObject(queryAlbums);

                JSONArray JAAlbums = JOTemp.getJSONArray("data");

                if (JAAlbums.length() == 0) {
                    stopLoadingData = true;

                    Runnable run = new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "No more Albums", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    };
                    Albums.this.runOnUiThread(run);

                } else {
                    // PAGING JSONOBJECT
                    JSONObject JOPaging = JOTemp.getJSONObject("paging");
                    // Log.e("PAGING", JOPaging.toString());

                    if (JOPaging.has("next")) {
                        String initialpagingURL = JOPaging
                                .getString("next");
                        // Log.e("initialpagingURL", initialpagingURL);

                        String[] parts = initialpagingURL.split("limit=10");
                        String getLimit = parts[1];

                        pagingURL = "https://graph.facebook.com/"
                                + initialUserID + "/albums&access_token="
                                + Utility.mFacebook.getAccessToken()
                                + "?limit=10" + getLimit;
                        // Log.e("NEW PAGING URL", pagingURL);

                    } else {
                        stopLoadingData = true;
                        Runnable run = new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "No more Albums available",
                                        Toast.LENGTH_SHORT).show();
                            }
                        };
                        Albums.this.runOnUiThread(run);
                    }

                    getAlbums albums;

                    for (int i = 0; i < JAAlbums.length(); i++) {
                        JSONObject JOAlbums = JAAlbums.getJSONObject(i);
                        // Log.e("INDIVIDUAL ALBUMS", JOAlbums.toString());

                        if (JOAlbums.has("link")) {

                            albums = new getAlbums();

                            // GET THE ALBUM ID
                            if (JOAlbums.has("id")) {
                                albums.setAlbumID(JOAlbums.getString("id"));
                            } else {
                                albums.setAlbumID(null);
                            }

                            // GET THE ALBUM NAME
                            if (JOAlbums.has("name")) {
                                albums.setAlbumName(JOAlbums
                                        .getString("name"));
                            } else {
                                albums.setAlbumName(null);
                            }

                            // GET THE ALBUM COVER PHOTO
                            if (JOAlbums.has("cover_photo")) {
                                albums.setAlbumCover("https://graph.facebook.com/"
                                        + JOAlbums.getString("cover_photo")
                                        + "/picture?type=album"
                                        + "&access_token="
                                        + Utility.mFacebook
                                                .getAccessToken());
                            } else {
                                albums.setAlbumCover("https://graph.facebook.com/"
                                        + JOAlbums.getString("id")
                                        + "/picture?type=album"
                                        + "&access_token="
                                        + Utility.mFacebook
                                                .getAccessToken());
                            }

                            // GET THE ALBUM'S PHOTO COUNT
                            if (JOAlbums.has("count")) {
                                albums.setAlbumPhotoCount(JOAlbums
                                        .getString("count"));
                            } else {
                                albums.setAlbumPhotoCount("0");
                            }

                            arrAlbums.add(albums);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        // get listview current position - used to maintain scroll position
        int currentPosition = lv.getFirstVisiblePosition();

        // APPEND NEW DATA TO THE ARRAYLIST AND SET THE ADAPTER TO THE
        // LISTVIEW
        adapter = new AlbumsAdapter(Albums.this, arrAlbums);
        lv.setAdapter(adapter);

        // Setting new scroll position
        lv.setSelectionFromTop(currentPosition + 1, 0);

        // SET LOADINGMORE "FALSE" AFTER ADDING NEW FEEDS TO THE EXISTING
        // LIST
        loadingMore = false;

        // HIDE THE BOTTOM PROGRESS BAR (SPINNER) AFTER LOADING MORE ALBUMS
        linlaProgressBar.setVisibility(View.GONE);
    }

}

The loadMoreAlbums Asynctask is run from a onScrollListener setup in the onCreate():

    lv.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if ((lastInScreen == totalItemCount) && !(loadingMore)) {

                if (stopLoadingData == false) {
                    // FETCH THE NEXT BATCH OF FEEDS
                    new loadMoreAlbums().execute();
                }

            }
        }
    });

You can choose the relevant parts from my code, or you can use it in it's entirety (after filling a few blanks of course). Hope some of this helps.

Siddharth Lele
  • 27,623
  • 15
  • 98
  • 151
  • No problem. Take whatever you need from it. – Siddharth Lele Sep 12 '12 at 10:23
  • What is the Url for getting album photos, now i have album id i want to get particular album photos . – RajaReddy PolamReddy Sep 12 '12 at 11:40
  • A call to this link will get the first 25 photos from the specific album: https://graph.facebook.com/**the_album_id**/photos&access_token=_your_access_token_. To get all photos add _?limit=0_ after your access_token – Siddharth Lele Sep 12 '12 at 12:08
  • I am getting error in this line: Albums.this.runOnUiThread(run); – rams Feb 09 '13 at 06:04
  • @ram0801: Is this in an Activity or a Fragment? And if it is an Activity, replace the `Albums.this.runOnUiThread(run);` with `YOUR_ACTIVITY.this.runOnUiThread(run);` – Siddharth Lele Feb 09 '13 at 06:52
  • Hi Siddharth Lele could you please let me know what the adapter code is for this, also, what is "getAlbums albums;" and "arrAlbums" thank you :) – Jack Dec 20 '14 at 19:29
  • Hi @Jack. Similar to this answer http://stackoverflow.com/a/13265776/450534, the `arrAlbums` is an ArrayList defined as: `ArrayList arrAlbums`. The adapter used in this example is also similar to the answer linked in this comment. Make a few modifications where required though. This is for showing Albums while the linked answer if for Photos in an Album. The idea is still the same though. If you got Photos working, Albums should be a breeze too. – Siddharth Lele Dec 21 '14 at 04:46
  • @IceMAN hi again from over a year later(I was trying to get this to work a over a year ago as you can see). I am still trying to get this to work and I'm having no luck. I have set up all of the code you've provided here and I've managed to completely debug my app, and I've realized that my codes not going past the "if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {" part. Has the Facebook sdk changed? I am making sure I am logging in and have a user ID and Access token. Thanks again. – Jack Mar 09 '16 at 19:31
  • @Jack: The Facebook SDK has changed drastically since. I am not sure if the code posted above works. I haven't used the SDK for a long time now. Let me see if I can find something more current that might be of help to you. – Siddharth Lele Mar 10 '16 at 03:58
  • @IceMAN thank you very much. I thought I was going crazy after spending 6 hours trying to get it to work. I've looked at the updated docs and it seems that it hasn't changed that much from what the code does above. – Jack Mar 10 '16 at 11:12