原文: https://javatutorial.net/android-sqlite-database-example

[上一教程(https://javatutorial.net/android-sqlite-database-introduction)对 Android 中的 SQLite 数据库进行了简介。 本教程以示例说明了所有 CRUD(创建,检索,更新,删除)功能。

示例背景

让我们开始使用 SQLite 数据库。 本示例全部有关注册和登录过程以及将用户凭据存储到数据库中的逐步说明。 当用户单击“注册”按钮时,将出现一个新活动,并且用户填写该表单,该表单具有四个值,分别是名字,姓氏,电子邮件 ID 和密码。 当用户单击“确定”按钮时,这些值将保存到数据库中。 下图显示了数据库中的注册表的外观

Android SQLite 数据库示例 - 图1

登录表

第 1 步:活动布局

让我们开始创建用于注册和登录的 xml 布局。如上所述,注册有四个字段和一个确定按钮。 用户单击“确定”按钮时,将显示一个对话框,因为已保存值,然后将开始登录活动。

这是activity_main.xml的代码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout android:layout_width="368dp"
  3. android:layout_height="495dp"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. tools:layout_editor_absoluteX="8dp"
  6. tools:layout_editor_absoluteY="8dp"
  7. xmlns:android="http://schemas.android.com/apk/res/android">
  8. <TextView
  9. android:id="@+id/textView2"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:layout_alignParentTop="true"
  13. android:layout_centerHorizontal="true"
  14. android:layout_marginTop="104dp"
  15. android:text="Sign In"
  16. android:textColor="@android:color/holo_red_dark"
  17. android:textSize="25sp" />
  18. <EditText
  19. android:id="@+id/Email"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_below="@+id/textView2"
  23. android:layout_centerHorizontal="true"
  24. android:layout_marginTop="26dp"
  25. android:ems="10"
  26. android:inputType="textPersonName"
  27. android:text="Email ID" />
  28. <EditText
  29. android:id="@+id/Password"
  30. android:layout_width="wrap_content"
  31. android:layout_height="wrap_content"
  32. android:layout_alignEnd="@+id/Email"
  33. android:layout_alignRight="@+id/Email"
  34. android:layout_centerVertical="true"
  35. android:ems="10"
  36. android:inputType="textPassword"
  37. android:text="password" />
  38. <Button
  39. android:id="@+id/buttonSignIn"
  40. android:layout_width="wrap_content"
  41. android:layout_height="wrap_content"
  42. android:layout_alignLeft="@+id/Password"
  43. android:layout_alignStart="@+id/Password"
  44. android:layout_below="@+id/Password"
  45. android:layout_marginTop="52dp"
  46. android:backgroundTint="@color/colorAccent"
  47. android:onClick="SignIN"
  48. android:text="Sign In" />
  49. <Button
  50. android:id="@+id/buttonSignUp"
  51. android:layout_width="wrap_content"
  52. android:layout_height="wrap_content"
  53. android:layout_alignEnd="@+id/Password"
  54. android:layout_alignRight="@+id/Password"
  55. android:layout_alignTop="@+id/buttonSignIn"
  56. android:backgroundTint="@color/colorAccent"
  57. android:onClick="SignUP"
  58. android:text="Sign Up" />
  59. </RelativeLayout>

现在为activity_sign_up.xml创建另一个布局。 登录有两个字段和两个按钮,分别是“登录”和“登录”。 如果您已经有一个帐户,请输入 ID 和密码并登录。如果没有,请单击“注册”按钮并为您创建帐户。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout android:layout_width="368dp"
  3. android:layout_height="495dp"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. tools:layout_editor_absoluteX="8dp"
  6. tools:layout_editor_absoluteY="8dp"
  7. xmlns:android="http://schemas.android.com/apk/res/android">
  8. <TextView
  9. android:id="@+id/tSignUP"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:text="Sign Up"
  13. android:textColor="@android:color/holo_red_dark"
  14. android:textSize="25sp"
  15. android:layout_alignParentTop="true"
  16. android:layout_centerHorizontal="true"
  17. android:layout_marginTop="22dp" />
  18. <EditText
  19. android:id="@+id/tFirstName"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_below="@+id/tSignUP"
  23. android:layout_centerHorizontal="true"
  24. android:layout_marginTop="26dp"
  25. android:ems="10"
  26. android:inputType="textPersonName"
  27. android:text="First Name" />
  28. <EditText
  29. android:id="@+id/tPassword"
  30. android:layout_width="wrap_content"
  31. android:layout_height="wrap_content"
  32. android:ems="10"
  33. android:inputType="textPassword"
  34. android:text="password"
  35. android:layout_below="@+id/tEmail"
  36. android:layout_alignLeft="@+id/tEmail"
  37. android:layout_alignStart="@+id/tEmail"
  38. android:layout_marginTop="23dp" />
  39. <EditText
  40. android:id="@+id/tLastName"
  41. android:layout_width="wrap_content"
  42. android:layout_height="wrap_content"
  43. android:layout_alignLeft="@+id/tFirstName"
  44. android:layout_alignStart="@+id/tFirstName"
  45. android:layout_below="@+id/tFirstName"
  46. android:layout_marginTop="14dp"
  47. android:ems="10"
  48. android:inputType="textPersonName"
  49. android:text="Last Name" />
  50. <EditText
  51. android:id="@+id/tEmail"
  52. android:layout_width="wrap_content"
  53. android:layout_height="wrap_content"
  54. android:layout_alignEnd="@+id/tLastName"
  55. android:layout_alignRight="@+id/tLastName"
  56. android:layout_below="@+id/tLastName"
  57. android:layout_marginTop="25dp"
  58. android:ems="10"
  59. android:inputType="textPersonName"
  60. android:text="Email ID" />
  61. <Button
  62. android:id="@+id/buttonOK"
  63. android:layout_width="wrap_content"
  64. android:layout_height="wrap_content"
  65. android:layout_alignEnd="@+id/tPassword"
  66. android:layout_alignRight="@+id/tPassword"
  67. android:layout_below="@+id/tPassword"
  68. android:layout_marginTop="47dp"
  69. android:background="@color/colorAccent"
  70. android:onClick="OK"
  71. android:text="OK" />
  72. </RelativeLayout>

步骤 2:创建数据库助手类

此类在磁盘上创建数据库。

  1. package com.example.admin.androiddatabaseexample;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteDatabase.CursorFactory;
  5. import android.database.sqlite.SQLiteOpenHelper;
  6. import android.util.Log;
  7. public class DataBaseHelper extends SQLiteOpenHelper {
  8. public DataBaseHelper(Context context, String name, CursorFactory factory, int version) {
  9. super(context, name, factory, version);
  10. }
  11. // Called when no database exists in disk and the helper class needs
  12. // to create a new one.
  13. @Override
  14. public void onCreate(SQLiteDatabase _db) {
  15. try {
  16. _db.execSQL(LoginDatabaseAdapter.DATABASE_CREATE);
  17. }catch(Exception er){
  18. Log.e("Error","exceptioin");
  19. }
  20. }
  21. // Called when there is a database version mismatch meaning that the version
  22. // of the database on disk needs to be upgraded to the current version.
  23. @Override
  24. public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
  25. {
  26. // Log the version upgrade.
  27. Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
  28. // Upgrade the existing database to conform to the new version. Multiple
  29. // previous versions can be handled by comparing _oldVersion and _newVersion
  30. // values.
  31. // The simplest case is to drop the old table and create a new one.
  32. _db.execSQL("DROP TABLE IF EXISTS " + "LOGIN");
  33. // Create a new one.
  34. onCreate(_db);
  35. }
  36. }

步骤 3:创建登录数据库类

登录数据库是一类,您在其中实现所有数据库编码。 首先使用四个字段创建用于登录的表,然后实现所有其他方法。

  1. package com.example.admin.androiddatabaseexample;
  2. import android.app.AlertDialog;
  3. import android.content.ContentValues;
  4. import android.content.Context;
  5. import android.content.DialogInterface;
  6. import android.database.Cursor;
  7. import android.database.SQLException;
  8. import android.database.sqlite.SQLiteDatabase;
  9. import android.util.Log;
  10. import android.widget.Toast;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. public class LoginDatabaseAdapter {
  14. static final String DATABASE_NAME = "database.db";
  15. String ok="OK";
  16. static final int DATABASE_VERSION = 1;
  17. public static String getPassword="";
  18. public static final int NAME_COLUMN = 1;
  19. // TODO: Create public field for each column in your table.
  20. // SQL Statement to create a new database.
  21. static final String DATABASE_CREATE = "create table LOGIN( ID integer primary key autoincrement,FIRSTNAME text,LASTNAME text,USERNAME text,PASSWORD text); ";
  22. // Variable to hold the database instance
  23. public static SQLiteDatabase db;
  24. // Context of the application using the database.
  25. private final Context context;
  26. // Database open/upgrade helper
  27. private static DataBaseHelper dbHelper;
  28. public LoginDatabaseAdapter(Context _context)
  29. {
  30. context = _context;
  31. dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
  32. }
  33. // Method to openthe Database
  34. public LoginDatabaseAdapter open() throws SQLException
  35. {
  36. db = dbHelper.getWritableDatabase(); return this;
  37. }
  38. // Method to close the Database
  39. public void close()
  40. {
  41. db.close();
  42. }
  43. // method returns an Instance of the Database
  44. public SQLiteDatabase getDatabaseInstance()
  45. {
  46. return db;
  47. }
  48. // method to insert a record in Table
  49. public String insertEntry(String firstName,String lastName,String Id,String password)
  50. {
  51. try {
  52. ContentValues newValues = new ContentValues();
  53. // Assign values for each column.
  54. newValues.put("FIRSTNAME", firstName);
  55. newValues.put("LASTNAME", lastName);
  56. newValues.put("USERNAME", Id);
  57. newValues.put("PASSWORD", password);
  58. // Insert the row into your table
  59. db = dbHelper.getWritableDatabase();
  60. long result=db.insert("LOGIN", null, newValues);
  61. System.out.print(result);
  62. Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show();
  63. }catch(Exception ex) {
  64. System.out.println("Exceptions " +ex);
  65. Log.e("Note", "One row entered");
  66. }
  67. return ok;
  68. }
  69. // method to delete a Record of UserName
  70. public int deleteEntry(String UserName)
  71. {
  72. String where="USERNAME=?";
  73. int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
  74. Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
  75. return numberOFEntriesDeleted;
  76. }
  77. // method to get the password of userName
  78. public String getSinlgeEntry(String userName)
  79. {
  80. db=dbHelper.getReadableDatabase();
  81. Cursor cursor=db.query("LOGIN", null, "USERNAME=?", new String[]{userName}, null, null, null);
  82. if(cursor.getCount()<1) // UserName Not Exist
  83. return "NOT EXIST";
  84. cursor.moveToFirst();
  85. getPassword= cursor.getString(cursor.getColumnIndex("PASSWORD"));
  86. return getPassword;
  87. }
  88. // Method to Update an Existing
  89. public void updateEntry(String userName,String password)
  90. {
  91. // create object of ContentValues
  92. ContentValues updatedValues = new ContentValues();
  93. // Assign values for each Column.
  94. updatedValues.put("USERNAME", userName);
  95. updatedValues.put("PASSWORD", password);
  96. String where="USERNAME = ?";
  97. db.update("LOGIN",updatedValues, where, new String[]{userName});
  98. }
  99. }

步骤 4:MainActivity.java

在该类中,您可以从登录活动中获取 ID 和密码,并在点击监听器上实现登录和注册按钮。

  1. package com.example.admin.androiddatabaseexample;
  2. import android.app.AlertDialog;
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.content.Intent;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.os.Bundle;
  8. import android.util.Log;
  9. import android.view.View;
  10. import android.widget.EditText;
  11. public class MainActivity extends AppCompatActivity {
  12. private EditText etUserEmail;
  13. private EditText etPassword;
  14. public String username;
  15. private String password;
  16. String storedPassword;
  17. Context context=this;
  18. LoginDatabaseAdapter loginDataBaseAdapter;
  19. @Override
  20. protected void onCreate(Bundle savedInstanceState) {
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.activity_main);
  23. // create the instance of Databse
  24. loginDataBaseAdapter=new LoginDatabaseAdapter(getApplicationContext());
  25. etUserEmail = (EditText) findViewById(R.id.Email);
  26. etPassword = (EditText) findViewById(R.id.Password);
  27. }
  28. public void SignIN(View view) {
  29. try {
  30. loginDataBaseAdapter = loginDataBaseAdapter.open();
  31. username = etUserEmail.getText().toString();
  32. password = etPassword.getText().toString();
  33. if (username.equals("") || password.equals("")) {
  34. AlertDialog alertDialog = new AlertDialog.Builder(this).create();
  35. alertDialog.setTitle("ALERT!");
  36. alertDialog.setMessage("Fill All Fields");
  37. alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
  38. public void onClick(DialogInterface dialog, int which) {
  39. }
  40. });
  41. alertDialog.show();
  42. }
  43. // fetch the Password form database for respective user name
  44. if (!username.equals("")) {
  45. storedPassword = loginDataBaseAdapter.getSinlgeEntry(username);
  46. // check if the Stored password matches with Password entered by user
  47. if (password.equals(storedPassword)) {
  48. Intent intent1 = new Intent(MainActivity.this, DisplayInfoActivity.class);
  49. startActivity(intent1);
  50. // finish();
  51. }
  52. else
  53. {
  54. AlertDialog alertDialog = new AlertDialog.Builder(this).create();
  55. alertDialog.setTitle("ALERT!");
  56. alertDialog.setMessage("Incorrect Username OR Password");
  57. alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
  58. public void onClick(DialogInterface dialog, int which) {
  59. }
  60. });
  61. alertDialog.show();
  62. }
  63. }
  64. }
  65. catch (Exception ex)
  66. {
  67. Log.e("Error", "error login");
  68. }
  69. }
  70. public void SignUP(View view)
  71. {
  72. Intent intent = new Intent(MainActivity.this, SignUp.class);
  73. startActivity(intent);
  74. }
  75. @Override
  76. protected void onDestroy()
  77. {
  78. // TODO Auto-generated method stub
  79. super.onDestroy();
  80. // Close The Database
  81. loginDataBaseAdapter.close();
  82. }
  83. }

