How to get Facebook user photo albums using graph api? - android

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

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.

Related

How to get position of listitem using setonitemclicklistener and send to next activity

In my app I am getting response from server and displayint it in listview, now what I am trying is when user click on listitem it should get position of it and need to send it to next activity, but it is not working.
Following is mt snippet code
btn_go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// listView1.removeAllViews();
listView1.setAdapter(null);
arraylist_oper = new ArrayList<HashMap<String, String>>();
// listView1.notify();
new getOperationalControlList().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
});
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
//qr = ((String) listView1.getItemAtPosition(position)).toString();
Intent intent=new Intent(OperationalControl.this,DispatchTracking.class);
intent.putExtra("arrow_val", "2");
intent.putExtra("qrcodes", qr);
Toast.makeText(OperationalControl.this, qr, Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
class getOperationalControlList extends AsyncTask<String, String, String> {
private String msg = "";
int register_error = 1;
JSONArray operation;
JSONObject obc;
String error;
String access_token, office_name, office_id;
String user_id;
String name;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(OperationalControl.this);
progressDialog.setCancelable(true);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
noresponse.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObjSend;
String content = null;
arraylist_oper = new ArrayList<HashMap<String, String>>();
try {
consts.pref = getSharedPreferences("pref", MODE_PRIVATE);
consts.editor = consts.pref.edit();
String OperationalControlList_URL = ((consts.pref
.getString(consts.Base_URL,
consts.Base_URL)) + consts.OperationalControlList_URL);
Log.d("OperationalControlList_URL url:",
OperationalControlList_URL);
arraylist = new ArrayList<HashMap<String, String>>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(OperationalControlList_URL);
System.out.println("URL :-"
+ consts.OperationalControlList_URL.toString());
user_id = consts.pref.getString("user_id", "");
access_token = consts.pref.getString("access_token", "");
office_id = consts.pref.getString("office_id", "");
date = date_dropdown.getText().toString();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(
5);
nameValuePair.add(new BasicNameValuePair("user_id", user_id));
nameValuePair.add(new BasicNameValuePair("access_token",
access_token));
nameValuePair.add(new BasicNameValuePair("filter", filter));
nameValuePair
.add(new BasicNameValuePair("office_id", office_id));
nameValuePair.add(new BasicNameValuePair("date", date));
// Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("USER_ID : " + user_id.toString());
System.out.println("access_token : "
+ access_token.toString());
System.out.println("filter : " + filter.toString());
System.out.println("office_id : " + office_id.toString());
System.out.println("date : " + date.toString());
content = EntityUtils.toString(entity);
Log.d("aaa", content);
jsonObjSend = new JSONObject(content.toString());
if (jsonObjSend.getString("status").equals("2")) {
register_error = 1;
error = jsonObjSend.getString("error");
if (error.equals("3")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("4")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("5")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("6")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("7")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("8")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("9")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("10")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("11")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("12")) {
msg = jsonObjSend.getString("message");
} else {
msg = jsonObjSend.getString("message");
}
// {"status":1,"message":"There is no activity of the selected day and filtering otpions"}
} else if (jsonObjSend.getString("status").equals("1")) {
if (jsonObjSend.has("message"))
msg = jsonObjSend.getString("message");
// msg = jsonObjSend.getString("message");
register_error = 0;
operation = new JSONArray();
if (jsonObjSend.has("list")) {
operation = jsonObjSend.getJSONArray("list");
// arraylist_oper = new ArrayList<HashMap<String,
// String>>();
for (int i = 0; i < operation.length(); i++) {
map = new HashMap<String, String>();
qr = operation.getJSONObject(i)
.getString("qrcode");
type = operation.getJSONObject(i)
.getString("type").toString();
Log.d("Types", type);
String origin = operation.getJSONObject(i)
.getString("origin");
String destiny = operation.getJSONObject(i)
.getString("destiny");
String stop_status = operation.getJSONObject(i)
.getString("stop_status");
String stop_status_name = operation
.getJSONObject(i).getString(
"stop_status_name");
String stop_status_color = operation
.getJSONObject(i).getString(
"stop_status_color");
map.put("qrcode", qr);
map.put("type", type);
map.put("origin", origin);
map.put("destiny", destiny);
map.put("stop_status", stop_status);
map.put("stop_status_name", stop_status_name);
map.put("stop_status_color", stop_status_color);
// map.put("status_name", status_name);
arraylist_oper.add(map);
Log.d("qrcode:", qr + " type: " + type
+ " origine: " + origin);
}
} else {
msg = jsonObjSend.getString("message");
}
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if (error.equals("6")) {
Intent intent=new Intent(OperationalControl.this,LoginActivity.class);
startActivity(intent);
OperationalControl.this.finish();
}
try {
if (arraylist_oper.size() > 0) {
Operational_LazyAdapter adpt = new Operational_LazyAdapter(
getApplicationContext(), arraylist_oper);
listView1.setAdapter(adpt);
// Toast.makeText(getApplicationContext(), msg,
// Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Office não definir corretamente ou" + msg,
Toast.LENGTH_LONG).show();
noresponse.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Response
{"status":1,
"list":[{
"qrcode":"#00000757-00000277-700101-0000000040",
"type":"Tipo de Opera\u00e7\u00e3o: Chegada",
"origin":"Origem: ARMAMAR (757)",
"destiny":"Destino: REGUA (277)",
"stop_status":6,
"stop_status_name":"Finalizado",
"stop_status_color":"#cccccc"
},
{
"qrcode":"#00000278-00000277-700101-0000000041",
"type":"Tipo de Opera\u00e7\u00e3o: Chegada",
"origin":"Origem: LAMEGO (278)",
"destiny":"Destino: REGUA (277)",
"stop_status":6,
"stop_status_name":"Finalizado",
"stop_status_color":"#cccccc"
}]
}
On the Intent you create on the list item click listener you should add all variables you need.
In your case add
intent.putExtra("position", position);
In your DispatchTracking Activity use
int position = getIntent().getExtras().getInt("position");
Just you need to pass your HashMap Arraylist to next Activity. Like,
intent.putExtra("myList",arraylist_oper);
and in your next Activity just retrieve as
Intent intent = getIntent();
ArrayList<HashMap<String,String>> mylist = (ArrayList<HashMap<String, String>>)intent.getSerializableExtra("myList");
EDIT :
You need to pass your qrCode too next Activity
intent.putExtra("qrcodes", arraylist_oper.get(position).get("qrcode")));
Now retrieve in next activity as
String qrCode = intent.getStringExtra("qrcodes");
Now check your retrivable arraylist in your second activity using For loop.
for(int i=0; i < myList.size ; i++) {
if(qrCode.equals(myList.get(i).get("qrcode"))){
// get your data here you can get according to qrCode. Like
String density = myList.get(i).get("destiny"); // same for others
}

Facebook GraphRequest get list of albums or create one android

Facebook has recently updated their SDK to V 2.0,In effect my app must be upgraded to make calls to v2.0 or greater.
Some modifications are
*Session is replaced by Accesstoken.
So far i can login and post a video/images using GraphRequest API on their account.next step is getting user's list of albums
The doc says
/* 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();
but updated SDK doesn't has Request API neither it allows session or am i interpreting it wrong?
Has anyone found the solution yet?
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.
I use this method for fetching facebook albums. It has no paging process. Working good for me.
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();
}
I used the function from Safa Gürdag and contains just one little error or deprecated call, for the date I am writing works like below. Instead of using:
album.setImageUrl("https://graph.facebook.com/" + dataObj.getString("cover_photo")
+ "/picture?type=normal" + "&access_token=" + AccessToken.getCurrentAccessToken().getToken());
I replace it with:
album.setImageUrl("https://graph.facebook.com/" + dataObj.getString("id")
+ "/picture?type=thumbnail" + "&access_token=" + AccessToken.getCurrentAccessToken().getToken());

Android Facebook Albums Display using Facebook Android sdk

I am building an android app in which i am using facebook android sdk to get login into facebook. The login part went smoothly but now i am hang how to display albums in gridview after getting login into facebook. When all albums would get display in grid view, then when i click on any one album it must opened with check box on top left of each image . So that when i check the check box of particular image it must be saved in device sd card and other functionality the checked images must get collage in table layout having tablerow & background color for each table row. I will attach some files so you can have idea what i want. Hoping for your positive reply for the same. So please send full source code for the same. I am trying it from last 20 days but i didnt succeed :-( Hoping for the reply soon.
enter code herepublic class Albums extends Activity{
private static final String APP_ID = "1403104849907306";
private Facebook facebook = new Facebook(APP_ID);
// HOLD THE URL TO MAKE THE API CALL TO
private String URL;
// STORE THE PAGING URL
private String pagingURL;
// FLAG FOR CURRENT PAGE
int current_page = 1;
// BOOLEAN TO CHECK IF NEW FEEDS ARE LOADING
Boolean loadingMore = true;
Boolean stopLoadingData = false;
ArrayList<getAlbums> arrAlbums = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
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... arg0) {
// 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/" + "100005623513169"
+ "/photos&access_token="
+ facebook.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");
// IN MY CODE, I GET THE NEXT PAGE LINK HERE
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/"
+ "100005623513169" + "/albums&access_token="
+ facebook.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="
+ facebook.getAccessToken());
} else {
albums.setAlbumCover("https://graph.facebook.com/"
+ JOAlbums.getString("id")
+ "/picture?type=album"
+ "&access_token="
+ facebook.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) {
ListView lv = null;
ListAdapter adapter = null;
// 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);
}
}
class loadMoreAlbums extends AsyncTask<Void, Void, Void> {
LinearLayout linlaProgressBar = (LinearLayout)findViewById(R.id.linlaProgressBar);
#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/"
+ "100005623513169" + "/albums&access_token="
+ facebook.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="
+ facebook
.getAccessToken());
} else {
albums.setAlbumCover("https://graph.facebook.com/"
+ JOAlbums.getString("id")
+ "/picture?type=album"
+ "&access_token="
+ facebook
.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) {
AdapterView<ListAdapter> lv = null;
// 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
AlbumsAdapter adapter = new AlbumsAdapter(Albums.this, arrAlbums);
lv.setAdapter(adapter);
// Setting new scroll position
((ListView) 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);
}
}
}
}
You should use Facebook SDK 3.0+ for Android, and take advantage of their Request.executeAsync() method. After logging the user into the app and retrieving the Session object, you can make requests on the Graph API. Here is my method for requesting a user's albums:
/**
* Makes a request for user's photo albums from Facebook Graph API
* #param session
*/
private void fetchAlbumsFromFB(Session session) {
// callback after Graph API response with user object
Request.GraphUserCallback graphUserCallback;
graphUserCallback = new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
JSONObject jsonObject = null;
if (user != null)
jsonObject = user.getInnerJSONObject();
ImageAdapter.getInstance().setPhotoAlbums(jsonObject);
}
};
// assign callback to final instance variable in inner class
final Request.GraphUserCallback finalCallback = graphUserCallback;
Request.Callback wrapperCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
finalCallback.onCompleted(response.getGraphObjectAs(GraphUser.class), response);
}
};
// make a new async request
Bundle params = new Bundle();
params.putString("fields", "photos");
Request request = new Request(session, "me/albums", params, null, wrapperCallback);
request.executeAsync();
}
Then you can parse the JSON response like this:
/**
* Updates the array with cover photos from albums
*
* #param photosObject
*/
public void setPhotoAlbums(JSONObject photosObject) {
try {
mPhotoAlbumsArray = photosObject.getJSONArray("data");
coverPhotosArr = new String[mPhotoAlbumsArray.length()];
for (int i = 0; i < mPhotoAlbumsArray.length(); i++) {
JSONObject obj1 = mPhotoAlbumsArray.getJSONObject(i);
JSONObject obj2 = (JSONObject) obj1.get("photos");
JSONArray obj3 = obj2.getJSONArray("data");
JSONObject obj4 = obj3.getJSONObject(0);
String picture = String.valueOf(obj4.get("picture"));
coverPhotosArr[i] = picture;
}
// notify GridView's adapter that underlying data has been changed
notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}

Is it possible to have access to Facebook gallery and let the user select an image?

I think title is self descriptive. In my application I have a log-in form. Based on request, users should be able to set their image of profile via Facebook.
So, my question is, is it possible to show gallery images of users inside application and let users to select an image from it?
I have checked Facebook SDK and goggled as well but those information that I found was base on uploading image to Facebook by Graph.
Any suggestion/comments would be appreciated.
Have you checked this answer here:
ImageView user_picture;
userpicture=(ImageView)findViewById(R.id.userpicture);
URL img_value = null;
img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
userpicture.setImageBitmap(mIcon1);
You may see this too.
Edit
I think this shall work to load albums, but the only difference is that you need an access token. This means you can fetch the album of the user only if this user is logged into Facebook. The following code has an AsyncTask called getAlbumsData. Within that look into the doInBackground.It fetches JSON and on onPostExecute,you would see it is loading the album into a listview which was already defined earlier.
Here is the (simple) sample code
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 more help, look into the original answer. If still you need more then there's a full working source code with explanation. Though that's a bit more confusing than the answer I referred.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget

In my application I am displaying facebook wall stream, I am using Facebook Graph API to get the data of each post.
Sometimes when I scroll the list fastly, I am getting the OutOfMemoryerror. I really don't know what the techniques are used by facebook applications to display the wall data.
Can I know about the techniques used by them?
I am getting data from Facebook as pages form. So, I am displaying all the data in the page at once. How can I display only limited data, as we can see with facebook apps?
class doInBack extends AsyncTask<URL, Integer, Long>
{
protected void onPreExecute()
{ if(boolDialog){
dialog=MyProgressDialog.show(Wall.this, null,null);
}
}
// currentweb= webserv;
#Override
protected Long doInBackground(URL... arg0) {
currentweb=webserv;
Log.e("hi","doback parsing");
try
{
wallres=UrltoValue.getValuefromUrl(currentweb);
Log.i("wallrespages",wallres);
JSONObject jobj1=new JSONObject(wallres);
JSONObject jobj2=jobj1.getJSONObject("paging");
webserv= jobj2.getString( "next");
jsonArray = jobj1.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
if(jsonObject.has("message")||jsonObject.has("picture")) {
try{
// msg[j]=jsonObject.getString("message");
if(jsonObject.has("message"))
{
msg.add(jsonObject.getString("message"));
}
else{
msg.add("");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
// msg[j]=jsonObject.getString("message");
if(jsonObject.has("picture"))
{
String firstpicture=jsonObject.getString("picture");
String secondpicture=firstpicture.replaceAll("_s.jpg", "_n.jpg");
Log.e("picurl",secondpicture);
pic.add(secondpicture);
}
else{
pic.add("");
}
}
catch(Exception e){
e.printStackTrace();
} objid.add(jsonObject.getString("id"));
JSONObject jobj=jsonObject.getJSONObject("from");
name.add(jobj.getString("name"));
id.add(jobj.getString("id"));
if(jsonObject.getString("type").equals("checkin")){
name.set(i,jobj.getString("name")+" "+"is at"+" "+jsonObject.getString("name"));
}
profimg.add("http://graph.facebook.com/"+id.get(j)+"/picture?type=square");
JSONObject commentjobj=jsonObject.getJSONObject("comments");
comment.add(commentjobj.getString("count"));
if(jsonObject.has("likes")) {
Log.e("likeornot","likre");
JSONObject likesjobj=jsonObject.getJSONObject("likes");
likes.add(likesjobj.getString("count"));
String postid=jsonObject.getString("id");
// graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'" + postid + "'";
// Log.d("finalThreadID", finalThreadID);
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
// Utility.mAsyncRunner.request(null, params, new LikesListener());
String fqlResponse = Login.mFacebook.request(params);
System.out.println(fqlResponse);
JSONArray JOLikeresponse=new JSONArray(fqlResponse);
if(JOLikeresponse.length()!=0){
JSONObject JOLikeObject = JOLikeresponse.getJSONObject(0);
if ( JOLikeObject.has("likes")) {
String optlike,optlikesarray;
JSONObject optLikes=JOLikeObject;
JSONArray optLikesArray;
try{
optLikes = JOLikeObject.getJSONObject("likes");
optlike="like";
}
catch(Exception e){
optlike="unlike";
}
//
if(optlike.equals("like")){
if (optLikes.has("user_likes")) {
String getUserLikes = optLikes.getString("user_likes");
if (getUserLikes.equals("true")) {
like_or_unlike.add("Unlike");
} else if (getUserLikes.equals("false")) {
like_or_unlike.add("Like");
}
}
else {
like_or_unlike.add("Like");
}
} else {
like_or_unlike.add("Like");
}
}
//if likes object is not there in like response
else {
like_or_unlike.add("Like");
}
}
//if the like response Array length is zero
else {
like_or_unlike.add("Like");
}//FQL query object
}
//If likes are not there
else{
likes.add("0");
like_or_unlike.add("Like");
}
weburl.add(currentweb);
Log.e("comment", comment.get(j));
// bitmap[j]= getBitmapFromURL(profimg[j]);
// profimg1.setImageBitmap(bitmap[j]);
// imageLoader.DisplayImage( profimg[j].replace(" ", "%20"), profimg1) ;
// System.out.println( bitmap[j]);
// j++;
// f=j;
String getCreatedTime = jsonObject.getString("created_time");
// long finalTimeStamp = Long.valueOf(getCreatedTime);
// SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
// String timestamp = dateFormatter.format(new Date(finalTimeStamp * 1000L));
SimpleDateFormat formatter = getDateFormat();
ParsePosition pos = new ParsePosition(0);
long then = formatter.parse(getCreatedTime, pos).getTime();
long now = new Date().getTime();
long seconds = (now - then)/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
String friendly = null;
long num = 0;
if (days > 0) {
num = days;
friendly = days + " day";
} else if (hours > 0) {
num = hours;
friendly = hours + " hour";
} else if (minutes > 0) {
num = minutes;
friendly = minutes + " minute";
} else if(seconds>0) {
num = seconds;
friendly = seconds + " second";
}
else{
friendly = "few seconds";
}
if (num > 1) {
friendly += "s";
}
String postTimeStamp = friendly.toLowerCase() + " ago";
Log.e("date",postTimeStamp );
date.add(postTimeStamp);
j++;
}
}
// if(jsonObject.getString("message")!=""){
// msg[i]=jsonObject.getString("message");
//
// JSONObject jobj=jsonObject.getJSONObject("from");
// name[i]= jobj.getString("name");
// id[i]=jobj.getString("id");
// Log.e("msg",msg[i]);
// Log.e("name",name[i]);
// Log.e("id",id[i]);
// }
//
// }
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Long result) {
try
{ if(addFooter){
listView.addFooterView(footerView);
}
addFooter=false;
System.out.println(scroll);
if(scroll){
adapter=new MySimpleArrayAdapter(Wall.this,R.layout.wall,pic,name,msg,id,profimg,comment,objid,weburl,likes, like_or_unlike,date);
listView.setAdapter(adapter);
listView.postDelayed(new Runnable() {
// #Override
public void run() {
listView.onRefreshComplete();
}
}, 2000);
if(boolDialog){
dialog.dismiss();
}
}
else{
// adapter=new MySimpleArrayAdapter(Wall.this,R.layout.wall,pic,name,msg,id,profimg,bitmap,comment,objid,weburl);
adapter.notifyDataSetChanged();
listView.postDelayed(new Runnable() {
// #Override
public void run() {
listView.onRefreshComplete();
}
}, 2000);
}
if(boolDialog){
dialog.dismiss();
}
}
catch(Exception e)
{
e.printStackTrace();
if(boolDialog){
dialog.dismiss();
}
}
boolDialog=false;
}
}
private static SimpleDateFormat getDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
}

Categories

Resources