DownloadManager error 416 not found in Android while download file - android

i have a problem. I want to download file from web server database MySQL. I use JSON to parse url of the file. But when i try to download, it always return 416.
What's the problem? My code or how i store the file url in database?
My error
05-22 21:22:41.615: WARN/DownloadManager(262): Aborting request for download 15: http error 416
This is my onCreate code
super.onCreate(savedInstanceState);
//cek koneksi internet
cd = new ConnectionDetector(this);
IsConnected = cd.isConnectingToInternet();
Bundle b = getIntent().getExtras();
konteksCocok = b.getString("kts_cocok");
Log.d("konteks datang", "data: " + konteksCocok);
if(IsConnected) {
new downloadFile().execute(urlBerkas);
} else {
showAlertDialog(this, "Koneksi Gagal", "Tidak ada koneksi internet", false);
}
This is my json and download manager code
class downloadFile extends AsyncTask<String, String, String> {
int count;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(unduhBerkas.this);
progress.setMessage("Mengambil data...");
progress.setIndeterminate(false);
progress.setCancelable(false);
progress.show();
}
#Override
protected String doInBackground(String... xUrl) {
// TODO Auto-generated method stub
//mendapatkan data dari database berupa detail berkas
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("konteks", konteksCocok));
Log.d("konteks kirim", "data: " + konteksCocok);
JSONObject json = jParser.makeHttpRequest(url_webservice, "POST", params);
Log.d("data: ", json.toString());
//menampilkan data lokasi POI
try {
int sukses = json.getInt(TAG_SUCCESS);
if(sukses == 1) {
POI = json.getJSONArray(TAG_BERKAS);
for(int i = 0; i < POI.length(); i++) {
JSONObject c = POI.getJSONObject(i);
nama = c.getString(TAG_NAMA_PENGGUNA);
konteks = c.getString(TAG_KONTEKS_BERKAS);
urlBerkas = c.getString(TAG_URL_BERKAS);
namaBerkas = c.getString(TAG_NAMA_BERKAS);
Log.d("namaDB", "data: " + nama);
Log.d("ktsDB", "data: " + konteks);
Log.d("urlDB", "data: " + urlBerkas);
Log.d("berkasDB", "data: " + namaBerkas);
}
try {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String url = "http://10.0.2.2/locRemService/berkas/" + urlBerkas;
Request request = new Request(Uri.parse(url));
enqueue = dm.enqueue(request
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nama));
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
Log.d("data downloaded", "sukses");
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE)
);
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
} else {
Log.d("JSON error", "JSON trouble");
}
} catch(JSONException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
Toast.makeText(getApplicationContext(), "Unduh Berkas...", Toast.LENGTH_LONG).show();
}
#Override
protected void onPostExecute(String result) {
progress.dismiss();
}
}
Anybody can help?? Thanks for the help...

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

getting error java.io.FileNotFoundException:

I am trying to read phone contacts and send that list to my server, but getting FileNotFound error in some phones but programme is working properly in some phones. following is my class -
public class UpdateNetwork extends Activity {
private String server, server_response;
private String updatenetwork = "/update-network.php";
private String data_to_send;
public JSONArray jacontacts;
public JSONObject jcontacts;
public ArrayList<String> contacts;
private ProgressDialog pd;
private Long user_id;
private MainActivity main;
JSONObject jo = null;
Button update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatenetwork);
server = getString(R.string.server_add_new);
contacts = new ArrayList<String>();
main = new MainActivity();
update = (Button) findViewById(R.id.update);
update.setVisibility(View.INVISIBLE);
user_id = main.getDefaultsint("user_id", UpdateNetwork.this);
Updatenetwork un = new Updatenetwork(true);
un.execute();
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
URL url = null;
try {
url = new URL(server + updatenetwork);
data_to_send = "contacts=" + jcontacts + "&";
data_to_send += "user_id=" + user_id;
Updatenetwork un = new Updatenetwork(url, data_to_send);
un.execute();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class Updatenetwork extends AsyncTask<String, Integer, JSONObject> {
private URL url;
Boolean un_send = false;
String data_to_send;
public Updatenetwork(Boolean b) {
this.un_send = b;
}
public Updatenetwork(URL url, String data_to_send2) {
this.url = url;
this.data_to_send = data_to_send2;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (un_send) {
update.setVisibility(View.VISIBLE);
} else {
finish();
}
pd.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(UpdateNetwork.this, "Please wait...", "Sending...");
}
#Override
protected JSONObject doInBackground(String... params) {
Log.e("value of un_send", "********"+un_send+jcontacts);
if(un_send){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
/* System.out.println("name : " + name );
*/
// get <span id="IL_AD4" class="IL_AD">the phone number</span>
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(phone);
jacontacts = new JSONArray();
/* System.out.println("phone" + phone);*/
}
for(int i=0; i<contacts.size(); i++){
jacontacts.put(contacts.get(i));
}
jcontacts = new JSONObject();
try{
jcontacts.put("contacts", jacontacts);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Log.e("value inside", "json obj"+jcontacts);*/
pCur.close();
jo = jcontacts;
}
}
}
} else {
BufferedReader reader=null;
try
{
Log.e("inside try block ", "get text 11111111" + data_to_send);
URLConnection conn = url.openConnection();
Log.e("inside try block ", "get text 2222222" + data_to_send);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside ", "while loop");
}
server_response = sb.toString();
Log.e("server_response ", "server_response" +server_response);
}
catch(FileNotFoundException(String detailMessage))
{
Log.e("MyTag ", "Failure to get json data in --1--", ex);
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {
Log.e("MyTag", "Failure to get json data in ", ex);
}
}
try {
jo = new JSONObject(server_response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jo;
}
}
}
following is what i got in errorlog
12-18 16:44:21.922: E/MyTag(32005): Failure to get json data in --1--
12-18 16:44:21.922: E/MyTag(32005): java.io.FileNotFoundException: http:// server address/update-network.php
12-18 16:44:21.922: E/MyTag(32005): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:194)

