如何在Assets文件夹中显示来自sqlite数据库的数据?

时间:2019-02-01 01:12:12

标签: java android database sqlite

我想在列表视图的资产文件夹中显示来自test.db的数据。我已经搜索了互联网,但还没有找到它。这是我的数据库助手的一个示例。

在test.db数据库中,有[数字,名称,学校]。如何显示数据? 我想在列表视图的资产文件夹中显示来自test.db的数据。我已经搜索了互联网,但还没有找到它。这是我的数据库助手的一个示例。

在test.db数据库中,有[数字,名称,学校]。如何显示数据? 我想在列表视图的资产文件夹中显示来自test.db的数据。我已经搜索了互联网,但还没有找到它。这是我的数据库助手的一个示例。

在test.db数据库中,有[数字,名称,学校]。如何显示数据?

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "test.db";
    private static final int DATABASE_VERSION = 1;
    private final Context context;
    SQLiteDatabase db;

    private static final String DATABASE_PATH = "/data/data/"+context.getPackageName()+"/databases/";
    private final String USER_TABLE = "user";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
        createDb();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void createDb(){
        boolean dbExist = checkDbExist();

        if(!dbExist){
            this.getReadableDatabase();
            copyDatabase();
        }
    }

    private boolean checkDbExist(){
        SQLiteDatabase sqLiteDatabase = null;

        try{
            String path = DATABASE_PATH + DATABASE_NAME;
            sqLiteDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        } catch (Exception ex){
        }

        if(sqLiteDatabase != null){
            sqLiteDatabase.close();
            return true;
        }

        return false;
    }

    private void copyDatabase(){
        try {
            InputStream inputStream = context.getAssets().open(DATABASE_NAME);

            String outFileName = DATABASE_PATH + DATABASE_NAME;

            OutputStream outputStream = new FileOutputStream(outFileName);

            byte[] b = new byte[1024];
            int length;

            while ((length = inputStream.read(b)) > 0){
                outputStream.write(b, 0, length);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private SQLiteDatabase openDatabase(){
        String path = DATABASE_PATH + DATABASE_NAME;
        db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
        return db;
    }
    public void close(){
        if(db != null){
            db.close();
        }
    }

1 个答案:

答案 0 :(得分:0)

  

如何显示数据?

您需要确定数据的显示方式/位置。假设通过一个Activity并通过ListView,则:-

然后您可能会通过查询来提取数据,可能使用SQLiteDatabase query method检索游标。

然后,您可以通过游标适配器,例如SimpleCursorAdapter

  • 请注意,CursorAdapters需要一列专门命名为 _id 的列,并且该列应该是rowid列的别名。

ListView 中显示行。

放在一起

以下代码(注释仅显示列表中的名称和School,您可以创建适合的布局)是基于数据库( test.db )的工作示例,该数据库包含名为<拥有数字名称学校

列的strong>用户
  • 注意:数据库帮助程序已更改为可处理Android 9+版本

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "test.db";
    private static final int DATABASE_VERSION = 1;
    private static String DATABASE_PATH;
    private final Context context;
    SQLiteDatabase db;

    //private static final String DATABASE_PATH = "/data/data/" + context.getPackageName() + "/databases/"; //<<<<<<<<<< no need to hard code anything see below
    public final static String USER_TABLE = "user";
    public final static String USER_NUMBERS_COLUMN = "numbers";
    public final static String USER_NAME_COLUMN = "name";
    public final static String USER_SCHOOL_COLUMN = "school";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
        DATABASE_PATH = context.getDatabasePath(DATABASE_NAME).getPath(); //<<<<<<<<<< Recommended way
        createDb();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void createDb() {
        boolean dbExist = checkDbExist();

        if (!dbExist) {
            //this.getReadableDatabase(); //<<<<<<<< will mess up Android 9 as it creates -wal and -shm files
            copyDatabase();
        }
    }

    private boolean checkDbExist() {

        /**
         * Checks the file instead of trying to open the database,
         * makes directories if needed (the get around to this was opening the database to create them)
         */
        File db = new File(DATABASE_PATH);
        if (!db.exists()) {
            if(!new File(db.getParent()).exists()) {
                new File(db.getParent()).mkdirs();
            }
            return false;
        } else {
            return true;
        }

        /* Done away with unreliable method
        SQLiteDatabase sqLiteDatabase = null;
        try {
            String path = DATABASE_PATH;
            sqLiteDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        } catch (Exception ex) {
        }
        if (sqLiteDatabase != null) {
            sqLiteDatabase.close();
            return true;
        }
        return false;
        */
    }

    private void copyDatabase() {
        try {
            InputStream inputStream = context.getAssets().open(DATABASE_NAME);
            String outFileName = DATABASE_PATH;
            OutputStream outputStream = new FileOutputStream(outFileName);

            byte[] b = new byte[1024];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private SQLiteDatabase openDatabase() {
        String path = DATABASE_PATH;
        db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
        return db;
    }

    public void close() {
        if (db != null) {
            db.close();
        }
    }

    /**
     * Extract all columns for all rows adding column _id for CursorAdapter
     */
    public Cursor getAllMyData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String[] columns = new String[]{"*,rowid AS " + BaseColumns._ID};
        return db.query(
                USER_TABLE,columns,
                null,null,null,null,null);
    }
}
  • 注意事项
    • 查看评论以获取一些解释
    • 遗留了一些旧代码,但已将其注释掉

MainActivity.java

这是所使用的活动,包括一个ListView

 public class MainActivity extends AppCompatActivity {

    DatabaseHelper mDBHlpr;
    Cursor mCsr;
    ListView mUserList;
    SimpleCursorAdapter mSCA;
    Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        mUserList = this.findViewById(R.id.userlist); //<<<<<<<<<< id of the ListView
        mDBHlpr = new DatabaseHelper(this); //Instantiate the database helper
        setupOrRefreshTheListView();
    }

    private void setupOrRefreshTheListView() {
        mCsr = mDBHlpr.getAllMyData();
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    mCsr,
                    // Columns from the Cursor to include in the ListView (must have a corresponding view in the layout)
                    new String[]{
                            DatabaseHelper.USER_NAME_COLUMN,
                            DatabaseHelper.USER_SCHOOL_COLUMN
                    },
                    // Views in the ListView into which the Data is placed (must correspond with Column in the Cursor)
                    new int[]{
                            android.R.id.text1,
                            android.R.id.text2},
                    0
            );
            mUserList.setAdapter(mSCA);
            // Add an on item click listener in this case Toasts data
            mUserList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(
                            mContext,
                            "You clicked the row with an ID of " + String.valueOf(id) +
                                    " Name is " + mCsr.getString(mCsr.getColumnIndex(DatabaseHelper.USER_NAME_COLUMN)) +
                                    " School is " + mCsr.getString(mCsr.getColumnIndex(DatabaseHelper.USER_SCHOOL_COLUMN)) +
                                    " Numbers is " + String.valueOf(mCsr.getInt(mCsr.getColumnIndex(DatabaseHelper.USER_NUMBERS_COLUMN))),
                            Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            mSCA.swapCursor(mCsr); // This reapplies the Cursor to reflect any changes
        }
    }
}

以上内容已在API 21(棒棒糖)和28(派)上运行。以下是一个示例屏幕截图:-

enter image description here