android - 如何使用带有 Activity android的现成sql数据库启动应用程序

标签 android sqlite android-studio activeandroid

我想使用预制的 SQLite 数据库启动我的应用程序, 我将能够读取和写入。 我目前在我的应用程序中使用 Active Android 来读取和写入 MySQL 表。 是否有可能使用 Active android 从文件中打开 SQLite 数据库表?或者是否有更好的实现方法?

最佳答案

您可以从 android 的 Assets 文件夹中读取您的数据库文件 (.sqlite)。你可以通过这个在线创建你的数据库文件(.sqlite)url以及读取此文件的 Java 代码如下:-

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.freshstartappz.appusagetracker.dto.AppInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;


public class DataBaseHelper extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "AppTracker.sqlite";

    private static final String DB_PATH_SUFFIX = "/databases/";
    static Context ctx;

    public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        ctx = context;
    }


    public void CopyDataBaseFromAsset() throws IOException {


        InputStream myInput = ctx.getAssets().open(DATABASE_NAME);

        // Path to the just created empty db

        String outFileName = getDatabasePath();

        // if the path doesn't exist first, create it
        File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);

        if (!f.exists())

            f.mkdir();

        // Open the empty db as the output stream

        OutputStream myOutput = new FileOutputStream(outFileName);


        // transfer bytes from the inputfile to the outputfile

        byte[] buffer = new byte[1024];

        int length;

        while ((length = myInput.read(buffer)) > 0) {

            myOutput.write(buffer, 0, length);

        }


        // Close the streams

        myOutput.flush();

        myOutput.close();

        myInput.close();


    }

    private static String getDatabasePath() {

        return ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX

                + DATABASE_NAME;

    }


    public SQLiteDatabase openDataBase() throws SQLException {

        File dbFile = ctx.getDatabasePath(DATABASE_NAME);


        if (!dbFile.exists()) {

            try {

                CopyDataBaseFromAsset();

                System.out.println("Copying sucess from Assets folder");

            } catch (IOException e) {

                throw new RuntimeException("Error creating source database", e);
            }

        }


        return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);

    }

    @Override

    public void onCreate(SQLiteDatabase db) {

    }

    @Override

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

        // TODO Auto-generated method stub


    }


    //add your public methods for insert, get, delete and update data in database.
    public ArrayList<AppInfo> getAppsInfo() {
        ArrayList<AppInfo> appInfos = new ArrayList<AppInfo>();
        String selectQuery;
        Cursor cursor;
        // Select All Query
        selectQuery = "SELECT  * FROM appinfo";
        SQLiteDatabase db = this.getReadableDatabase();
        cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                AppInfo appInfo = new AppInfo(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
                appInfos.add(appInfo);
            } while (cursor.moveToNext());

        }
        return appInfos;
    }
}

这是使用您的字段更改 sqlite 文件名和表名的示例代码。

关于android - 如何使用带有 Activity android的现成sql数据库启动应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099911/

相关文章:

java - 类(class)倒数计时器不会重置

android - GLSurfaceView.onPause() 会破坏上下文吗?

perl - 错误消息:无法对未定义的值调用方法“做”

javascript - Firefox 扩展的 "Extension Storage"的数据存储在哪里?

android - 配置更改后或启动这些操作的 Activity 被破坏后,SQLite CRUD 操作的预期行为是什么?

android camera2 qrscanner 二维码扫描器

java - 为什么我在使用 Retrofit2 时得到 "Type okhttp3.Call does not have type parameters"?

android - 如何使用 Android android.provider.MediaStore.ACTION_IMAGE_CAPTURE 拍摄多张照片?

android - 错误: Gradle DSL method not found: compile()

java - AutoFitTextureView 无法解析 Android Studio 中的符号