在android中解析httpresponse后的字符串比较

时间:2012-08-10 13:36:43

标签: android string httpresponse

我无法理解为什么字符串比较不起作用

protected String doInBackground(String... args) 
{
   DefaultHttpClient httpClient =   new DefaultHttpClient();
   HttpPost httpPost            =   new HttpPost(url_login);
   httpPost.setEntity(new UrlEncodedFormEntity(params));
   HttpResponse httpResponse    =   httpClient.execute(httpPost);
   HttpEntity entity            =   httpResponse.getEntity();
   InputStream is               =   entity.getContent();
   String returnState           =   new String();
   returnState                  =   convertStreamToString(is);


   Log.d("retunState ", returnState); // returning desired string

   //if (returnState=="user") // this is not working, however returnState = user
   // OR 
   //if (returnState.equals("user")) 
   // OR
   if (returnState.equalsIgnoreCase("user")) // this is not working also
   {                        
      Intent i = new Intent(Main.this, SecondPage.class);
      startActivity(i);
      finish();
   }

} // close of doInbackgorund function

private static String convertStreamToString(InputStream is) 
{

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb      = new StringBuilder();

String line = null;
try {
        while ((line = reader.readLine()) != null) {
            sb.append((line + "\n"));
            }
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
           is.close();
        } catch (IOException e) {
          e.printStackTrace();
     }
   }
 return sb.toString();
}

即使returnState = user或returnState = no_user,所有三个if条件都没有给出任何错误,第二个活动永远不会启动。如果returnState = user,我想启动另一个活动,但无论如何,如果阻止

,它就不会进入

1 个答案:

答案 0 :(得分:5)

您的第一个if语句正在跳过您的下一个语句,因为它是错误的。注释掉第一个if。

你可能在returnState中也有空格。尝试使用.trim()

//if (returnState=="user") 
if (returnState.trim().equalsIgnoreCase("user")) 
{                        
   Intent i = new Intent(Main.this, SecondPage.class);
   startActivity(i);
   finish();
}