步骤 5:SignUp.java

当用户在注册活动中单击“确定”按钮时,将出现一个对话框,指出值已添加到数据库的登录表中。

  1. package com.example.admin.androiddatabaseexample;
  2. import android.support.v7.app.AppCompatActivity;
  3. import android.os.Bundle;
  4. import android.app.AlertDialog;
  5. import android.content.Context;
  6. import android.content.DialogInterface;
  7. import android.content.Intent;
  8. import android.view.View;
  9. import android.widget.EditText;
  10. public class SignUp extends AppCompatActivity {
  11. Context context=this;
  12. private EditText et_first_name;
  13. private EditText et_last_name;
  14. private EditText et_ID;
  15. private EditText et_password;
  16. private String firstName;
  17. private String lastName;
  18. private String userName;
  19. private String password;
  20. String receieveOk;
  21. LoginDatabaseAdapter loginDataBaseAdapter;
  22. @Override
  23. protected void onCreate(Bundle savedInstanceState)
  24. {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.activity_sign_up);
  27. // get Instance of Database Adapter
  28. loginDataBaseAdapter=new LoginDatabaseAdapter(getApplicationContext());
  29. loginDataBaseAdapter=loginDataBaseAdapter.open();
  30. et_first_name = (EditText) findViewById(R.id.tFirstName);
  31. et_last_name = (EditText) findViewById(R.id.tLastName);
  32. et_ID = (EditText) findViewById(R.id.tEmail);
  33. et_password = (EditText) findViewById(R.id.tPassword);
  34. }
  35. public void OK(View view)
  36. {
  37. firstName = et_first_name.getText().toString();
  38. lastName = et_last_name.getText().toString();
  39. userName = et_ID.getText().toString();
  40. password = et_ID.getText().toString();
  41. if((firstName.equals(""))||(lastName.equals(""))||(userName.equals(""))||(password.equals("")))
  42. {
  43. //Display Message
  44. AlertDialog alertDialog = new AlertDialog.Builder(this).create();
  45. alertDialog.setTitle("ALERT!");
  46. alertDialog.setMessage("All fields must be filled");
  47. alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
  48. public void onClick(DialogInterface dialog, int which) {
  49. }
  50. });
  51. alertDialog.show();
  52. }
  53. else
  54. {
  55. // Save the Data in Database
  56. receieveOk=loginDataBaseAdapter.insertEntry(firstName,lastName,userName, password);
  57. AlertDialog alertDialog = new AlertDialog.Builder(this).create();
  58. alertDialog.setTitle("SUCCESSFUL!");
  59. alertDialog.setMessage("SIGN IN NOW " + receieveOk);
  60. alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
  61. public void onClick(DialogInterface dialog, int which) {
  62. Intent intent = new Intent(SignUp.this, MainActivity.class);
  63. startActivity(intent);
  64. }
  65. });
  66. alertDialog.show();
  67. finish();
  68. }
  69. }
  70. @Override
  71. protected void onDestroy()
  72. {
  73. // TODO Auto-generated method stub
  74. super.onDestroy();
  75. loginDataBaseAdapter.close();
  76. }
  77. }

现在运行您的应用程序并进行测试。 这是正在运行的应用程序的屏幕截图

Android SQLite 数据库示例 - 图2

登入

Android SQLite 数据库示例 - 图3

错误的 ID 或密码

Android SQLite 数据库示例 - 图4

注册

您可以从链接下载此代码。