java - Using Handler across unnested thread class -


i have code written, in seperate thread connection made , data retrieved. working fine.

my problem arises when try pass information main thread via handler.

because code thread off main thread not nested inside main class, reference pass handler not seem hold. suggestions how can modify code allow handler data passed main thread.

code main thread (stripped out leaving important bits):

public class myactivity extends activity {  handler mhandler = new handler(){     public void handlemessage(message msg){         bundle b;         if(msg.what==1){             b = msg.getdata();             wecanmove = b.getboolean("key");             log.d("what did get", string.valueof(b.getboolean("key")));         }         super.handlemessage(msg);     } };   public void start(view view) throws interruptedexception {     context context;     boolean wehavefile = checkfile();     system.out.println(userinfo[0] + "\n" + userinfo[1]);     if (wehavefile) {         intent intent = new intent(myactivity.this, otheractivity.class);         startactivity(intent);     } else {          //databasemiddleman login = new databasemiddleman();         /*login.run();         login.login(userinfo[0],userinfo[1]);*/         arraylist <string> uinfo = new arraylist<string>();         uinfo.add(0,userinfo[0]);         uinfo.add(1,userinfo[1]);         databasemiddleman login = new databasemiddleman(0,uinfo,this.mhandler);         thread thread = new thread(login);         thread.start();         thread.sleep();         if(wecanmove) {             intent intent = new intent(myactivity.this, otheractivity.class);             startactivity(intent);         }else{              context = this.getapplicationcontext();              new alertdialog.builder(myactivity.this)                     .settitle("errore")                     .setmessage("credenziali errate!")                     .setpositivebutton(android.r.string.yes, new dialoginterface.onclicklistener() {                         public void onclick(dialoginterface dialog, int which) {                          }                     })                     .setnegativebutton(android.r.string.no, new dialoginterface.onclicklistener() {                         public void onclick(dialoginterface dialog, int which) {                             // nothing                         }                     })                     .seticon(android.r.drawable.ic_dialog_alert)                     .show();         }     } } 

the code object runs in seperate thread:

public class databasemiddleman implements runnable{ public string serveraddress; public boolean loginsucess = false; private arraylist<string> params; private int whichmethodtoexecute; private handler hd;  public databasemiddleman(int selection, arraylist<string> params, handler msg){     this.params = params;     this.whichmethodtoexecute = selection;     hd = msg; }  public void run(){     if(this.whichmethodtoexecute ==  0){         this.login();     } }    public void login(){     string username = params.get(0);     string password = params.get(1);      string link = "xxxxxxxxxxxxxx";     string query = "xxxxxxxxxxxxxxx";     httpclient httpclient = new defaulthttpclient();      httppost httppost = new httppost(link);      basicnamevaluepair querypair = new basicnamevaluepair("query", query);     list<namevaluepair> namevaluepairlist = new arraylist<namevaluepair>();     namevaluepairlist.add(querypair);     bundle b = new bundle(1);      try {         urlencodedformentity urlencodedformentity = new urlencodedformentity(namevaluepairlist);          httppost.setentity(urlencodedformentity);         try {             httpresponse httpresponse = httpclient.execute(httppost);             inputstream inputstream = httpresponse.getentity().getcontent();             inputstreamreader inputstreamreader = new inputstreamreader(inputstream);             bufferedreader bufferedreader = new bufferedreader(inputstreamreader);             string bufferedstrchunk = null;             stringbuilder stringbuilder = new stringbuilder();              while ((bufferedstrchunk = bufferedreader.readline()) != null) {                 stringbuilder.append(bufferedstrchunk);             }              string queryresult = stringbuilder.tostring();             log.d("sql pass",queryresult);             if (queryresult.equals(password)){                 loginsucess = true;                  b.putboolean("key",true);                 log.d("sql pass","test passed");             } else {                  b.putboolean("key",false);             }          } catch (clientprotocolexception cpe) {             system.out.println("first exception caz of httpresponese :" + cpe);             cpe.printstacktrace();         } catch (ioexception ioe) {             system.out.println("second exception caz of httpresponse :" + ioe);             ioe.printstacktrace();         }     } catch (unsupportedencodingexception uee) {         system.out.println("an exception given because of urlencodedformentity argument :" + uee);         uee.printstacktrace();     }      message msgs = hd.obtainmessage();     msgs.setdata(b);     hd.sendmessage(msgs); } 

what message looper? object receives queue of messages, , sequentially runs message handlers in same thread, 1 another. next run after previous completed.

so, imagine, there start event put in queue. looper starts handler, run cascade of methods, , start(view view). looper halted until methods completed , handler done. so, next message in queue, run handlemessage of your's handler, executed after start returns.

never use thread.sleep() in main thread. better use

thread.join(); 

to wait until asyn thread complete.

if want pass 1 single object between threads after thread done, can use approach:

allocate in runnable volatile variable:

public class databasemiddleman implements runnable{      public volatile bundle mresult;     ... 

just after thread completed, can access variable:

    databasemiddleman login = new databasemiddleman(0,uinfo,this.mhandler);     thread thread = new thread(login);     thread.start();     ...     // blah blah blah, here doing actions in parallel, while thread doing it's work     ...     thread.join();      bundle b = login.mresult;             wecanmove = b.getboolean("key"); 

note, instead of bundle, can pass here boolean value itself. also, can create several result variables, if needed.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -