2011-11-26 27 views
1

這裏是我的Java代碼:Android的登錄驗證到遠程MySQL數據庫

btnLogin.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    ArrayList <NameValuePair> postParameters = new ArrayList <NameValuePair>(); 
    postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString())); 
    postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString())); 

    //String valid = "1"; 
    String response = null; 
    try { 
     response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters); 
     String res = response.toString(); 
     // res = res.trim(); 
     res = res.replaceAll("\\s+", ""); 
     //error.setText(res); 
     if (res.equals("1")) { 
     txtError.setText("Correct Username or Password"); 
     //Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class); 
     //startActivity(i); 
     } else { 
     txtError.setText("Sorry!! Incorrect Username or Password"); 
     } 
    } catch (Exception e) { 
     txtUsername.setText(e.toString()); 
    } 
    } 
}); 

我認爲有一個在我的res.equals一個錯誤,因爲它口口聲聲說「無效的用戶名或密碼」即使我已經輸入了正確的用戶名或密碼。但是,當我將res.equals更改爲res.contains時,即使輸入了正確的用戶名和密碼,它仍會說「正確的用戶名或密碼」。我真的需要你的幫助。全部掌握在android開發中。希望你能幫助我。而且,當我更改txtError.setText(res)只是爲了檢查它是否返回1和0時,它不會。

+0

郵PHP代碼的問題可能是有(順便說一下我使用相同的代碼,並檢查http://www.sampleweb.com/imba.php響應我卡在相同的問題哈哈:) – BiggDawgg

+0

你試過'trim()'? 'txtUsername.getText()。toString()。trim()' – Sebastiano

+0

這是什麼?從來沒有聽說過trim() – BiggDawgg

回答

1

這需要在PHP文件做不是在Android代碼:

<?php 

define('DB_USER', "root"); //username used to connect to the database. 
define('DB_PASSWORD', ""); //password used to connect to the database. 
define('DB_DATABASE', "dbname"); //database name 
define('DB_SERVER', "127.0.0.1"); //database server address 

?> 

使用JSON解析器,你就那麼需要解析服務器上的數據。您需要使用類似下面的東西:

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    public JSONParser() { 

    } 

    //Method to connect to the database 
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { 

     //The following works just as in normal GET and POST methods 
     try { 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      }   

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

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 

在第二類中,那麼你就需要定義連接參數如下:

public class UserFunctions { 

    private JSONParser jsonParser; 

    private static String loginURL = "http://www.sampleweb.com/login.php"; 
    private static String registerURL = "http://www.sampleweb.com/register.php"; 

    private static String login_tag = "login"; 
    private static String register_tag = "register"; 

    // constructor 
    public UserFunctions(){ 
     jsonParser = new JSONParser(); 
    } 

    /** 
    * function make Login Request 
    * @param email 
    * @param password 
    * */ 
    public JSONObject loginUser(String email, String password){ 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", login_tag)); 
     params.add(new BasicNameValuePair("email", email)); 
     params.add(new BasicNameValuePair("password", password)); 
     JSONObject json = jsonParser.getJSONFromUrl(loginURL, params); 
     // return json 
     // Log.e("JSON", json.toString()); 
     return json; 
    } 

    /** 
    * function make Login Request 
    * @param name 
    * @param email 
    * @param password 
    * */ 
    public JSONObject registerUser(String name, String email, String password){ 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", register_tag)); 
     params.add(new BasicNameValuePair("name", name)); 
     params.add(new BasicNameValuePair("email", email)); 
     params.add(new BasicNameValuePair("password", password)); 

     // getting JSON Object 
     JSONObject json = jsonParser.getJSONFromUrl(registerURL, params); 
     // return json 
     return json; 
    } 

    /** 
    * Function get Login status 
    * */ 
    public boolean isUserLoggedIn(Context context){ 
     DatabaseHandler db = new DatabaseHandler(context); 
     int count = db.getRowCount(); 
     if(count > 0){ 
      // user logged in 
      return true; 
     } 
     return false; 
    } 

    /** 
    * Function to logout user 
    * Reset Database 
    * */ 
    public boolean logoutUser(Context context){ 
     DatabaseHandler db = new DatabaseHandler(context); 
     db.resetTables(); 
     return true; 
    } 

} 

除此之外,你將最終需要使用您的應用程序類來解析數據並將其顯示給用戶。有幾個在線教程可以做到這一點。

希望這有助於:)

+0

@ching你能否接受這個答案,並讚揚它,這有助於你? :) –

1

這實在是很難搞清楚什麼與怎麼回事了從服務器的響應。要調試的問題,爲有效和無效的用戶名/密碼組合使用像curlPostman一個POST庫