如何为sqlite创建一个简单的SignUp(Email,UserName,Password)。然后使用他们的UserName& SignIn / LogIn。密码?
我尝试了这段代码,但在插入时遇到错误。此代码在SignUp上编写
String user=username.getText().toString();
String pass=password.getText().toString();
String mail=email.getText().toString();
if ((user.matches(""))||(pass.matches(""))||(mail.matches(""))) {
Log.d("SignUp", "Vacant Field");
return;
}
else {
DatabaseAdapter dbadapter=new DatabaseAdapter(null);
dbadapter.insertdata(user, pass, mail);
Log.d("SignUp", "Data's stored in SQLite");
}
在 DatabaseAdapter 类中,我使用了此代码
public class DatabaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// SQL to Create a new Database
static final String DATABASE_CREATE= "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text, EMAIL text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public DatabaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DatabaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
// to store data`s in SQLite db
public void insertdata(String username, String password, String email)
{
ContentValues values=new ContentValues();
// Assign values for each row.
values.put("USERNAME", username);
values.put("PASSWORD", password);
values.put("EMAIL", email);
Log.d("DatabaseAdapter", "Data's are assin to insert");
// Insert the row into your table
db.insert("LOGIN", null, values);
Log.d("DatabaseAdapter", "Data's stored successfully");
db.close();
}
public String getSingleEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
}
按下SignUp按钮时出现错误
FATAL ERROR, Null pointer Exception Error
答案 0 :(得分:1)
DatabaseAdapter dbadapter=new DatabaseAdapter(null);
这就是你犯错的地方。您应该传递当前活动而不是null
。
正确的调用语法应如下所示,
DatabaseAdapter dbadapter=new DatabaseAdapter(this);
答案 1 :(得分:1)
signup.java(活动)
package...name;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class signup extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//to link to the second activity
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
}
});
}
public void onSignUpClick(View v){
if(v.getId() == R.id.btn_Register)
{
EditText name = (EditText)findViewById(R.id.TFname);
EditText email = (EditText)findViewById(R.id.TFemail);
EditText pass1 = (EditText)findViewById(R.id.TFpass1);
EditText pass2 = (EditText)findViewById(R.id.TFpass2);
String namestr = name.getText().toString();
String emailstr = name.getText().toString();
String pass1str = name.getText().toString();
String pass2str = name.getText().toString();
if(!pass1str.equals(pass2str))
{
//popup msg:
Toast tpass = Toast.makeText(signup.this, "passwords don't match", Toast.LENGTH_LONG);
tpass.show();
}
else
{
//insert the details in DB:
Contact c = new Contact();
c.setName(namestr);
c.setEmail(emailstr);
c.setPass(pass1str);
helper.insertContact(c);
}
}
}
}
DatabaseHelper.java(Class)
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE="create table contacts (id integer primary key not null ," +
"name text not null, email text not null, uname text not null, pass text not null);";
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertContact(Contact c)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//create a string query
String query = "select * from contacts ";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_EMAIL, c.getEmail());
values.put(COLUMN_PASS, c.getPass());
//this will insert the content in the database
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String name){
db = this.getReadableDatabase();
String query = "select name, pass from" +TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a, b;
b="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
if(a.equals(name)){
b=cursor.getString(1);
break;
}
}
while (cursor.moveToNext());
}
return b;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS"+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
Contact.java(class)
public class Contact {
String name, email, uname, pass;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return this.email;
}
public void setUname(String uname)
{
this.uname = uname;
}
public String getUname()
{
return this.uname;
}
public void setPass(String pass)
{
this.pass = pass;
}
public String getPass()
{
return this.pass;
}
}
Login.java(活动)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends Activity {
DatabaseHelper helper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
TextView registerScreen = (TextView) findViewById(R.id.link_to_signup);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), signup.class);
startActivity(i);
}
});
}
public void onSigninClick(View v){
if(v.getId() == R.id.btnLogin)
{
EditText a = (EditText)findViewById(R.id.TFname);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpassword);
String pass = a.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password))
{
Intent i = new Intent(Login.this, signup.class);
i.putExtra("name" , str);
startActivity(i);
}
else{//popup msg:
Toast temp = Toast.makeText(Login.this, "username & passwords don't match", Toast.LENGTH_LONG);
temp.show();}
}
}
}
Display.java(活动)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Display extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
String name = getIntent().getStringExtra("name");
TextView tv = (TextView)findViewById(R.id.TFname);
tv.setText(name);
}
}
答案 2 :(得分:1)
主要活动
Button login_button;
EditText email_edit, password_edit;
TextView goToRegister;
DatabaseHelper userDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
email_edit = (EditText) findViewById(R.id.edit_email_login);
password_edit = (EditText) findViewById(R.id.edit_password_login);
userDatabase = new DatabaseHelper(this);
//Go to Register Activity
goToRegister = (TextView) findViewById(R.id.go_to_register);
goToRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent goToRegister = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(goToRegister);
}
});
login_button = (Button) findViewById(R.id.button_register);
login_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (validate()) {
//Get values from EditText fields
String email = email_edit.getText().toString();
String password = password_edit.getText().toString();
//Authenticate User
User currentUser = userDatabase.Authenticate(new User(null, null, email, password));
//Check Authentication is successful or not
if (currentUser != null) {
Intent goToDash = new Intent(MainActivity.this, DashboardActivity.class);
goToDash.putExtra("Email", currentUser.email);
goToDash.putExtra("Name", currentUser.name);
startActivity(goToDash);
Toast.makeText(MainActivity.this, " Login Successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, " Failed to Logged in!", Toast.LENGTH_LONG).show();
}
}
}
});
}
private boolean validate() {
boolean valid = false;
//Get values from EditText fields
String email = email_edit.getText().toString();
String pass = password_edit.getText().toString();
//Handling validation
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
valid = false;
email_edit.setError("Please enter valid Email");
} else {
valid = true;
email_edit.setError(null);
}
//Handling Password
if (pass.isEmpty()) {
valid = false;
password_edit.setError("Please enter Valid Password");
}
return valid;
}
}
注册活动
Button register_butoon;
TextView goToLogin;
EditText edit_email, edit_password, edit_confirm_pass, edit_full_name;
DatabaseHelper userDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
userDatabase = new DatabaseHelper(this);
edit_full_name = (EditText) findViewById(R.id.edit_full_name);
edit_email = (EditText) findViewById(R.id.edit_email_register);
edit_password = (EditText) findViewById(R.id.edit_password_register);
edit_confirm_pass = (EditText) findViewById(R.id.edit_confirm_pass);
register_butoon = (Button) findViewById(R.id.button_register);
goToLogin = (TextView) findViewById(R.id.register_text_view);
goToLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent goToLogin = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(goToLogin);
}
});
register_butoon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (validate()) {
//Get Input From edit text
String userName = edit_full_name.getText().toString();
String userEmail = edit_email.getText().toString();
String userPass = edit_password.getText().toString();
String userConfirmationPass = edit_confirm_pass.getText().toString();
if (userConfirmationPass.equals(userPass) && !userDatabase.isEmailExists(userEmail)) {
//Insert data in Database from EditText field
userDatabase.addUser(new User(null, userName, userEmail, userPass));
Toast.makeText(RegisterActivity.this, "User created successfully! Please Login ", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, Toast.LENGTH_LONG);
} else if (!userConfirmationPass.equals(userPass)) {
Toast.makeText(RegisterActivity.this, "Password is not Matched ", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(RegisterActivity.this, "User already exists , Check your email ", Toast.LENGTH_LONG).show();
}
}
}
});
}
//This method is used to validate input given by user
public boolean validate() {
boolean valid = false;
//Get values from EditText fields
String UserName = edit_full_name.getText().toString();
String Email = edit_email.getText().toString();
String Password = edit_password.getText().toString();
//Handling validation for UserName field
if (UserName.isEmpty()) {
valid = false;
edit_full_name.setError("Please enter valid username!");
} else {
if (UserName.length() > 5) {
valid = true;
edit_full_name.setError(null);
} else {
valid = false;
edit_full_name.setError("Username is to short!");
}
}
//Handling validation for Email field
if (!Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
edit_email.setError("Please enter valid email!");
} else {
valid = true;
edit_email.setError(null);
}
//Handling validation for Password field
if (Password.isEmpty()) {
valid = false;
edit_password.setError("Please enter valid password!");
} else {
if (Password.length() > 2) {
valid = true;
edit_password.setError(null);
} else {
valid = false;
edit_password.setError("Password is to short!");
}
}
return valid;
}
}
个人资料活动或仪表板活动
TextView email_display, user_name;
Button logOut;
DatabaseHelper userDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
userDatabase = new DatabaseHelper(this);
logOut = (Button) findViewById(R.id.logout);
logOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Finish current Activity
finish();
Toast.makeText(DashboardActivity.this, "LogOut Successful", Toast.LENGTH_SHORT).show();
}
});
email_display = (TextView) findViewById(R.id.display_email);
user_name = (TextView) findViewById(R.id.user_name);
Intent i = this.getIntent();
String email = i.getStringExtra("Email");
String name = i.getStringExtra("Name");
user_name.setText(name);
email_display.setText(email);
}
}
DatabaseHelper类
//Table Name
public static final String TABLE_NAME = "user";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User Table Columns names
public static final String COLUMN_USER_ID = "user_id";
public static final String COLUMN_USER_NAME = "user_name";
public static final String COLUMN_USER_EMAIL = "user_email";
public static final String COLUMN_USER_PASSWORD = "user_password";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT,"
+ COLUMN_USER_PASSWORD + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
/**
* Constructor
*
* @param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
//Add user in Database
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.name);
values.put(COLUMN_USER_EMAIL, user.email);
values.put(COLUMN_USER_PASSWORD, user.password);
//Inserting row
db.insert(TABLE_NAME, null, values);
//Close the database
db.close();
}
public User Authenticate(User user) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID,
COLUMN_USER_NAME,
COLUMN_USER_EMAIL,
COLUMN_USER_PASSWORD
};
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
do {
User user1 = new User(cursor.getString(cursor.getColumnIndex(this.COLUMN_USER_ID)),
cursor.getString(cursor.getColumnIndex(this.COLUMN_USER_NAME)),
cursor.getString(cursor.getColumnIndex(this.COLUMN_USER_EMAIL)),
cursor.getString(cursor.getColumnIndex(this.COLUMN_USER_PASSWORD)));
if (user.password.equalsIgnoreCase(user1.password) && user.email.equals(user1.email)) {
return user1;
}
} while (cursor.moveToNext());
}
cursor.close();
return null;
}
public boolean isEmailExists(String email) {
SQLiteDatabase db = this.getReadableDatabase();
// array of columns to fetch
String[] columns = {COLUMN_USER_EMAIL};
//Selection
String selection = COLUMN_USER_EMAIL + " = ? ";
//Selection Args
String[] selection_Args = {email};
//Query
Cursor cursor = db.query(TABLE_NAME,
columns,
selection,
selection_Args,
null,
null,
null
);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
return true;
}
return false;
}
}
用户类别
public class User {
//Variable
public String id;
public String name;
public String email;
public String password;
//Constructor with two parameters
public User(String email, String password) {
this.email = email;
this.password = password;
}
//Parameter Constructor containing all three parameter
public User(String id, String name, String email, String password) {
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
}