Sur*_*jRk 0 sqlite android login cursor
我正在尝试为Android中的应用创建登录屏幕.我已将有关用户的信息存储在数据库的"用户"表中.我正在尝试使用光标对象将登录屏幕中输入的用户名和密码与数据库中的值进行匹配,但它不起作用,导致应用程序崩溃.有人可以推荐或修改方法,如果可能的话,可以使用一些代码片段.非常感谢大家,谢谢.
下面是LoginForm类的代码.(它使用DBAdapter类连接到数据库)
package com.androidbook.LoginForm;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;
public class LoginForm extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DBAdapter db = new DBAdapter(getBaseContext());
final AutoCompleteTextView username = (AutoCompleteTextView)this.findViewById(R.id.AutoComUsernameLogin);
final AutoCompleteTextView password = (AutoCompleteTextView)this.findViewById(R.id.AutoComPasswordLogin);
Button Register = (Button) findViewById(R.id.ClicktoRegister);
Register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), RegistrationForm.class);
startActivityForResult(myIntent, 0);
}
});
//************************** LOG IN LOGIC******************************//
Button Login = (Button) findViewById(R.id.LoginButton);
Login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String Username = username.getText().toString();
final String Password= password.getText().toString();
db.open();
Cursor c = db.getAllTitles();
while(c.moveToNext())
{
String c1=c.getString(2);
String c2=c.getString(3);
if(c1 == Username)
{
if(c2 == Password)
{
Toast.makeText(LoginForm.this,
"You are succesfully logged in.",
Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(view.getContext(), Menu.class);
startActivityForResult(myIntent, 0);
}
else
{
Toast.makeText(LoginForm.this, "Incorrect password",Toast.LENGTH_LONG).show();
}
Intent myIntent = new Intent(view.getContext(), LoginForm.class);
startActivityForResult(myIntent, 0);
}
else
Toast.makeText(LoginForm.this, "Incorrect",Toast.LENGTH_LONG).show();
}
db.close();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
Chirag Raval的回答是函数,但很容易受到SQL注入的攻击.恶意用户可以使用基本SQLi有效负载轻松绕过身份验证机制(只要数据库中至少有一个条目被检查).
具有有界值的参数化查询是更安全的方法.
修复代码段:
public int Login(String username,String password)
{
String[] selectionArgs = new String[]{username, password};
try
{
int i = 0;
Cursor c = null;
c = db.rawQuery("select * from login_table where username=? and password=?", selectionArgs);
c.moveToFirst();
i = c.getCount();
c.close();
return i;
}
catch(Exception e)
{
e.printStackTrace();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这种简单的改进更安全,更容易编码.
| 归档时间: |
|
| 查看次数: |
14351 次 |
| 最近记录: |