2013-05-26 115 views
0

Android设计不允许网络在主线程上强制它,但它不是一个好的做法。所以我想同步主线程和另一个线程,以便我可以从数据库获取用户身份验证的响应。我同步不工作..Android与其他线程的主线程之间同步

这是在主线程的代码..

if (loginBTN.getId() == ((Button) v).getId()) { 

    String emailId = loginField.getText().toString().trim(); 
    String password = passwordField.getText().toString().trim(); 

    postParameters.add(new BasicNameValuePair("username", emailId)); 
    postParameters.add(new BasicNameValuePair("password", password)); 

    try { 

     System.out.println("b4 response" + responseToString); 

     checkLogin(); 

     System.out.println("after response" + responseToString); 

     synchronized (this) { 

      while (isAvailable == false) { 

       wait(); 

      } 

      if (responseToString.equalsIgnoreCase("1")) { 

       statusLBL.setText("Login Successful..."); 

      } 

      else { 

       statusLBL.setText("Sorry Incorrect Username or Password..."); 

      } 
     } 

    } 

    catch (Exception e) { 

     statusLBL.setText(e.toString()); 
    } 

} 




private void checkLogin() { 

     Thread thread = new Thread(new Runnable() { 

      @Override 
      public void run() { 

       try { 

        HttpClient http = new DefaultHttpClient(); 
        HttpPost request = new HttpPost("http://example.org/api/android_gradhub/login_user.php"); 
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); 
        request.setEntity(formEntity); 
        HttpResponse response = http.execute(request); 
        HttpEntity entity = response.getEntity(); 

        // responseToString = EntityUtils.toString(entity); 

        synchronized (this) { 

         while (isAvailable == true) { 

          wait(); 

         } 

         responseToString = EntityUtils.toString(entity); 
         notifyAll(); 
        } 

        System.out.println("response " + responseToString); 
       } 

       catch (Exception e) { 

        e.printStackTrace(); 
       } 
      } 
     }); 

     thread.start(); 

    } 
+1

什么问题? –

+1

你的问题是什么? – Daniel

+0

同步不起作用.. – user2421377

回答

0

删除所有synhronization,然后只是把thread.join()作为最后陈述中checkLogin这是在继续之前等待线程完成的最简单方法。

如果要决定何时等待(就像你可能想要做其他的东西在主程序需要检查在登录之前),那么你可以从返回checkLogin线程。比你决定何时join回到你的主程序。 (即签名更改为public Thread checkLogin,checkLogin的最后一行变为return thread。回到主程序中,当您想等待checkLogin完成时,请拨Thread thread = checkLogin(); - 使用thread.join(),直到主线程和checkLogin线程同时为止。

+0

这工作,但可以帮助我解决我的同步问题我正在学习多线程,所以这将是一个很好的帮助.. – user2421377

+0

为什么你需要在你的例子同步。什么是有争议的资源? **共享资源**问题的更现实的例子会有所帮助。 – xagyg

+0

responseToString是有争议的资源 – user2421377