php - Lazy Load listview Item from server json response -
i'm developing android app load data server json parser.i want load data in 10 item part server , when user scroll down listview new 10 item part load server , add current listview(such market apps).
here java code:
public class allproductsactivity extends listactivity { //jpcode int part=0; string refreshnumber="0"; //convert shamsi roozh jcal = new roozh(); string myjpdiff; imagebutton btnnewproduct; view ntcheck; private sessionmanager session; private button logout; //internet check jp // flag internet connection status boolean isinternetpresent = false; // connection detector class connectiondetector cd; //end internet check jp private sqlitehandler db; //jpcode //end jpcode // progress dialog private progressdialog pdialog; // creating json parser object jsonparser jparser = new jsonparser(); arraylist<hashmap<string, string>> productslist; // url products list private static string url_all_products = "http://www.jpdesign.ir/android_login_api/ac/get_all_products.php"; // json node names private static final string tag_success = "success"; private static final string tag_products = "products"; private static final string tag_pid = "pid"; private static final string tag_name = "name"; //jpcode private static final string tag_auth = "auth"; private static final string tag_hit = "hit"; private static final string tag_date = "created_at"; private static final string tag_jptime = "jptime"; private static final string tag_jppart = "part"; private textview txtname; // products jsonarray jsonarray products = null; typeface jpfont; public pulltorefreshlistview listview; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); overridependingtransition(r.anim.push_right_in,r.anim.push_right_out); setcontentview(r.layout.all_products); jpfont = typeface.createfromasset(getassets(), "fonts/yekan.ttf"); textview fakedate= (textview) findviewbyid(r.id.textview1); fakedate.settypeface(jpfont); // sqlite database handler db = new sqlitehandler(getapplicationcontext()); // session manager session = new sessionmanager(getapplicationcontext()); //jpcode //adding slidemenu final slidingmenu menu = new slidingmenu(this); menu.setmode(slidingmenu.right); menu.settouchmodeabove(slidingmenu.touchmode_fullscreen); menu.setshadowwidthres(r.dimen.shadow_width); menu.setshadowdrawable(r.drawable.shadowright); menu.setbehindoffsetres(r.dimen.slidingmenu_offset); menu.setfadedegree(0.35f); menu.attachtoactivity(this, slidingmenu.sliding_content); menu.setmenu(r.layout.slide_layout); imagebutton iconfehrest = (imagebutton) findviewbyid(r.id.sliding); // name of user // fetching user details sqlite hashmap<string, string> user = db.getuserdetails(); string name = user.get("name"); string email = user.get("email"); txtname = (textview) findviewbyid(r.id.mnt); // displaying user details on screen log.d("log", name +" , "+email); txtname.settext(name); //txtemail.settext(email); ///end name iconfehrest.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { menu.toggle(); } }); //end slide menu //jpcode logout= (button) findviewbyid(r.id.ulogout); logout.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { logoutuser(); } }); final view ntcheck = findviewbyid(r.id.net_check); ntcheck.setvisibility(view.gone); // creating connection detector class instance cd = new connectiondetector(getapplicationcontext()); // internet status isinternetpresent = cd.isconnectingtointernet(); imagebutton ntchecker= (imagebutton) findviewbyid(r.id.nt_check); ntchecker.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { // todo auto-generated method stub intent = new intent(allproductsactivity.this,allproductsactivity.class); startactivity(i); } }); //jp pull refresh strictmode.threadpolicy policy = new strictmode.threadpolicy.builder() .detectall().penaltylog().build(); strictmode.setthreadpolicy(policy); listview = (pulltorefreshlistview) getlistview(); listview.setonrefreshlistener(new onrefreshlistener() { //@override public void onrefresh() { // work refresh list here. productslist = new arraylist<hashmap<string, string>>(); // loading products in background thread new loadallproducts().execute(); pdialog.hide(); } }); // end of jp pull refresh // check internet status if (isinternetpresent) { // internet connection present // make http requests // hashmap listview productslist = new arraylist<hashmap<string, string>>(); ntcheck.setvisibility(view.gone); //hide internet checker // loading products in background thread new loadallproducts().execute(); } else { // internet connection not present // ask user connect internet log.d("no internet connection", "you don't have internet connection."); //toast.maketext(this, "you don't have internet connection.", toast.length_long).show(); ntcheck.setvisibility(view.visible); } btnnewproduct = (imagebutton) findviewbyid(r.id.newpost); imagebutton searchbtn = (imagebutton) findviewbyid(r.id.searchbtn); btnnewproduct.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { // launching create new product activity intent = new intent(allproductsactivity.this, newproductactivity.class); startactivity(i); } }); //end of jp // hashmap listview //jpdast productslist = new arraylist<hashmap<string, string>>(); // loading products in background thread //jpdast new loadallproducts().execute(); // listview listview lv = getlistview(); // on seleting single product // launching edit product screen lv.setonitemclicklistener(new onitemclicklistener() { @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { // getting values selected listitem string pid = ((textview) view.findviewbyid(r.id.pid)).gettext() .tostring(); // starting new intent intent in = new intent(getapplicationcontext(), viewpro.class); // sending pid next activity in.putextra(tag_pid, pid); // starting new activity , expecting response startactivityforresult(in, 100); } }); //jp scroller //add footer before adding adapter, else footer not load! // view footerview = ((layoutinflater)this.getsystemservice(context.layout_inflater_service)).inflate(r.layout.footer, null, false); // this.getlistview().addfooterview(footerview); //here magic happens lv.setonscrolllistener(new onscrolllistener() { listadapter adapter = new simpleadapter( allproductsactivity.this, productslist, r.layout.list_item, new string[] { tag_pid, tag_name,tag_auth,tag_hit, tag_date}, new int[] { r.id.pid, r.id.name, r.id.auth, r.id.hit, r.id.date } ); @override public void onscroll(abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) { int lastitem = firstvisibleitem + visibleitemcount; int lastitemposition=adapter.getcount(); if ( adapter.getcount() >= 10 && lastitem > adapter.getcount() - 6) { boolean isloading = false; if (!isloading) { if(isinternetpresent){ if(lastitem > lastitemposition){ //productslist = new arraylist<hashmap<string, string>>(); // loading products in background thread new loadallproducts().execute(); //receiveddata(); log.d("log", "jpdesign here"); ((baseadapter) adapter).notifydatasetchanged(); part += 1; } } isloading = true; } } } public void onscrollstatechanged(abslistview view, int scrollstate) {} }); //jp end scroller } // response edit product activity @override protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); // if result code 100 if (resultcode == 100) { // if result code 100 received // means user edited/deleted product // reload screen again intent intent = getintent(); finish(); startactivity(intent); } } /** * background async task load product making http request * */ class loadallproducts extends asynctask<string, string, string> { /** * before starting background thread show progress dialog * */ @override protected void onpreexecute() { super.onpreexecute(); pdialog = new progressdialog(allproductsactivity.this); pdialog.setmessage("در حال دریافت اطلاعات ..."); pdialog.setindeterminate(false); pdialog.setcancelable(false); pdialog.show(); } /** * getting products url * */ protected string doinbackground(string... args) { log.d("log", part+""); list<namevaluepair> params2 = new arraylist<namevaluepair>(); params2.add(new basicnamevaluepair(tag_jppart, "" + part)); jsonobject json2 = jparser.makehttprequest(url_all_products, "post", params2); log.d("post checker: ", json2.tostring()); // building parameters list<namevaluepair> params = new arraylist<namevaluepair>(); // getting json string url jsonobject json = jparser.makehttprequest(url_all_products, "get", params); // check log cat json reponse //log.d("jpdesign products: ", json.tostring()); try { // checking success tag int success = json.getint(tag_success); if (success == 1 ) { //adapter.notifydatasetchanged(); refreshnumber="1"; // products found // getting array of products products = json2.getjsonarray(tag_products); string myjpdate=json.getstring(tag_jptime); // log.d("time test", myjpdate); log.d("time test", products+""); // looping through products //for (int = 0; < products.length(); i++) { (int = 0; < products.length(); i++) { jsonobject c = products.getjsonobject(i); // storing each json item in variable string id = c.getstring(tag_pid); string name = c.getstring(tag_name); //jpcode string auth = c.getstring(tag_auth); string hit = c.getstring(tag_hit); string date = c.getstring(tag_date); //jptime diff string datestart = date; string datestop = myjpdate; date d1 = null; date d2 = null; date jd1 = null; date jd2 = null; date fyear = null; simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss"); simpledateformat jpformat = new simpledateformat("yyyy-mm-dd"); try { d1 = format.parse(datestart); d2 = format.parse(datestop); jd1 =jpformat.parse(datestart); jd2 =jpformat.parse(datestop); dateformat formatter ; formatter = new simpledateformat("yyyy-mm-dd"); fyear = (date)formatter.parse(datestart); // (3) create new string using date format want string ymd = formatter.format(fyear); int len=ymd.length(); string[] myinarray=new string[len]; string fy=string.valueof(ymd.charat(0))+string.valueof(ymd.charat(1))+string.valueof(ymd.charat(2))+string.valueof(ymd.charat(3)); string fm=string.valueof(ymd.charat(5))+string.valueof(ymd.charat(6)); string fd=string.valueof(ymd.charat(8))+string.valueof(ymd.charat(9)); jcal.gregoriantopersian(integer.parseint(fy), integer.parseint(fm), integer.parseint(fd)); string myconverttime= jcal.tostring(); //in milliseconds long diff = d2.gettime() - d1.gettime(); long jpdiff = jd2.gettime() - jd1.gettime(); long diffseconds = diff / 1000 % 60; long diffminutes = diff / (60 * 1000) % 60; long diffhours = diff / (60 * 60 * 1000) % 24; long diffdays = diff / (24 * 60 * 60 * 1000); // 1s=1000 ,1m=60000,1h=3.6e+6 1day = 86400000 if(jpdiff==0 && diff<=60000){ myjpdiff="هم اکنون";} if(jpdiff==0 && diff>60000 && diff<(59*60000)){ myjpdiff=diffminutes+" دقیقه قبل";} if(jpdiff==0 && diff>(60*60000) && diff<(24*59*60000)){ myjpdiff=diffhours+" ساعت قبل";} if(jpdiff==86400000){ myjpdiff=" 1 روز قبل ";} if(jpdiff>86400000){ myjpdiff=myconverttime;} log.d("time test",fy+" "+diff+" "+ jpdiff+" "+diffdays+"day "+diffhours+"hour "+diffminutes+""); } catch (exception e) { e.printstacktrace(); } //end jptime diff // creating new hashmap hashmap<string, string> map = new hashmap<string, string>(); // adding each child node hashmap key => value map.put(tag_pid, id); map.put(tag_name, name); map.put(tag_auth, auth); //jpcode map.put(tag_hit, hit); //jpcode map.put(tag_date, myjpdiff); //jpcode // adding hashlist arraylist productslist.add(map); } } else { refreshnumber="0"; // no products found // launch add new product activity intent = new intent(getapplicationcontext(), newproductactivity.class); // closing previous activities i.addflags(intent.flag_activity_clear_top); startactivity(i); } } catch (jsonexception e) { e.printstacktrace(); } return null; } /** * after completing background task dismiss progress dialog * **/ protected void onpostexecute(string file_url) { // dismiss dialog after getting products pdialog.dismiss(); // updating ui background thread runonuithread(new runnable() { public void run() { /** * updating parsed json data listview **/ // textview dt=(textview) findviewbyid(r.id.date); // dt.settypeface(jpfont); listadapter adapter = new simpleadapter( allproductsactivity.this, productslist, r.layout.list_item, new string[] { tag_pid, tag_name,tag_auth,tag_hit, tag_date}, new int[] { r.id.pid, r.id.name, r.id.auth, r.id.hit, r.id.date } ); // updating listview setlistadapter(adapter); ((pulltorefreshlistview) getlistview()).onrefreshcomplete(); } }); } } //jpcode logout private void logoutuser() { session.setlogin(false); db.deleteusers(); // launching login activity intent intent = new intent(allproductsactivity.this, loginactivity.class); startactivity(intent); finish(); } //end jp logout }
and here php file on server:
<?php header("cache-control: no-cache, must-revalidate"); // http/1.1 header("expires: sat, 26 jul 2014 05:00:00 gmt"); // date in past ?> <?php /* * following code list products */ // array json response $response = array(); // include db connect class require_once __dir__ . '/db_connect.php'; // connecting db $db = new db_connect(); // products products table //jpadd codes $part = $_post['part']; //$part = $_get['part']; $start = $part * 10; $result = mysql_query("select *from products order by`created_at` desc limit $start, 10") or die(mysql_error()); //$result = mysql_query("select *from products order by`created_at` desc") or die(mysql_error()); // check empty result if (mysql_num_rows($result) > 0) { // looping through results // products node $response["jptime"] = date("y-m-d h:i:s"); //$jptime["my_date"]= date("y-m-d h:i:s"); $response["products"] = array(); $response["part"] = $part; while ($row = mysql_fetch_array($result)) { // temp user array $product = array(); $product["pid"] = $row["pid"]; $product["name"] = $row["name"]; //$product["price"] = $row["price"]; //$product["description"] = $row["description"]; $product["created_at"] = $row["created_at"]; //$product["updated_at"] = $row["updated_at"]; //jpcode $product["auth"] = $row["auth"]; $product["hit"] = $row["hit"]; // $my_date = date("y-m-d h:i:s"); // push single product final response array array_push($response["products"], $product); } // success $response["success"] = 1; // echoing json response echo json_encode($response); } else { // no products found $response["success"] = 0; $response["message"] = "محصولی یافت نشد"; // echo no users json echo json_encode($response); } ?>
but when user scroll down list nothing happen
my application code worked: public class product_listing extends fragment { private static final string tag = subcategoryactivity.class.getsimplename(); private static final string tag_imagepath = "imagepath"; private static final string tag_productid = "productid"; private static final string tag_productname = "productname"; private static final string tag_supplierid = "supplierid"; private static final string tag_suppliername = "suppliername"; private static final string tag_category_id = "catid"; private static final string tag_product_count = "productcount"; private progressdialog pdialog; private list<products> catlist = new arraylist<products>(); private listview listview; private productsadapter adapter; int id_count = 0; private int current_page = 0; int mprelast; public product_listing() { } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { return inflater.inflate(r.layout.fragment_product__listing, container, false); } @override public void onactivitycreated(@nullable bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); listview = (listview) getview().findviewbyid(r.id.list1); adapter = new productsadapter(getactivity(), catlist); listview.setadapter(adapter); int currentposition = listview.getfirstvisibleposition(); listview.setselectionfromtop(currentposition + 1, 0); listview.setonscrolllistener(new abslistview.onscrolllistener() { @override public void onscrollstatechanged(abslistview abslistview, int i) { } @override public void onscroll(abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) { int lastitem = firstvisibleitem + visibleitemcount; if(lastitem == totalitemcount){ if (mprelast != lastitem) { mprelast = lastitem; new loadproductdesc().execute(); } } } }); new loadproductdesc().execute(); } private void hidepdialog() { if (pdialog != null && pdialog.isshowing()) { pdialog.dismiss(); pdialog = null; } } class loadproductdesc extends asynctask<string, string, string> { /** * before starting background thread show progress dialog */ @override protected void onpreexecute() { super.onpreexecute(); pdialog = new progressdialog(getactivity()); pdialog.setmessage("getting data ..."); pdialog.setindeterminate(false); pdialog.setcancelable(true); pdialog.show(); } protected string doinbackground(string... args) { httpclient httpclient = new defaulthttpclient(); httpresponse response; string responsestring = null; try { // make http request response = httpclient.execute(new httpget()); statusline statusline = response.getstatusline(); if (statusline.getstatuscode() == httpstatus.sc_ok) { bytearrayoutputstream out = new bytearrayoutputstream(); response.getentity().writeto(out); out.close(); responsestring = out.tostring(); } else { // close connection response.getentity().getcontent().close(); throw new ioexception(statusline.getreasonphrase()); } } catch (exception e) { log.d("test", "couldn't make successful request!"); } return responsestring; } protected void onpostexecute(final string response) { super.onpostexecute(response); // creating volley request obj string s1 = getactivity().getintent().getstringextra("index"); current_page += 1; final string url = "your url link" + s1 + "," + current_page; jsonarrayrequest moviereq = new jsonarrayrequest(url, new response.listener<jsonarray>() { @override public void onresponse(jsonarray response) { log.d(tag, response.tostring()); try { if (isnetworkstatusavialable (getactivity())) { // parsing json (int = 0; < response.length() && response.length() != 0; i++) { jsonobject obj = response.getjsonobject(i); products products = new products(); id_count = id_count + 1; products.setproductname(obj.getstring(tag_productname)); products.setthumbnailurl(obj.getstring(tag_imagepath)); products.setproductid(obj.getint(tag_productid)); products.setsuppliername(obj.getstring(tag_suppliername)); products.setsupplierid(obj.getint(tag_supplierid)); products.setcategoryid(obj.getint(tag_category_id)); string count = obj.getstring(tag_product_count); catlist.add(products); textview textview = (textview) getview().findviewbyid(r.id.listofproducts); textview.settext(string.valueof("total 1 " + id_count + " products listed of " + count)); } } else { toast.maketext(getactivity(),"check internet connectivity!!",toast.length_long).show(); return; } } catch (jsonexception e) { e.printstacktrace(); } catch (nullpointerexception ne) { toast.maketext(getactivity(), "check internet connectivity!!", toast.length_long).show(); } hidepdialog(); // notifying list adapter data changes // renders list view updated data adapter.notifydatasetchanged(); } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { volleylog.d(tag, "error: " + error.getmessage()); hidepdialog(); } }); // adding request request queue appcontroller.getinstance().addtorequestqueue(moviereq); } } public static boolean isnetworkstatusavialable (context context) { connectivitymanager connectivitymanager = (connectivitymanager) context.getsystemservice(context.connectivity_service); if (connectivitymanager != null) { networkinfo netinfos = connectivitymanager.getactivenetworkinfo(); if(netinfos != null) if(netinfos.isconnected()) return true; } return false; } }
Comments
Post a Comment