简体   繁体   English

通过Access SQLite在资产文件夹中显示数据

[英]Display data by Access SQLite in the asset folder

I need help to retrieve data from the database in the asset folder by using getter and setter. 我需要帮助,可以使用getter和setter从资产文件夹中的数据库检索数据。 I dont have any idea on how to retrieve the data since im new to android. 自从我是android新手以来,我对如何检索数据一无所知。 What will be the code to be add to retrieve data in the database. 将添加什么代码以检索数据库中的数据。

public class DatabaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.example.user.displayname/databases/";
    private static String DB_NAME = "displayname";
    private SQLiteDatabase myDataBase;
    private Context myContext = null;


    public DatabaseHelper(Context context) {
        super(context, DB_NAME, (SQLiteDatabase.CursorFactory) null, 1);
        this.myContext = context;
    }

    public void createDataBase() throws IOException {
        boolean dbExist = this.checkDataBase();
        if(!dbExist) {
            this.getReadableDatabase();

            try {
                this.copyDataBase();
            } catch (IOException e) {
                throw new Error("Error");
            }
        }
    }

    public void copyDataBase() throws IOException {
        InputStream myInput = this.myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        FileOutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];

        int length;
        while((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public boolean checkDataBase() {
        SQLiteDatabase checkDB = null;

        try {
            String e = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(e, (SQLiteDatabase.CursorFactory)null, 0);
        } catch (SQLiteException e) {
            ;
        }

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

        return checkDB != null;
    }

    public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        this.myDataBase = SQLiteDatabase.openDatabase(myPath, (SQLiteDatabase.CursorFactory)null, 0);
    }

    public synchronized void close() {
        if(this.myDataBase != null) {
            this.myDataBase.close();
        }

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    public void createDatabase() {
    }
}

Please check below code which is work for me: 请检查以下对我有用的代码:

private static String DB_NAME ="Your_Db_Name";// Database name 私有静态字符串DB_NAME =“ Your_Db_Name”; //数据库名称

DB_NAME here is the name of your database. DB_NAME此处是您的数据库的名称。 And you have a copy of the database in the assets folder, so for example if your database name is todoExample, then the value of DB_NAME will be todoExample, 并且在assets文件夹中有一个数据库副本,因此,例如,如果您的数据库名称是todoExample,则DB_NAME的值将是todoExample,

private static String DB_NAME ="todoExample"; 私有静态字符串DB_NAME =“ todoExample”;

DataHelper.java DataHelper.java

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

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper"; 
private static String DB_PATH = ""; 
private static String DB_NAME ="todoExample";// Database name
private SQLiteDatabase mDataBase; 
private final Context mContext;

public DataBaseHelper(Context context) 
{
    super(context, DB_NAME, null, 1);
    if(android.os.Build.VERSION.SDK_INT >= 17){
       DB_PATH = context.getApplicationInfo().dataDir + "/databases/";         
    }
    else
    {
       DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    }
    this.mContext = context;
}   

public void createDataBase() throws IOException
{
    boolean mDataBaseExist = checkDataBase();
    if(!mDataBaseExist)
    {
        this.getReadableDatabase();
        this.close();
        try 
        {
            //Copy the database from assests
            copyDataBase();
            Log.e(TAG, "createDatabase database created");
        } 
        catch (IOException mIOException) 
        {
            throw new Error("ErrorCopyingDataBase");
        }
    }
}
    //Check that the database exists here: /data/data/your package/databases/Da Name
    private boolean checkDataBase()
    {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    //Copy the database from assets
    private void copyDataBase() throws IOException
    {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer))>0)
        {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    //Open the database, so we can query it
    public boolean openDataBase() throws SQLException
    {
        String mPath = DB_PATH + DB_NAME;
        //Log.v("mPath", mPath);
        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        return mDataBase != null;
    }

    @Override
    public synchronized void close() 
    {
        if(mDataBase != null)
            mDataBase.close();
        super.close();
    }
}

DataAdapter.java 数据适配器

import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DataAdapter 
{
    protected static final String TAG = "DataAdapter";

    private final Context mContext;
    private SQLiteDatabase mDb;
    private DataBaseHelper mDbHelper;

    public DataAdapter(Context context) 
    {
        this.mContext = context;
        mDbHelper = new DataBaseHelper(mContext);
    }

    public DataAdapter createDatabase() throws SQLException 
    {
        try 
        {
            mDbHelper.createDataBase();
        } 
        catch (IOException mIOException) 
        {
            Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
            throw new Error("UnableToCreateDatabase");
        }
        return this;
    }

    public DataAdapter open() throws SQLException 
    {
        try 
        {
            mDbHelper.openDataBase();
            mDbHelper.close();
            mDb = mDbHelper.getReadableDatabase();
        } 
        catch (SQLException mSQLException) 
        {
            Log.e(TAG, "open >>"+ mSQLException.toString());
            throw mSQLException;
        }
        return this;
    }

    public void close() 
    {
        mDbHelper.close();
    }

     public Cursor getTodoData()
     {
         try
         {
             String sql ="SELECT * FROM list";

             Cursor mCur = mDb.rawQuery(sql, null);
             if (mCur!=null)
             {
                mCur.moveToNext();
             }
             return mCur;
         }
         catch (SQLException mSQLException) 
         {
             Log.e(TAG, "getTestData >>"+ mSQLException.toString());
             throw mSQLException;
         }
     }
}

