我正在在Android Studio中创建一个连接到SQLite的登录名。如果用户名和密码正确(我俩都存储在数据库中),我想继续第二次活动。可以从我的管理页面添加用户,一切正常。如何检查用户名和密码是否存储在数据库中?
到目前为止,这是我的代码:
主要活动:
package com.example.schoolapp;
import android.content.Intent;
import android.se.omapi.Session;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.schoolapp.Admin.DBHelper;
import com.example.schoolapp.Admin.ThirdActivity;
import com.example.schoolapp.Eleve.SecondActivity;
public class MainActivity extends AppCompatActivity {
DBHelper SchoolAppDB;
//Initialisation des variables
private EditText Name;
private EditText Password;
private Button Login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Mise en relation des variables a leurs correspondants dans le fichier XML par leur ID
Name = (EditText) findViewById(R.id.etNewName);
Password = (EditText) findViewById(R.id.etPassword);
Login = (Button) findViewById(R.id.btnLogin);
Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//getting Edit Text values and stores it into string
String username = Name.getText().toString();
String password = Password.getText().toString();
//check authorized user or not
if (SchoolAppDB.checkUser(username, password)) {
Intent intent =new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Login Successfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong Username or Password", Toast.LENGTH_LONG).show();
}
}
});
}
}
DBHelper的checkUserLogin方法:
public boolean checkUserLogin(String username,String password){
SQLiteDatabase db=this.getWritableDatabase();
String Query = "select USER_NAME, USER_PASSWORD from USER where USER_NAME='"+ username +"' and USER_PASSWORD='"+ password+"'";
Cursor cursor = null;
try {
cursor = db.rawQuery(Query, null);//raw query always holds rawQuery(String Query,select args)
} catch (Exception e) {
e.printStackTrace();
}
if(cursor!=null && cursor.getCount()>0){
cursor.close();
return true;
}
else{
cursor.close();
return false;
}
}