2011-04-12 103 views
0

我正在使用POST方法將HttpClient發送給腳本。該腳本工作正常,它只是檢查表中是否存在數據庫。如果該表存在「1」,則回顯回顯。來自腳本問題的Android響應

在下面的代碼一切正常

HttpClient client = new DefaultHttpClient(); 
        HttpPost post = new HttpPost("//remote//script.php"); 

        List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
        pairs.add(new BasicNameValuePair("tblname", concatenated)); 
        try 
        { 
         post.setEntity(new UrlEncodedFormEntity(pairs)); 
        } 
        catch (UnsupportedEncodingException e) 
        { 
         e.printStackTrace(); 
        } 
        try 
        { 
         HttpResponse response = client.execute(post); 
         entity = response.getEntity(); 
         res = EntityUtils.toString(entity); //this is now the echo back from the script, "1" means tbl already exists exists 

        } 
        catch (ClientProtocolException e) 
        { 
         e.printStackTrace(); 
        } 
        catch (IOException e) 
        { 
         e.printStackTrace(); 
        } 


        Toast msg1 = Toast.makeText(main.this, res, Toast.LENGTH_LONG); 
        msg1.setGravity(Gravity.CENTER, msg1.getXOffset()/2, msg1.getYOffset()/2); 
        msg1.show(); 
        SavePreferences("prefs", concatenated); 
        //fire the authed intent 
        startauthedactivity(); 
        } 

如果提供給腳本的表中存在1結束時顯示在祝酒,如果它不存在,那麼敬酒是空的,這是正確的行爲。

當我將一個-if-應用於響應時,即使該表存在,它也總是調用真實條件。在下面的代碼中,如果表存在,那麼res應該= 1,並且條件不成立,所以else塊應該啓動,但它永遠不會啓動。然而,古怪,如果我通過它存在的腳本表,則使用敬酒不實際顯示1 ...

if(res != "1") 
       { 

       Toast msg1 = Toast.makeText(main.this, res, Toast.LENGTH_LONG); 
       msg1.setGravity(Gravity.CENTER, msg1.getXOffset()/2, msg1.getYOffset()/2); 
       msg1.show(); 
       SavePreferences("prefs", concatenated); 
       //fire the authed intent 
       startauthedactivity(); 
       } 
       else 
       { 
        //do nothing 
       } 

回答

2

在Java中,你必須使用equals()方法比較字符串

if("1".equals(res)) {... 

請注意,您應該使用"1".equals(res)代替res.equals("1")

如果資源是null,第一個將工作,因爲equals處理空參數。 第二個將得到一個NullPointerException,因爲res爲空:)

+0

有史以來最快的答案2。只檢查:D – brux 2011-04-12 17:18:19

1

變化

if(res != "1") 

if(res.equals("1")) 

爲什麼?

==比較對象的引用(它在內存中的位置)。 equals比較字符串的內容。

+0

有史以來最快的答案2。只有檢查:D – brux 2011-04-12 17:17:35