1

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

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

我对如何实现这一点有点困惑?

我正在尝试创建一个扩展的单独类AsyncTask

这是我的主要活动

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 来决定做什么。

我将不胜感激有关此主题的任何建议或帮助!非常感谢

4

1 回答 1

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 中的“OK”重构为一个常量(以便于阅读和维护),并将大多数基于 HTTP 的代码重构为某种基类或实用程序类,以便您可以重用它。

于 2013-02-21T02:13:50.407 回答