Facebook GraphRequest获取专辑列表或创建一个Android

时间:2015-05-12 06:15:04

标签: android facebook facebook-graph-api

Facebook最近将他们的SDK更新为V 2.0,实际上我的应用必须升级才能拨打v2.0或更高版本。 一些修改是

*会话由Accesstoken替换。

到目前为止,我可以在他们的帐户上使用GraphRequest API登录和发布视频/图像。下一步是获取用户的相册列表

doc

/* make the API call */
new Request(
session,
"/{user-id}/albums",
null,
HttpMethod.GET,
new Request.Callback() {
    public void onCompleted(Response response) {
        /* handle the result */
    }
}
).executeAsync();

但更新后的SDK没有提供Request API,也不允许会话,或者我解释错了吗?

有没有人找到解决方案呢?

3 个答案:

答案 0 :(得分:3)

在onCreate()方法中,我调用的是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);
}

}

为了完整起见,这里是我用来获取永不停止列表的寻呼URL的方法:

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

}

loadMoreAlbums Asynctask是从onCreate()中的onScrollListener设置运行的:

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

        }
    }
});

您可以从我的代码中选择相关的部分,或者您可以完整地使用它(当然在填写几个空格之后)。希望其中一些有用。

答案 1 :(得分:2)

我使用此方法获取Facebook专辑。它没有分页过程。对我有用。

   public void getAlbums(){


    GraphRequest request = GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(
                        JSONObject object,
                        GraphResponse response) {
                        if(object!=null) {
                            try {
                                JSONObject obj = object.getJSONObject("albums");
                                JSONArray jArray = obj.getJSONArray("data");
                                for(int i =0;i<jArray.length();i++){
                                    FbAlbumItem album = new FbAlbumItem();
                                    JSONObject dataObj = jArray.getJSONObject(i);
                                    album.setAlbumId(dataObj.getString("id"));
                                    album.setAlbumName(dataObj.getString("name"));
                                    album.setImageUrl("https://graph.facebook.com/" + dataObj.getString("cover_photo") + "/picture?type=normal"
                                            + "&access_token=" + AccessToken.getCurrentAccessToken().getToken());

                                    fbAlbums.add(album);
                                }
                                lv.setAdapter(adapter);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else
                            StaticFunctions.message(con,"Bir Hata Oluştu");
                linlaHeaderProgress.setVisibility(View.GONE);
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "albums{id,cover_photo,name}");
    request.setParameters(parameters);
    request.executeAsync();

}

答案 2 :(得分:2)

我使用了SafaGürdag的功能,只包含一个小错误或不推荐的电话,因为我写作的日期如下所示。而不是使用:

    album.setImageUrl("https://graph.facebook.com/" + dataObj.getString("cover_photo") 
+ "/picture?type=normal" + "&access_token=" + AccessToken.getCurrentAccessToken().getToken());

我将其替换为:

    album.setImageUrl("https://graph.facebook.com/" + dataObj.getString("id")
 + "/picture?type=thumbnail" + "&access_token=" + AccessToken.getCurrentAccessToken().getToken());