how to refresh the ListView in android when data i appended to ListView

I have made a ListView and made a custom adapter for it,I am calling two Asynctask one for getting all messages from webservice and another is for reply of the message,I want to append the replied message to the ListView. Currently i am not getting it right way. My code is as below:
main.java
import com.epe.yehki.adapter.ChatAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class ChatHistoryActivity extends Activity {
private ProgressDialog pDialog;
JSONArray msgArry;
JSONObject jsonObj;
private ChatAdapter chatContent;
ArrayList<HashMap<String, String>> msgList;
ListView lv;
JSONArray msgs = null;
String pro_id, pro_name, pro_img, grup_id, sender_id, cust_id;
TextView tv_switch;
public boolean flag = false;
Header header;
Menu menu;
Intent in;
Button reply;
RelativeLayout rl_reply;
EditText et_reply;
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_chat_history);
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);
reply = (Button) findViewById(R.id.btn_reply);
rl_reply = (RelativeLayout) findViewById(R.id.rl_reply);
rl_reply.setVisibility(View.GONE);
et_reply = (EditText) findViewById(R.id.et_reply);
menu.setSelectedTab(3);
header.title.setText("Conversation");
msgList = new ArrayList<HashMap<String, String>>();
pro_id = getIntent().getStringExtra(Const.TAG_PRODUCT_ID);
sender_id = getIntent().getStringExtra(Const.TAG_CUSTOMER_ID);
grup_id = getIntent().getStringExtra(Const.TAG_GROUP_ID);
cust_id = Pref.getValue(ChatHistoryActivity.this, Const.PREF_CUSTOMER_ID, "");
/* new GetChatHistory().execute(); */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
rl_reply.setVisibility(View.VISIBLE);
}
});
// message reply ...!!Chat api(conversation)
reply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new DoReply().execute();
// new GetChatHistory().execute();
}
});
}
#Override
protected void onResume() {
super.onResume();
new GetChatHistory().execute();
}
private class GetChatHistory extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.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_CHAT_HISTORY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&sender_id=" + sender_id + "&product_id=" + pro_id;
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 msg_body = c.getString(Const.TAG_MESSAGE_BODY);
HashMap<String, String> message = new HashMap<String, String>();
message.put(Const.TAG_CUSTOMER_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_MESSAGE_BODY, msg_body);
msgList.add(message);
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Utils.showCustomeAlertValidation(ChatHistoryActivity.this, "No messgaes found", "yehki", "Ok");
msgList.clear();
}
});
}
} 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 != null)
pDialog.dismiss();
System.out.println("::::::::::::inside post:::::::::::");
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
}
}
/*
* GET CONVERSATION LIST.........REPLY
*/
private class DoReply extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChatHistoryActivity.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_MESSAGE_REPLY;
url = "?customer_id=" + cust_id + "&group_id=" + grup_id + "&receiver_id=" + sender_id + "&product_id=" + pro_id + "&message=" + et_reply.getText().toString().trim();
url = url.replace(" ", "%20");
url = query + url;
System.out.println(":::::::::::::My MESSGES URL::::::::::::::" + url);
System.out.println(":::::::::::::::get chat history called:::::::::::::;;");
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString("status").equals("sucess")) {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has been sent", Toast.LENGTH_SHORT).show();
}
});
} else {
// et_reply.setText("");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ChatHistoryActivity.this, "Message has not been sent", Toast.LENGTH_SHORT).show();
}
});
}
} 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);
System.out.println("::::::::::::inside post:::::::::::");
// Dismiss the progress dialog
if (pDialog != null)
pDialog.dismiss();
chatContent = new ChatAdapter(ChatHistoryActivity.this, msgList);
chatContent.notifyDataSetChanged();
lv.setAdapter(chatContent);
new GetChatHistory().execute();
}
}
}

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