📜  如何在Android中创建数据并将数据添加到SQLite数据库?

📅  最后修改于: 2021-05-09 18:34:16             🧑  作者: Mango

SQLite是Android中另一个可用的数据存储,我们可以在其中将数据存储在用户的设备中,并可以在需要时随时使用。在本文中,我们将介绍在Android应用程序中创建SQLite数据库以及在Android应用程序中向该数据库添加数据的过程。这是一系列4篇文章的系列文章,我们将在Android中使用SQLite数据库执行基本的CRUD(创建,读取,更新和删除)操作。我们将在本系列中涵盖以下4篇文章:

  1. 如何在Android中创建数据并将数据添加到SQLite数据库?
  2. 如何从Android中的SQLite数据库读取数据?
  3. 如何在Android中将数据更新到SQLite数据库?
  4. 如何在Android的SQLite数据库中删除数据?

什么是SQLite数据库?

SQLite数据库是Android提供的开源数据库,用于以文本文件的形式在用户设备内存储数据。我们可以对此数据执行许多操作,例如添加新数据,更新,读取和删除该数据。 SQLite是一个脱机数据库,它本地存储在用户设备中,我们不必创建任何连接即可连接到该数据库。

如何将数据存储在SQLite数据库中?

数据以的形式存储在SQLite数据库中。当我们将这些数据存储在SQLite数据库中时,它以类似于excel工作表的表的形式排列。下面是存储在SQLite数据库中的SQLite数据库的表示形式。

如何将数据存储在SQLite数据库中?

SQLite数据库中的重要方法

以下是我们将在Android的此SQLite数据库集成中使用的几种重要方法。

Method

Description

getColumnNames() This method is used to get the Array of column names of our SQLite table. 
getCount() This method will return the number of rows in the cursor. 
isClosed() This method returns a Boolean value when our cursor is closed. 
getColumnCount() This method returns the total number of columns present in our table. 
getColumnName(int columnIndex) This method will return the name of the column when we passed the index of our column in it. 
getColumnIndex(String columnName) This method will return the index of our column from the name of the column.
getPosition() This method will return the current position of our cursor in our table. 

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中将数据添加到SQLite数据库。我们将创建一个数据库,用于添加课程名称,课程说明,课程持续时间和课程曲目。我们将所有这些数据保存在我们的SQLite数据库中。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在AndroidManifest.xml文件中添加访问存储的权限

导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。

XML


XML


  
    
    
  
    
    
  
    
    
  
    
    
  
    
    


Java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
  
public class DBHandler extends SQLiteOpenHelper {
  
    // creating a constant variables for our database.
    // below variable is for our database name.
    private static final String DB_NAME = "coursedb";
      
    // below int is our database version
    private static final int DB_VERSION = 1;
      
    // below variable is for our table name.
    private static final String TABLE_NAME = "mycourses";
      
    // below variable is for our id column.
    private static final String ID_COL = "id";
      
    // below variable is for our course name column
    private static final String NAME_COL = "name";
      
    // below variable id for our course duration column.
    private static final String DURATION_COL = "duration";
      
    // below variable for our course description column.
    private static final String DESCRIPTION_COL = "description";
     
    // below variable is for our course tracks column.
    private static final String TRACKS_COL = "tracks";
  
    // creating a constructor for our database handler.
    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
  
    // below method is for creating a database by running a sqlite query
    @Override
    public void onCreate(SQLiteDatabase db) {
        // on below line we are creating 
        // an sqlite query and we are 
        // setting our column names
        // along with their data types.
        String query = "CREATE TABLE " + TABLE_NAME + " ("
                + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + NAME_COL + " TEXT,"
                + DURATION_COL + " TEXT,"
                + DESCRIPTION_COL + " TEXT,"
                + TRACKS_COL + " TEXT)";
  
        // at last we are calling a exec sql 
        // method to execute above sql query
        db.execSQL(query);
    }
  
    // this method is use to add new course to our sqlite database.
    public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {
          
        // on below line we are creating a variable for 
        // our sqlite database and calling writable method 
        // as we are writing data in our database.
        SQLiteDatabase db = this.getWritableDatabase();
          
        // on below line we are creating a 
        // variable for content values.
        ContentValues values = new ContentValues();
          
        // on below line we are passing all values 
        // along with its key and value pair.
        values.put(NAME_COL, courseName);
        values.put(DURATION_COL, courseDuration);
        values.put(DESCRIPTION_COL, courseDescription);
        values.put(TRACKS_COL, courseTracks);
          
        // after adding all values we are passing
        // content values to our table.
        db.insert(TABLE_NAME, null, values);
          
        // at last we are closing our
        // database after adding database.
        db.close();
    }
  
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // this method is called to check if the table exists already.
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}