Todo.java Todo.java

package com.example.todo;

public class Todo {

    private String name;
    private String note;

    public Todo() {
    }

    public Todo(String name, String note) {
        this.name = name;
        this.note = note;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

}

Now you can use it like: 现在您可以像这样使用它:

List<Todo> todoItem = new ArrayList<Todo>();
DataAdapter mDbHelper = new DataAdapter(urContext);        
mDbHelper.createDatabase();      
mDbHelper.open();

Cursor cursor = mDbHelper.getTodoData();
if (cursor.moveToFirst()) {
            do {
                Todo todo = new Todo();
                todo.setName(cursor.getString(1));
                todo.setNote(cursor.getString(2));

                todoItem.add(todo);

            } while (cursor.moveToNext());
}

mDbHelper.close();

You can not write to files in Assets direcotry. 您无法在“资产”目录中写入文件。 The database is frequently save here: 该数据库经常保存在这里:

string dbPath = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "Database.db3");

And loading can be done for example (C# xamarin) 例如,可以完成加载(C#xamarin)

public static List<Cars> GetCars(int id, ref string logText)
{
  List<Cars> ret = null;
  string dbPath = EVODatabase.GetDBPath();
  try
  {
    using (SQLiteConnection conn = new SQLiteConnection(dbPath))
    {
      object[] param = new object[0];
      SQLiteCommand cmd = conn.CreateCommand("select * from Cars where id = " + id, param);
      ret = cmd.ExecuteQuery<Cars>();
    }
  }
  catch (Exception ex)
  {
    logText += "\n" + ex.Message + "\n" + ex.StackTrace + "\n" + ex.InnerException;
  }
  return ret;
}

You can do this way: 您可以这样做:

DBAdapter.java : DBAdapter.java

Here you have to change two lines: 在这里,您必须更改两行:

public static final String DATABASE_NAME = "my_db_title";
public final static String DATABASE_PATH = "/data/data/my_package_name_here/databases/";

DBAdapter Class : DBAdapter

public class DBAdapter extends SQLiteOpenHelper {
    private SQLiteDatabase myDataBase;
    private final Context myContext;
    public static final String DATABASE_NAME = "my_db_title";
    public final static String DATABASE_PATH = "/data/data/my_package_name_here/databases/";
    public static final int DATABASE_VERSION = 1;

    // public static final int DATABASE_VERSION_old = 1;

    // Constructor
    public DBAdapter(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }

    // Create a empty database on the system
    public void createDatabase(Context ctx) throws IOException {
        boolean dbExist1 = checkDataBase();
        if (!dbExist1) {
            this.getReadableDatabase();
            try {
                this.close();
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    // Check database already exist or not
    private boolean checkDataBase() {
        boolean checkDB = false;
        try {
            String myPath = DATABASE_PATH + DATABASE_NAME;
            File dbfile = new File(myPath);
            checkDB = dbfile.exists();
        } catch (SQLiteException e) {
        }
        return checkDB;
    }

    // Copies your database from your local assets-folder to the just created
    // empty database in the system folder
    private void copyDataBase() throws IOException {
        String outFileName = DATABASE_PATH + DATABASE_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myInput.close();
        myOutput.flush();
        myOutput.close();
    }

    // delete database
    public void db_delete() {
        File file = new File(DATABASE_PATH + DATABASE_NAME);
        if (file.exists()) {
            file.delete();
            System.out.println("delete database file.");
        }
    }

    // Open database
    public void o() throws SQLException {
        String myPath = DATABASE_PATH + DATABASE_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    public synchronized void c() throws SQLException {
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }

    public void onCreate(SQLiteDatabase db) {
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion) {
            Log.v("Database Upgrade", "Database version higher than old.");
            db_delete();
        }
    }

    // Other stuff
}

In Activity or Fragment : 活动片段中

private DBAdapter mDbAdapter;

On onCreate() : onCreate()上

mDbAdapter = new DBAdapter(mContext);
    try {
        mDbAdapter.createDatabase(mContext);
    } catch (IOException e) {
        e.printStackTrace();
    }

Done 完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM