Android Facebook Albums Display using Facebook Android sdk - android

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

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

old data in the ListView remains there when i bind new values to ListView in android

I have one ListView,I have made a custom adapter for binding data to it,I have made an asynctask in the activity for getting data and display it into the listView,I have two different Urls for the same asyctask ,based on the condition i am using it,Thing is that when i am second time the listView doesn't remove the previous values.
main.java
public class MyMessagesActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
private MessageAdapter msgContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, pro_unit;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_messgaes);
lv = (ListView) findViewById(R.id.list);
tv_switch = (TextView) findViewById(R.id.tv_switch);
header = (Header) findViewById(R.id.header_msg);
menu = (Menu) findViewById(R.id.menu_msg);
menu.setSelectedTab(3);
header.title.setText("Messages");
msgList = new ArrayList<HashMap<String, String>>();
// url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this,
// Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
tv_switch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
tv_switch.setText("Switch to supplier");
new GetMessages().execute();
flag = false;
} else {
tv_switch.setText("Switch to buyer");
new GetMessages().execute();
flag = true;
}
}
});
// AsyncTAsk for Wholesale Product List...!!!
new GetMessages().execute();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
// in = new Intent(getApplicationContext(),
// ProductDetailActivity.class);
/*
* pro_name = ((TextView)
* view.findViewById(R.id.product_label)).getText().toString();
*
* // getting ProductId from the tag...
*
* pro_id = msgList.get(position).get(Const.TAG_PRODUCT_ID);
* pro_name = msgList.get(position).get(Const.TAG_PRODUCT_NAME);
* pro_img = msgList.get(position).get(Const.TAG_PRODUCT_IMG);
* System.out.println(
* ":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY================="
* + pro_name); Toast.makeText(MyMessagesActivity.this,
* pro_name, Toast.LENGTH_SHORT).show();
*/
// startActivity(in);
}
});
}
private class GetMessages extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyMessagesActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
String query = Const.API_MESSAGES;
if (flag) {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=1";
} else {
url = "?customer_id=" + Pref.getValue(MyMessagesActivity.this, Const.PREF_CUSTOMER_ID, "") + "&group_id=2";
}
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
msgArry = new JSONArray(jsonStr);
if (msgArry != null && msgArry.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + msgArry.length());
for (int i = 0; i < msgArry.length(); i++) {
JSONObject c = msgArry.getJSONObject(i);
String custID = c.getString(Const.TAG_CUSTOMER_ID);
String custName = c.getString(Const.TAG_CUSTOMER_NAME);
String proID = c.getString(Const.TAG_PRODUCT_ID);
String email = c.getString(Const.TAG_CUSTOMER_EMAIL);
String photo = Const.API_HOST + "/" + c.getString(Const.TAG_PHOTO);
String subject = c.getString(Const.TAG_SUBJECT);
String msg_read = c.getString(Const.TAG_MESSAGE_READ);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CAT_ID, custID);
message.put(Const.TAG_CUSTOMER_NAME, custName);
message.put(Const.TAG_PRODUCT_ID, proID);
message.put(Const.TAG_CUSTOMER_EMAIL, email);
message.put(Const.TAG_PHOTO, photo);
message.put(Const.TAG_SUBJECT, subject);
message.put(Const.TAG_MESSAGE_READ, msg_read);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(MyMessagesActivity.this, "No messgaes found", "yehki", "Ok");
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
}
}
}
Please help me for it,thank you eve-one
Try to remove the old records from your HashMap arraylist as below to remove all the data from arraylist.
After binding the data into ListView just clear your arraylist as below:
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
msgContent.notifyDataSetChanged();
lv.setAdapter(msgContent);
msgList.clear();
}
just clear your list
add mgList.clear(); in protected void onPreExecute()..
Put these lines in OnCreate() method itself,
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
Use this line in onPostExecute() of the AsynTask class,
msgContent.notifyDataSetChanged();
If this doesn't work try to add static keyword before msglist variable.
In your doInBackground() add below line before starting for loop:
msgList.clear();
You need to call msgList.clear(); before add data in to msgList arrayList. After that in onPostExecute() method just check condition while set adapter in to listview,
try {
if (msgList!= null
&& msgList.size() > 0) {
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);
msgContent.notifyDataSetChanged();
} else {
Toast.makeText(YourActivityName.this,
"No Data connection", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
Clearing the msgList is not worked for me. And use
msgList = new ArrayList>();
in doInBackground() before you adding the new content to the list. And just an info, there is no need to call notifyDataSetChanged() when you set a new instance of the adapter to a listview(And there is no problem if you called the notifyDataSetChanged).
msgContent = new MessageAdapter(MyMessagesActivity.this, msgList);
lv.setAdapter(msgContent);

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.

How to get Facebook user photo albums using graph api?

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.

Categories

Resources