一、结果测试
此时第一次运行,数据库进行创建,数据为空
我们去注册账号
输入用户名
输入密码
注册成功,自动返回登录页
查看数据库
再次返回注册页,注册名字为zzw,提示用户名已存在
我们返回登录页去登陆
登陆成功
二、问题总结
1、在Activity调用onCreate方法时,应该调用public void onCreate(@Nullable Bundle savedInstanceState)方法,而不是public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState)方法。
2、在数据库为空时,进行增删改查,如果调用数据库事务就会报错。
3、当使用startActivityForResult(intent,mRegisterCode);进行跳转时,在第二个界面的跳转回第一个页面的时候,必须要加上finish(),因为这个方法的定义是,当在第二个界面的操作完成后,自动跳回第一个界面,而finish()就起着判断在第二个Activity的操作是否完成的重要作用,只要不finish,那就不会跳转回来。
三、原码
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.familybook"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="家庭记账本" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".IndexActivity"/> <activity android:name=".RegisterActivity"/> </application> </manifest>
LoginActivity.java
package com.example.familybook; import android.content.Intent; import android.os.Bundle; import android.os.PersistableBundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.example.familybook.dao.IUserDao; import com.example.familybook.dao.UserDaoImpl; import com.example.familybook.database.UserDatabaseHelper; public class LoginActivity extends AppCompatActivity { private EditText mUsername; private EditText mPassword; private Button mLogin; private Button mGotoregister; private static final int mRegisterCode=1; private IUserDao mIUserDao; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //创建数据库 UserDatabaseHelper helper =new UserDatabaseHelper(LoginActivity.this); helper.getWritableDatabase(); //初始化控件 initView(); //设置事件监听 initListener(); } private void initListener() { mLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login(); } }); mGotoregister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { register(); } }); } private void register() { Intent intent =new Intent(this, RegisterActivity.class); startActivityForResult(intent,mRegisterCode); } private void login() { //账号 String usernameText =mUsername.getText().toString(); //密码 String passwordText =mPassword.getText().toString(); //对账号和密码进行检测 if(TextUtils.isEmpty(usernameText)){ //账号为空 Toast.makeText(this,"用户名不可以为空",Toast.LENGTH_SHORT).show(); return; }else if(TextUtils.isEmpty(passwordText)){ //密码为空 Toast.makeText(this,"密码不可以为空",Toast.LENGTH_SHORT).show(); }else { boolean result = mIUserDao.Login(usernameText, passwordText); if (result) { Intent intent = new Intent(this, IndexActivity.class); startActivity(intent); } else { //登录失败 Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show(); } } } private void initView() { mUsername=(EditText)this.findViewById(R.id.username); mPassword=(EditText)this.findViewById(R.id.password); mLogin=(Button) this.findViewById(R.id.login_btn); mGotoregister=(Button)this.findViewById(R.id.goto_register_btn); mIUserDao=new UserDaoImpl(this); } /** * 返回的结果在这里回调 * @param requestCode * @param resultCode * @param data */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String resultContent = null; //当我们判断这个请求码的时候,就知道,这是注册界面返回的结果 if (requestCode==mRegisterCode) { if(resultCode==2){ //注册成功 Toast.makeText(this,"注册成功",Toast.LENGTH_SHORT).show(); } } } }
RegisterActivity.java
package com.example.familybook; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import androidx.annotation.Nullable; import com.example.familybook.dao.IUserDao; import com.example.familybook.dao.UserDaoImpl; import com.example.familybook.entity.User; public class RegisterActivity extends Activity{ private RadioGroup mSex; private EditText mUsername; private EditText mPassword; private Button mRegisterBtn; private RadioButton mR; private IUserDao mIUserDao; private String TAG="RegisterActivity"; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); //初始化控件 initView(); //设置监听,处理点击事件 initListener(); } private void initListener() { mSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { mR =(RadioButton) findViewById(checkedId); } }); mRegisterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //点击了注册按钮 Registerhandler(); } }); } private void Registerhandler() { User user =null; //账号 String usernameText =mUsername.getText().toString().trim(); //密码 String passwordText =mPassword.getText().toString().trim(); //性别 String sexText; if(mR.getText().toString()!=null) { sexText = mR.getText().toString(); }else{ sexText="男"; } Log.e(TAG,"账户:"+usernameText); Log.e(TAG,"密码:"+passwordText); Log.e(TAG,"性别:"+sexText); //对账号和密码进行检测 if(TextUtils.isEmpty(usernameText)){ //账号为空 Toast.makeText(this,"用户名不可以为空",Toast.LENGTH_SHORT).show(); return; }else if(TextUtils.isEmpty(passwordText)){ //密码为空 Toast.makeText(this,"密码不可以为空",Toast.LENGTH_SHORT).show(); }else { boolean result = mIUserDao.isExist(usernameText); if (result) { //用户名已被使用 Toast.makeText(this, "此用户名已被注册", Toast.LENGTH_SHORT).show(); } else { user = new User(usernameText, passwordText, sexText); int rs = (int) mIUserDao.Register(user); Log.e(TAG,"rs:"+rs); if (rs > -1) { //注册成功,跳回登录页面 Intent intent = new Intent(); setResult(2, intent); finish(); } } } } private void initView() { mUsername = (EditText)this.findViewById(R.id.r_username); mPassword = (EditText)this.findViewById(R.id.r_password); mSex = (RadioGroup)this.findViewById(R.id.radioGroup); mRegisterBtn =(Button)this.findViewById(R.id.register_btn); mIUserDao =new UserDaoImpl(this); mR=(RadioButton)this.findViewById(R.id.man_radio); } }
IndexActivity.java
package com.example.familybook; import android.app.Activity; import android.os.Bundle; import androidx.annotation.Nullable; public class IndexActivity extends Activity { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_index); } }
database
UserDatabaseHelper.java
package com.example.familybook.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import androidx.annotation.Nullable; import com.example.familybook.utils.Constants; public class UserDatabaseHelper extends SQLiteOpenHelper { private static final String TAG = "UserDatabaseHelper"; public UserDatabaseHelper(@Nullable Context context) { super(context, Constants.USER_DB_NAME,null,Constants.USER_DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { /** * 创建数据库 */ Log.e(TAG,"数据库创建....."); String createsql=" create table " +Constants.USER_TABLE_NAME +"("+Constants.USER_TABLE_FIELD_ID + " integer primary key autoincrement," +Constants.USER_TABLE_FIELD_UNAME +" varchar(30)," +Constants.USER_TABLE_FIELD_UPWD+ " varchar(32)," +Constants.USER_TABLE_FIELD_SEX +" varchar(5) )"; db.execSQL(createsql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /** * 数据库更新 */ } }
entity
User.java
package com.example.familybook.entity; /** * 用户账号实体类 */ public class User { private int _id; private String username; private String password; private String sex; public User( ) { } public User( String username, String password, String sex) { this.username = username; this.password = password; this.sex = sex; } public User(int id, String username, String password, String sex) { _id = id; this.username = username; this.password = password; this.sex = sex; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User{" + "_id=" + _id + ", username=‘" + username + ‘\‘‘ + ", password=‘" + password + ‘\‘‘ + ", sex=‘" + sex + ‘\‘‘ + ‘}‘; } }
utils
Constants.java
package com.example.familybook.utils; /** * 常量类 */ public class Constants { public static final String USER_DB_NAME="user.db"; public static final int USER_DB_VERSION=1; public static final String USER_TABLE_NAME="user"; public static final String USER_TABLE_FIELD_ID="_id"; public static final String USER_TABLE_FIELD_UNAME="username"; public static final String USER_TABLE_FIELD_UPWD="password"; public static final String USER_TABLE_FIELD_SEX="sex"; }
dao
IUserDao.java
package com.example.familybook.dao; import com.example.familybook.entity.User; /** * 这是User数据库接口层 */ public interface IUserDao { boolean isExist(String username); boolean Login(String username,String password); long Register(User user); User Query(String username,String password); User Query(String username); }
UserDaoImpl.java
package com.example.familybook.dao; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.familybook.database.UserDatabaseHelper; import com.example.familybook.entity.User; import com.example.familybook.utils.Constants; public class UserDaoImpl implements IUserDao { private final UserDatabaseHelper mUserDatabaseHelper; public UserDaoImpl(Context context){ mUserDatabaseHelper=new UserDatabaseHelper(context); } @Override public boolean isExist(String username) { return Query(username)==null? false:true; } /** * 该方法用于登录 * @param username * @param password * @return */ @Override public boolean Login(String username,String password) { return Query(username,password)==null? false:true; } /** * 该方法用于注册账户 * @param user * @return */ @Override public long Register(User user) { SQLiteDatabase db =mUserDatabaseHelper.getWritableDatabase(); long result =-1; // db.beginTransaction(); try { ContentValues values =new ContentValues(); values.put(Constants.USER_TABLE_FIELD_UNAME,user.getUsername()); values.put(Constants.USER_TABLE_FIELD_UPWD,user.getPassword()); values.put(Constants.USER_TABLE_FIELD_SEX,user.getSex()); result=db.insert(Constants.USER_TABLE_NAME,null,values); }catch (Exception e){ e.printStackTrace(); }finally { db.close(); // db.endTransaction(); } return result; } /** * 该方法是通过检查用户名和密码查询用户 * @param username * @param password * @return */ @Override public User Query(String username, String password) { User user= null; SQLiteDatabase db =mUserDatabaseHelper.getWritableDatabase(); /** * 如果数据库不为空,进行查询 */ // db.beginTransaction(); try { String sql = "select * from " + Constants.USER_TABLE_NAME + " where " + Constants.USER_TABLE_FIELD_UNAME + "=? and " + Constants.USER_TABLE_FIELD_UPWD + "=?"; String[] str = new String[]{username, password}; Cursor cursor = db.rawQuery(sql, str); /** * 下面在库中进行具体查询,并将 */ if (cursor.moveToNext()) { /** * 将查到的数据逐一封装到user对象中 */ user = new User(); //set id int userID = cursor.getInt(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_ID)); user.set_id(userID); //set username String uname = cursor.getString(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_UNAME)); user.setUsername(uname); //set password String upwd = cursor.getString(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_UPWD)); user.setPassword(upwd); //set sex String usex = cursor.getString(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_SEX)); user.setSex(usex); } } catch (Exception e) { e.printStackTrace(); } finally { db.close(); // db.endTransaction(); } return user; } /** * 该方法是通过检查用户名来查找用户 * @param username * @return */ @Override public User Query(String username) { User user= null; SQLiteDatabase db =mUserDatabaseHelper.getWritableDatabase(); // db.beginTransaction(); try { String sql ="select * from "+Constants.USER_TABLE_NAME+" where "+Constants.USER_TABLE_FIELD_UNAME+"=? "; String[] str =new String[]{username}; Cursor cursor =db.rawQuery(sql,str); /** * 下面在库中进行具体查询,并将 */ if(cursor.moveToNext()){ /** * 将查到的数据逐一封装到user对象中 */ user =new User(); //set id int userID = cursor.getInt(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_ID)); user.set_id(userID); //set username String uname=cursor.getString(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_UNAME)); user.setUsername(uname); //set password String upwd=cursor.getString(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_UPWD)); user.setPassword(upwd); //set sex String usex=cursor.getString(cursor.getColumnIndex(Constants.USER_TABLE_FIELD_SEX)); user.setSex(usex); } }catch (Exception e){ e.printStackTrace(); }finally { db.close(); // db.endTransaction(); } return user; } }
layout
activity_login.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@mipmap/login"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:padding="30dp" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_marginLeft="30dp" android:drawableLeft="@mipmap/ic_launcher_round" android:text="家庭记账本" android:textSize="40sp" android:layout_height="wrap_content"/> <EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_marginTop="30dp" android:maxLines="1" android:layout_height="wrap_content" android:hint="用户名" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:maxLines="1" android:hint="密码" /> <Button android:id="@+id/login_btn" android:layout_width="match_parent" android:text="登录" android:textSize="20sp" android:layout_height="wrap_content"/> <Button android:id="@+id/goto_register_btn" android:background="@android:color/transparent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_gravity="center" android:text="没有账号,立即去注册" android:textColor="#00ffff" android:textSize="16sp" /> </LinearLayout> </LinearLayout>
activity_register.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="@mipmap/register" android:padding="30dp" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:text="欢迎注册家庭记账本" android:textSize="30sp" android:layout_marginTop="30dp" android:layout_gravity="center" android:layout_height="wrap_content"/> <EditText android:id="@+id/r_username" android:layout_width="match_parent" android:layout_marginTop="30dp" android:hint="请输入用户名" android:layout_height="wrap_content"/> <EditText android:id="@+id/r_password" android:layout_width="match_parent" android:layout_marginTop="30dp" android:inputType="text" android:hint="请输入密码" android:layout_height="wrap_content"/> <RadioGroup android:id="@+id/radioGroup" android:layout_width="wrap_content" android:layout_gravity="center" android:orientation="horizontal" android:layout_height="wrap_content"> <RadioButton android:id="@+id/man_radio" android:layout_width="wrap_content" android:text="男" android:checked="true" android:layout_height="wrap_content"> </RadioButton> <RadioButton android:id="@+id/woman_group" android:layout_width="wrap_content" android:text="女" android:layout_height="wrap_content"> </RadioButton> </RadioGroup> <Button android:id="@+id/register_btn" android:layout_width="wrap_content" android:text="注册" android:layout_gravity="center" android:layout_height="wrap_content"/> </LinearLayout>
activity_index.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:text="首页" android:textSize="50sp" android:layout_gravity="center" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:text="登录成功" android:layout_marginTop="200dp" android:layout_gravity="center" android:textSize="40sp" android:layout_height="wrap_content"/> </LinearLayout>