2010-07-01 162 views
0

我设法创建了函数的逻辑,但我不知道如何将它与数据库匹配。我只知道如何做硬编码的方式。RE:登录页面。如何匹配数据库中的用户名和密码以允许用户登录?

以下是我如何做到的。任何人都可以帮助我的'客人'部分,我相信一个SQL语句应该插入那里我是吗?我知道我错过了一些东西。在匹配用户名和密码之前,我应该首先检查用户是否存在于数据库中,然后检查密码是否与用户名匹配。

所以总而言之,我需要'if else'语句的帮助。

package one.two; 

import android.app.Activity; 
import android.content.Intent; 
import android.database.Cursor; 

import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.GridView; 
import android.widget.ListView; 
import android.widget.TextView; 



public class Login extends Activity implements OnClickListener{ 

/** Called when the activity is first created. */ 

    private EditText etUsername; 
    private EditText etPassword; 
    private Button btnLogin; 
    //private Button btnRegister; 
    private TextView lblResult; 

    @Override 

    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 

     setContentView(R.layout.main); 
    // Get the EditText and Button References 
     etUsername = (EditText)findViewById(R.id.usernametxt); 
     etPassword = (EditText)findViewById(R.id.passwordtxt); 
     btnLogin = (Button)findViewById(R.id.btnLogin); 
     //btnRegister = (Button)findViewById(R.id.btnRegister); 
     lblResult = (TextView)findViewById(R.id.msglbl); 


     Button btnArrival = (Button) findViewById(R.id.btnRegister); 
     btnArrival.setOnClickListener(this); 


    // Set Click Listener 
    btnLogin.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     // Check Login 
     String username = etUsername.getText().toString(); 
     String password = etPassword.getText().toString(); 

     if(username.equals("guest") && password.equals("guest")){ 
      lblResult.setText("Login successful."); 
     } else { 
      lblResult.setText("Login failed. Username and/or password doesn't match."); 
     } 
    } 
}); 



    } 

    public void onClick(View v) 
    { 
      Intent intent = new Intent(this, DatabaseActivity.class); 
      startActivity(intent); 
} 

} 

回答

1

之前,我相匹配的用户名和密码,我应该检查用户是否存在于数据库中,然后再检查是否与用户名的密码相匹配。

否除非在您的要求中您不需要创建两个SQL。你最好做类似的事情。 select count(*) from tableName where userNameField = username and passwordField = password并检查的行数是>比0登录是好的,否则用户名或密码无效

+0

如此这般: “如果(SELECT COUNT(*)FROM表名,其中userNameField =用户名和passwordField =密码){ lblResult.setText( “登录成功”);} 其他{ lblResult.setText( “登录失败的用户名和/或密码不匹配。”);} ” ? – Dayne 2010-07-01 07:35:43

+0

你需要哟执行此选择语句到数据库并检查返回的输出。检查你的数据库连接API。它可能位于http://developer.android.com/reference/java/sql/Connection.html。 – 2010-07-01 08:07:59

相关问题