Java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our edittext, button and dbhandler
    private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;
    private Button addCourseBtn;
    private DBHandler dbHandler;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing all our variables.
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        addCourseBtn = findViewById(R.id.idBtnAddCourse);
          
        // creating a new dbhandler class 
        // and passing our context to it.
        dbHandler = new DBHandler(MainActivity.this);
          
        // below line is to add on click listener for our add course button.
        addCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  
                // below line is to get data from all edit text fields.
                String courseName = courseNameEdt.getText().toString();
                String courseTracks = courseTracksEdt.getText().toString();
                String courseDuration = courseDurationEdt.getText().toString();
                String courseDescription = courseDescriptionEdt.getText().toString();
                 
                // validating if the text fields are empty or not.
                if (courseName.isEmpty() && courseTracks.isEmpty() && courseDuration.isEmpty() && courseDescription.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter all the data..", Toast.LENGTH_SHORT).show();
                    return;
                }
                  
                // on below line we are calling a method to add new 
                // course to sqlite data and pass all our values to it.
                dbHandler.addNewCourse(courseName, courseDuration, courseDescription, courseTracks);
                  
                // after adding the data we are displaying a toast message.
                Toast.makeText(MainActivity.this, "Course has been added.", Toast.LENGTH_SHORT).show();
                courseNameEdt.setText("");
                courseDurationEdt.setText("");
                courseTracksEdt.setText("");
                courseDescriptionEdt.setText("");
            }
        });
    }
}


步骤3:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  
    
    
  
    
    
  
    
    
  
    
    

步骤4:创建新的Java类以执行SQLite操作

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为DBHandler并向其中添加以下代码。在代码内部添加了注释,以更详细地了解代码。

Java

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
  
public class DBHandler extends SQLiteOpenHelper {
  
    // creating a constant variables for our database.
    // below variable is for our database name.
    private static final String DB_NAME = "coursedb";
      
    // below int is our database version
    private static final int DB_VERSION = 1;
      
    // below variable is for our table name.
    private static final String TABLE_NAME = "mycourses";
      
    // below variable is for our id column.
    private static final String ID_COL = "id";
      
    // below variable is for our course name column
    private static final String NAME_COL = "name";
      
    // below variable id for our course duration column.
    private static final String DURATION_COL = "duration";
      
    // below variable for our course description column.
    private static final String DESCRIPTION_COL = "description";
     
    // below variable is for our course tracks column.
    private static final String TRACKS_COL = "tracks";
  
    // creating a constructor for our database handler.
    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
  
    // below method is for creating a database by running a sqlite query
    @Override
    public void onCreate(SQLiteDatabase db) {
        // on below line we are creating 
        // an sqlite query and we are 
        // setting our column names
        // along with their data types.
        String query = "CREATE TABLE " + TABLE_NAME + " ("
                + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + NAME_COL + " TEXT,"
                + DURATION_COL + " TEXT,"
                + DESCRIPTION_COL + " TEXT,"
                + TRACKS_COL + " TEXT)";
  
        // at last we are calling a exec sql 
        // method to execute above sql query
        db.execSQL(query);
    }
  
    // this method is use to add new course to our sqlite database.
    public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {
          
        // on below line we are creating a variable for 
        // our sqlite database and calling writable method 
        // as we are writing data in our database.
        SQLiteDatabase db = this.getWritableDatabase();
          
        // on below line we are creating a 
        // variable for content values.
        ContentValues values = new ContentValues();
          
        // on below line we are passing all values 
        // along with its key and value pair.
        values.put(NAME_COL, courseName);
        values.put(DURATION_COL, courseDuration);
        values.put(DESCRIPTION_COL, courseDescription);
        values.put(TRACKS_COL, courseTracks);
          
        // after adding all values we are passing
        // content values to our table.
        db.insert(TABLE_NAME, null, values);
          
        // at last we are closing our
        // database after adding database.
        db.close();
    }
  
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // this method is called to check if the table exists already.
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}

步骤5:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our edittext, button and dbhandler
    private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;
    private Button addCourseBtn;
    private DBHandler dbHandler;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // initializing all our variables.
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        addCourseBtn = findViewById(R.id.idBtnAddCourse);
          
        // creating a new dbhandler class 
        // and passing our context to it.
        dbHandler = new DBHandler(MainActivity.this);
          
        // below line is to add on click listener for our add course button.
        addCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  
                // below line is to get data from all edit text fields.
                String courseName = courseNameEdt.getText().toString();
                String courseTracks = courseTracksEdt.getText().toString();
                String courseDuration = courseDurationEdt.getText().toString();
                String courseDescription = courseDescriptionEdt.getText().toString();
                 
                // validating if the text fields are empty or not.
                if (courseName.isEmpty() && courseTracks.isEmpty() && courseDuration.isEmpty() && courseDescription.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter all the data..", Toast.LENGTH_SHORT).show();
                    return;
                }
                  
                // on below line we are calling a method to add new 
                // course to sqlite data and pass all our values to it.
                dbHandler.addNewCourse(courseName, courseDuration, courseDescription, courseTracks);
                  
                // after adding the data we are displaying a toast message.
                Toast.makeText(MainActivity.this, "Course has been added.", Toast.LENGTH_SHORT).show();
                courseNameEdt.setText("");
                courseDurationEdt.setText("");
                courseTracksEdt.setText("");
                courseDescriptionEdt.setText("");
            }
        });
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

成功执行代码后,在EditText中输入所需的数据。最重要的是,如果您想了解如何在Android Studio中查看和定位SQLite数据库,请参考本文您可以在下面看到这是如何将数据存储在SQLite数据库中的

下面是执行创建和添加操作之后的完整项目文件结构: