2013-02-21 98 views
1

我正在尝试为我的应用程序创建一个登录系统。目前,用户可以在线创建帐户并下载应用程序。然后提示他们输入用户名和密码。在登录时检查用户详细信息Android

当他们按下登录按钮时,我想向服务器上的php脚本发出请求以检查结果,如果用户确实存在,则返回true;如果用户不存在,则返回false。

我有点困惑我应该如何实现这个?

我想创建一个单独的类,扩展AsyncTask

这是我的MainActivity

EditText username; 
EditText password; 
Button loginBtn; 
LinearLayout loginform; 
String passwordDetail; 
String usernameDetail; 
String url = "http://www.jdiadt.com/example/checklogindetails.php"; 

HttpTask httptask; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //Hide the Action Bar 
    ActionBar ab; 
    ab = this.getActionBar(); 
    ab.hide(); 

    //Get references to XML 
    username = (EditText)findViewById(R.id.username); 
    password = (EditText)findViewById(R.id.password); 
    loginBtn = (Button)findViewById(R.id.loginBtn); 
    loginform = (LinearLayout)findViewById(R.id.loginform); 

    //Animation 
    final AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f); 
    AlphaAnimation fadeOut = new AlphaAnimation(1.0f , 0.0f) ; 
    fadeIn.setDuration(1200); 
    fadeIn.setFillAfter(true); 
    fadeOut.setDuration(1200); 
    fadeOut.setFillAfter(true); 
    fadeOut.setStartOffset(4200+fadeIn.getStartOffset()); 

    //Run thread after 2 seconds to start Animation 
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable(){ 

     public void run() { 
      //display login form 
      loginform.startAnimation(fadeIn); 
      loginBtn.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
        //display(); 
        Toast.makeText(getApplicationContext(), "Checking login details...", Toast.LENGTH_SHORT).show(); 
        if(checkLoginDetails()){ 
         //OPENS NEW ACTIVITY 
         //Close splash screen 
         finish(); 
         //start home screen 
         Intent intent = new Intent(v.getContext(), SectionsActivity.class); 
         startActivity(intent); 
         //creates fade in animation between two activities 
         overridePendingTransition(R.anim.fade_in, R.anim.splash_fade_out); 
        } 
        else{ 
        } 
       } 
      }); 

     } 

    }, 2000); 


} 

//Check the login details before proceeding. 
public boolean checkLoginDetails(){ 
    usernameDetail = username.getText().toString(); 
    passwordDetail = password.getText().toString(); 
    httptask = new HttpTask(); 
    httptask.execute(url, usernameDetail, passwordDetail); 
    //if exists return true 
    //else return false 
    return false; 
} 

}

这是我HttpTask

public class HttpTask extends AsyncTask<String, Void, Boolean> { 

@Override 
protected Boolean doInBackground(String... params) { 

    String url = params[0]; 
    String username = params[1]; 
    String password = params[2]; 

    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(url); 

    List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("username", username)); 
    nameValuePairs.add(new BasicNameValuePair("password", password)); 

    try { 
     httpClient.execute(httpPost); 
     return true; 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

}

这是我的PHP脚本在我的网络服务器checklogindetails.php

require_once 'db_connect.php'; 

    $username = mysql_real_escape_string($_POST['username']); 
    $password = mysql_real_escape_string($_POST['password']); 

    $pwdMD5 = md5($password); 

    $sql = "SELECT * FROM users WHERE username = '$username' AND password='$pwdMD5'"; 
    $result = mysql_query($sql); 

    $count = mysql_num_rows($result); 

    if($count == 1){ 
     echo "Log in successful"; 
//RETURN TRUE 
    } 
    else{ 
     echo "Wrong username or password"; 
//RETURN FALSE 
    } 

我想我最困惑的地方是如何构建php脚本来检查登录细节以及如何根据它返回true或false来决定做什么。

我会很感激任何意见或在这个问题上的帮助!非常感谢

回答

1

上面的代码看起来不错,只是你错过了最后一步。 从PHP返回一些内容,然后在应用程序中读取它。

我建议PHP的输出改变的东西更容易解析/维持像“OK”和“ERROR”

然后将下面的代码添加到HttpTask。

final HttpResponse response = httpClient.execute(httpPost, localContext); 
if (response != null) 
{ 
    // parse response 
    final HttpEntity entity = response.getEntity(); 
    if (entity == null) 
    { 
     // response is empty, this seems an error in your use case 
     if (BuildConfig.DEBUG) 
     { 
      Log.d(HttpClient.TAG, "Response has no body"); //$NON-NLS-1$ 
     } 
    } 
    else 
    { 
     try 
     { 
      // convert response to string 
      this.mResponseAsString = EntityUtils.toString(entity); 
      if (BuildConfig.DEBUG) 
      { 
       Log.d(HttpClient.TAG, "Response: " + this.mResponseAsString); //$NON-NLS-1$ 
      } 

      // parse the string (assuming OK and ERROR as possible responses) 
      if (this.mResponseAsString != null && this.mResponseAsString.equals("OK") 
      { 
       // add happy path code here 
      } 
      else 
      { 
       // add sad path here 
      } 
     } 
     catch (final ParseException e) 
     { 
      Log.e(HttpClient.TAG, e.getMessage(), e); 
     } 
     catch (final IOException e) 
     { 
      Log.e(HttpClient.TAG, e.getMessage(), e); 
     } 
    } 
    this.mResponseCode = response.getStatusLine().getStatusCode(); 
} 

个人而言,我也重构了“确定”,在HttpTask为恒定(为方便阅读和维护),并重构大部分基于HTTP的代码,以某种基类或实用类的,所以你可以重用它。

相关问题