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");
}
Related
In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
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 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());
Following is my coding for downloading the data from web and on post execute I save it to DB and then update the ListAdapter for GUI.
Problem is when saving to the DB, screen freezes for the time it is getting saved in DB and for 600 records it is about 20 secs.
Please let me know, how can I change this, so that UI do not freeze.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
try {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
if((result==null)|| result.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
long endTime = System.currentTimeMillis();
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
}
}
catch (JSONException e) {
Log.e("log tag", "Error parsing data" + e.toString());
}
}
}
Changed Code as Suggested, screen do not freeze now, but I f I move to another screen , it crashes on the post execute.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("value of the response"+response);
//adding new */
if((response==null)|| response.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray;
try {
jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
System.out.println("All the not empty");
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
System.out.println("im area of tarinin");
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
System.out.println("Time for one JSON parsing "
+ (System.currentTimeMillis() - insideStart));
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog.dismiss();
}
}
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
System.out.println("category id on lcick listnere inside the post ecexute" + category_id);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
The database operation should be done in doInBackground()
Just like LuxuryMode says, all blocking operations need to be in background.
The problem with your approach is that you put all this in Activity, lifecycle of which is not appropriate for background operations.
Create application model that lives outside (usually in Application subclass) and move your AsyncTask there. In Activities bind to that model using simple pattern like observer/callback to update your Adapter.
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.