Android studio introduces an external SQLite database to obtain database list data

Preparation:

Prepare Android studio and a software for creating and managing databases, recommend SQLite Expert Professional or Navicat Premium. Here take SQLite Expert Professional as an example.

Create an external database:

1. Wear a sqlite database, define the database and corresponding data tables according to your own project requirements

Import the database into the Android studio project

1. Create an assets file in the main directory, and put the prepared sqlite database file into this directory

Explanation: The files under the assets folder will not be compressed when the application is packaged into an apk

2. Create a java class in the com.example.xxxx package under the java directory under the main directory to manage the database, as shown in the figure MyDatabaseHelper

 3. Complete the import of the database in the database class

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class MyDatabaseHelper {

    //导入的sqlite数据库文件名
    private final String DB_NAME = "questionCenter.db";
    private SQLiteDatabase myDatabase;
    private Context context;

    //定义类的方法
    public MyDatabaseHelper(Context context) {
        this.context = context;
    }





    // 复制和加载区域数据库中的数据
    public String CopyDBFile() throws IOException {

        // 在第一次运行应用程序时,加载数据库到data/data/当前包的名称/database/数据库名字
        //获取准确的路径,context.getPackageName()得到包名
        File dir = new File("data/data/" + context.getPackageName() + "/databases");
        //如果文件夹不存在,则创建指定的文件
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdir();
        }
        //文件声明
        File file = new File(dir, DB_NAME);
        //输入流
        InputStream inputStream = null;
        //输出流
        OutputStream outputStream = null;
        //若不存在,通过IO流的方式,将assets目录下的数据库文件,写入到项目模拟手机中,当开启模拟 
        //器时,会将数据库文件写入到模拟手机的内存中
        if (!file.exists()) {
            try {
                //创建文件
                file.createNewFile();
                //加载文件
                inputStream = context.getClass().getClassLoader().getResourceAsStream("assets/" + DB_NAME);
                //输出到文件
                outputStream = new FileOutputStream(file);

                byte[] buffer = new byte[1024];
                int len;
                //按字节写入
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }


            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                //关闭资源
                if (outputStream != null) {

                    outputStream.flush();
                    outputStream.close();

                }
                if (inputStream != null) {
                    inputStream.close();
                }

            }

        }

        return file.getPath();
    }
}

4. Open the first Activity when your Android project is running, and in the corresponding oncreate() method, use the database import method defined in the database class to complete the database initialization operation

Note: Not necessarily in the first Activity, but must import the database in the Activity before the project uses the database

 //导入数据库到创建的文件中
MyDatabaseHelper myHelper = new MyDatabaseHelper(WelcomeActivity.this);
        try {
            myHelper.CopyDBFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

In the position shown in the figure:

5. In the oncreate() method of the corresponding Activity, use the code shown in the figure to open the database, perform crud operations, add, delete, check and modify, and obtain database data

 Get database data: (use list collection)

1. Define a java class in the project to define the column names corresponding to the data table. Take the user table as an example:

 The code for the corresponding user class is as follows:

public class UserDemo {
    //对应userInfo数据库中的数据信息
    public String username;
    public String password;
    public  String savepsd;
    public String autologin;
    public String isregister;
    public int lastscore;

}

 2. Obtain the information data of the data table according to your own requirements

 //获取数据库的用户数据
    public List<UserDemo> getUsers(){
        List<UserDemo> list=new ArrayList<UserDemo>();
        //这是获取完整数据表信息的方法
        Cursor cursor = myDatabase.query("userInfo.db",null,null,null,null,null,null);
        //也可以使用Cursor对象的rawQuery方法,使用sql指定的数据
        //Cursor cursor = myDatabase.rawQuery("select * from userInfo",null);
        if(cursor.getCount()>0){
            cursor.moveToFirst();//将cursor移动到第一个光标上
            int count=cursor.getCount();
            //将cursor中的每一条记录生成一个question对象,并将该question对象添加到list中
            for(int i=0;i<count;i++){
                cursor.moveToPosition(i);
                UserDemo users =new UserDemo();
                users.username=cursor.getString(cursor.getColumnIndex("username"));
                users.lastscore=cursor.getInt(cursor.getColumnIndex("lastscoren"));
                users.password=cursor.getString(cursor.getColumnIndex("password"));
                users.autologin=cursor.getString(cursor.getColumnIndex("autologin"));
                users.savepsd=cursor.getString(cursor.getColumnIndex("savepsd"));
                users.isregister=cursor.getString(cursor.getColumnIndex("isregister"));
                list.add(users);
            }
           // System.out.println(list.get(2)); //可输出list集合的数据
        }
        return list;
    }

3. After obtaining the data through the collection, you can implement the corresponding functions according to your own requirements

If you need to operate the imported database, you can refer to the external sqlite database to operate the database after importing https://blog.csdn.net/NXBBC/article/details/123734221?spm=1001.2014.3001.5502

Guess you like

Origin blog.csdn.net/NXBBC/article/details/123663345