Android Fragment Executing without being called -
i have app using actionbar sherlock contains 3 tabs respective fragments. when login app, default book buy fragment supposed executed. notice after login executed, sell fragment partially executed. here's flow it's doing: login -> sell frag -> book buy frag -> json parser -> sell frag -> json parser -> book buy -> custom adapter.
the correct flow should be: login -> book buy frag -> json parser -> book buy -> custom adapter.
needless takes while me login first screen. can me strange behavior? keep in mind no tab has been selected @ point.
login java:
public class loginactivity extends activity { //textview text; progressdialog pdialog; string uemaillogin; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.login_scrn); system.out.println("loginactivity starte befoe session"); //declared 2 variables "final" ics compiler recognize them in onclicklistener final edittext useremail = (edittext) findviewbyid(r.id.emailinpt); final edittext userpass = (edittext) findviewbyid(r.id.passwordinpt); final textview text = (textview) findviewbyid(r.id.logerror); button loginbtn = (button) findviewbyid(r.id.loginbtn); button registerbtn = (button) findviewbyid(r.id.registerbtn); //executes code when submit button pressed loginbtn.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { if(useremail.gettext().length()== 0) { text.settext("enter email address"); } else if(userpass.gettext().length()== 0) { text.settext("enter password"); } else { system.out.println("logact check 2"); //start async task here http...because 4.0 can't process data on main ui new checklogin().execute(useremail.gettext().tostring(), userpass.gettext().tostring()); //clears input data off phone screen after login button hit useremail.settext(""); userpass.settext(""); //finish(); } } }); //original end of onclicklistner //}); // link register screen registerbtn.setonclicklistener(new view.onclicklistener() { public void onclick(view view) { intent register = new intent(getapplicationcontext(), registeractivity.class); startactivity(register); finish(); } }); } //class check successful login private class checklogin extends asynctask<string, string, string> { //progress dialog //private progressdialog pdialog; //show progress dialog before starting background thread @override protected void onpreexecute() { super.onpreexecute(); system.out.println("logact onpreexecute started"); pdialog = new progressdialog(loginactivity.this); //might can activity //pdialog = new progressdialog(getactivity());//might can activity pdialog.setmessage("logging in..."); pdialog.setindeterminate(false); pdialog.setcancelable(false); pdialog.show(); //system.out.println("onpreexecute finished"); } //get login info protected string doinbackground(string... arg0) { jsonobject json_data = null; string result = null; inputstream = null; stringbuilder sb = null; //inputstream = null; //opens internet connection , prepares files used in processing defaulthttpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("http://10.0.2.2/bkbarter.php"); //emulator try{ //loads array values sent php code db processing arraylist <namevaluepair> nvps = new arraylist <namevaluepair>(); nvps.add(new basicnamevaluepair("useraction", "login")); nvps.add(new basicnamevaluepair("useremail", arg0[0])); nvps.add(new basicnamevaluepair("userpass", arg0[1])); //stores user email later stored global variable in asynctask uemaillogin = arg0[0]; httppost.setentity(new urlencodedformentity(nvps)); httpresponse response = httpclient.execute(httppost); httpentity entity = response.getentity(); = entity.getcontent(); //shows logcat status response determine if data sent correctly //system.out.println("output = " + response); log.i("onclicklistner", response.getstatusline().tostring()); //clears input data off phone screen after login button hit } catch(exception e){ log.e("log_tag", "error in http connection "+e.tostring()); } //converts variables retrieved string try { bufferedreader reader = new bufferedreader(new inputstreamreader(is,"iso-8859-1"),8); sb = new stringbuilder(); sb.append(reader.readline() + "\n"); string line = "0"; while((line = reader.readline()) != null) { sb.append(line + "\n"); //system.out.println(sb); } is.close(); result = sb.tostring(); system.out.println(result); } catch(exception e) { log.e("log_tag", "error converting result "+e.tostring()); } return result; } //after completing background task, dismiss progress dialog @override protected void onpostexecute(final string result) { // might need (string result) here //super.onpostexecute(result); //jsonobject json_data = null; //dismiss dialog after getting records if(pdialog != null) { pdialog.dismiss(); } loginactivity.this.runonuithread(new runnable() { public void run() { jsonobject json_data = null; string success_resp_code = null; string error_resp_code = null; string useraction = null; //parses string json object try { json_data = new jsonobject(result); //stores json response code success_resp_code = json_data.getstring("success"); error_resp_code = json_data.getstring("error"); useraction = json_data.getstring("useraction"); } catch (jsonexception e) { log.e("login/json parser", "error parsing data " + e.tostring()); } //checks login status success or failure try { //if (json_data.getstring("success") != null) { if (success_resp_code != null) { if(integer.parseint(success_resp_code) == 1){ // user logged in toast.maketext(getapplicationcontext(), "you have logged in", toast.length_short).show(); //calls globals set user email global variable ((globals) getapplicationcontext()).setemaillogin(uemaillogin); //start bookbarter activity intent bookbarter = new intent(getapplicationcontext(), bookbarteractivity.class); startactivity(bookbarter); //close login screen // finish(); }else if (json_data.getstring("error") != null) { if(integer.parseint(error_resp_code) == 1) { //user entered incorrect password toast.maketext(getapplicationcontext(), "incorrect password", toast.length_short).show(); }else if(integer.parseint(error_resp_code) == 2) { //user not exist toast.maketext(getapplicationcontext(), "user not exist", toast.length_short).show(); } } } } catch(exception e) { log.e("log_tag", "error converting result "+e.tostring()); } system.out.println("logact onpostexecute finished"); } }); } } @override protected void onpause() { // todo auto-generated method stub super.onpause(); if(pdialog != null) pdialog.dismiss(); pdialog = null; finish(); } }
book buy frag:
public class buyfragtab extends sherlocklistfragment { //progress dialog private progressdialog pdialog; //creating json parser object jsonparser jsonparser = new jsonparser(); //bookbuy json array jsonarray bookbuyinfo = null; //array of book information arraylist<bookinfo> bookarray = new arraylist<bookinfo>(); //book listview listview booklv; mycustomadapter adapter; //search edittext edittext titlesearch; //dualpane variable boolean mdualpane; int mcurcheckposition = 0; //holder array json data movement public static arraylist<string> bkrecs; context context; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view = inflater.inflate(r.layout.buy_tbfrag, container, false); booklv = (listview)view.findviewbyid(android.r.id.list); //enables filtering contents of given listview booklv booklv.settextfilterenabled(true); //search inputed book title titlesearch = (edittext)view.findviewbyid(r.id.titlesearch); return view; } @override public void onactivitycreated(bundle savedinstancestate){ //super.onactivitycreated(savedinstancestate); //system.out.println("onactivitycreated executed"); bookarray = new arraylist<bookinfo>(); //load bookarray in background thread new loadbookbuyinfo().execute(); view detailsfragment = getactivity().findviewbyid(r.id.details_fragment_container); mdualpane = detailsfragment != null && detailsfragment.getvisibility() == view.visible; //set click listener item clicked in listview booklv.setonitemclicklistener(new onitemclicklistener() { public void onitemclick(adapterview<?> parent, view view, int position, long id){ string selecttitle, selectauthor, selectisbn, selectcond, selectprice = null; string selectseller, selectemail, selectphone, selectcollege = null; //when item clicked, show it's detailed view bookinfo bkrecs = (bookinfo)parent.getitematposition(position); //loads book detail information selecttitle = bkrecs.gettitle(); ...loads data... system.out.println(" title = " + selecttitle + " author = " + selectauthor); //if in dual pane/landscape mode, send selected user information show details display //to screen if (mdualpane) { showdetails(selecttitle, selectauthor, selectisbn, selectcond, selectprice, selectseller, selectemail, selectphone, selectcollege); }else { //if in portrait mode, create intent object start bookdetailsactivity intent bkintent = new intent("com.skipster.bookbarter.bookdetailsactivity"); //setting data (the clicked item's position intent bkintent.putextra("selected_title", selecttitle); ...put data... //start activity startactivity(bkintent); } } }); super.onactivitycreated(savedinstancestate); } //manages screen orientation flips********************************// @override public void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putint("curchoice", mcurcheckposition); } //landscap mode screen processing void showdetails(string title, string author, string isbn, string cond, string price, string seller, string email, string phone, string college){ //instantiating fragment bookdetailsfragment sherlockfragment detailsfragment = new bookdetailsfragment(); //get fragment manager fragment related operations fragmentmanager fm = getfragmentmanager(); //get fragment transaction object, can add, move or replace fragment fragmenttransaction ft = fm.begintransaction(); //creating bundle object pass data (clicked item's position) //from activity fragment bundle b = new bundle(); //loading bundle object b.putstring("selected_title", title); ... //setting/sending bundle object fragment //edited object received , sent displayed detailsfragment.setarguments(b); system.out.println("show details check2"); ft.replace(r.id.details_fragment_container, detailsfragment); system.out.println("show details check3"); ft.settransition(fragmenttransaction.transit_fragment_fade); //allows user press button go in reverse order //works in landscape mode not in portrait ft.addtobackstack(null); //executing transaction ft.commit(); return; } //background asynctask load bookbuyinfo making http request class loadbookbuyinfo extends asynctask<string, string, string> { //show progress dialog before starting background thread @override protected void onpreexecute() { super.onpreexecute(); pdialog = new progressdialog(getactivity());//might can activity pdialog.setmessage("loading books..."); pdialog.setindeterminate(false); pdialog.setcancelable(false); pdialog.show(); } //get bookbuyinfo data protected string doinbackground(string... arg0) { //building parameters arraylist<namevaluepair> bookvalues = new arraylist<namevaluepair>(); system.out.println("doinbackground executed"); //loads user action retrieve book records bookvalues.add(new basicnamevaluepair("useraction", "getr")); //getting json string url, "getr" = entire record jsonobject json = jsonparser.makehttprequest("http://10.0.2.2/bkbarter.php", "getr", bookvalues); //check logcat json response log.d("book buy json: ", json.tostring()); //get json data try { bookbuyinfo = json.getjsonarray("books"); //loop through books , load data (int = 0; < bookbuyinfo.length(); i++) { jsonobject b = bookbuyinfo.getjsonobject(i); string seller = b.getstring("name"); ...book info... //creating new book record bookarray bookinfo bkrecs = new bookinfo(title, author, isbn, cond, price, seller, email, phone, college); //add record arraylist bookarray.add(bkrecs); } } catch (jsonexception e) { e.printstacktrace(); } return null; } //after completing background task, dismiss progress dialog protected void onpostexecute(string file_url) { // might need (string result) here //dismiss dialog after getting records //pdialog.dismiss(); if(pdialog != null) { pdialog.dismiss(); } //update ui background thread //runonuithread(new runnable() { getactivity().runonuithread(new runnable() { public void run() { //updating parsed json data listview adapter = new mycustomadapter(getactivity(), r.layout.buy_tbfrag, bookarray); booklv.setadapter(adapter); //enable search filter search titles each letter inputed titlesearch.addtextchangedlistener(new textwatcher(){ @override public void aftertextchanged(editable cs){ //todo auto generated method-stub } @override public void beforetextchanged(charsequence cs, int start, int count, int after){ //todo auto generated method-stub } @override public void ontextchanged(charsequence cs, int start, int before, int count){ //when user changed text adapter.getfilter().filter(cs.tostring()); system.out.println("ontextchanged executed"); } }); } }); } }
sell frag:
public class sellfragtab extends sherlockfragment { edittext sbktitle, sbkauthor, sbkisbn, sbkcond, sbkphone, sbkprice, sbkcollege; textview text; //progress dialog private progressdialog pdialog; //bookbuy json array jsonarray bookbuyinfo = null; public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { system.out.println("sell frag tab executed"); view view = inflater.inflate(r.layout.sell_tbfrag, container, false); sbktitle = (edittext)view.findviewbyid(r.id.sbooktitle); sbkauthor = (edittext)view.findviewbyid(r.id.sbookauthor); sbkisbn = (edittext)view.findviewbyid(r.id.sbookisbn); sbkcond = (edittext)view.findviewbyid(r.id.sbookcond); sbkphone = (edittext)view.findviewbyid(r.id.sbookphone); sbkprice = (edittext)view.findviewbyid(r.id.sbookprice); sbkcollege = (edittext)view.findviewbyid(r.id.sbookcollege); text = (textview)view.findviewbyid(r.id.regerror); button subbutn = (button)view.findviewbyid(r.id.subbutn); system.out.println("sell frag tab check 2"); subbutn.setonclicklistener(new onclicklistener(){ @override public void onclick(view v){ if (sbktitle.gettext().length() == 0) { text.settext("enter book title"); } else if (sbkauthor.gettext().length() == 0) { text.settext("enter book author"); } else if (sbkcond.gettext().length() == 0) { text.settext("enter book condition"); } else if (sbkphone.gettext().length() == 0) { text.settext("enter phone number"); } else if (sbkcollege.gettext().length() == 0) { text.settext("enter college name"); } else if (sbkprice.gettext().length() == 0) { text.settext("enter book price"); } else { //gets global uemaillogin comparison in db. allow db //be updated book info if did register. string uemaillogin = ((globals) getactivity().getapplication()).getemaillogin(); //start async task here http...because 4.0 can't process data on main ui new postbookinfo().execute(sbktitle.gettext().tostring(), sbkauthor.gettext().tostring(), sbkisbn.gettext().tostring(), sbkcond.gettext().tostring(), sbkphone.gettext().tostring(), sbkcollege.gettext().tostring(), sbkprice.gettext().tostring(), uemaillogin); //clears input data off phone screen after login button hit sbktitle.settext(""); sbkauthor.settext(""); sbkisbn.settext(""); sbkcond.settext(""); sbkphone.settext(""); sbkcollege.settext(""); sbkprice.settext(""); //finish(); } } }); return view; } //background asynctask load bookbuyinfo making http request class postbookinfo extends asynctask<string, string, string> { //show progress dialog before starting background thread //@override //protected void onpreexecute() { // super.onpreexecute(); // pdialog = new progressdialog(getactivity());//might can activity // pdialog.setmessage("selling..."); // pdialog.setindeterminate(false); // pdialog.setcancelable(false); // pdialog.show(); //} //get bookbuyinfo data protected string doinbackground(string... arg0) { jsonobject json_data = null; string result = null; inputstream = null; stringbuilder sb = null; //inputstream = null; //opens internet connection , prepares files used in processing httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("http://10.0.2.2/bkbarter.php"); try{ //loads array values sent php code db processing arraylist <namevaluepair> nvps = new arraylist <namevaluepair>(); nvps.add(new basicnamevaluepair("useraction", "postr")); ...load data... system.out.println("nvps = " + nvps); httppost.setentity(new urlencodedformentity(nvps)); httpresponse response = httpclient.execute(httppost); httpentity entity = response.getentity(); = entity.getcontent(); //shows logcat status response determine if data sent correctly log.i("onclicklistner", response.getstatusline().tostring()); } catch(exception e){ log.e("log_tag", "error in http connection "+e.tostring()); } //converts variables retrieved string try { bufferedreader reader = new bufferedreader(new inputstreamreader(is,"iso-8859-1"),8); sb = new stringbuilder(); sb.append(reader.readline() + "\n"); string line = "0"; while((line = reader.readline()) != null) { sb.append(line + "\n"); system.out.println(sb); } is.close(); result = sb.tostring(); } catch(exception e) { log.e("log_tag", "error converting result "+e.tostring()); } return(result); } //after completing background task, dismiss progress dialog @override protected void onpostexecute(final string result) { // might need (string result) here getactivity().runonuithread(new runnable() { public void run() { jsonobject json_data = null; string success_resp_code = null; string error_resp_code = null; string useraction = null; //parses string json object try { json_data = new jsonobject(result); success_resp_code = json_data.getstring("success"); error_resp_code = json_data.getstring("error"); useraction = json_data.getstring("useraction"); } catch (jsonexception e) { log.e("register/json parser", "error parsing data " + e.tostring()); } //checks register status success or failure try { if (json_data.getstring("success") != null && integer.parseint(success_resp_code) == 1){ //successful save of book information toast.maketext(getactivity().getapplicationcontext(), "book info has been saved", toast.length_short).show(); }else if(json_data.getstring("error") != null && integer.parseint(error_resp_code) == 1) { //unsuccessful saving book information toast.maketext(getactivity().getapplicationcontext(), "error saving book info", toast.length_short).show(); } } catch(exception e) { log.e("log_tag", "error converting result "+e.tostring()); } } }); } } }
actionbar sherlock loads tab left , right of current 1 in order allow fast change of tabs. had problem in project: try leave out code in oncreate not want executed.
Comments
Post a Comment