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

时间:2015-10-20 06:20:27

标签: android sqlite

我需要帮助才能使用getter和setter从资产文件夹中的数据库中检索数据。我不知道如何检索数据,因为我是新的Android。在数据库中检索数据时要添加的代码是什么。

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() {
    }
}

3 个答案:

答案 0 :(得分:1)

请查看下面对我有用的代码:

private static String DB_NAME =“Your_Db_Name”; //数据库名称

此处的DB_NAME是您的数据库的名称。并且您在assets文件夹中有一个数据库副本,例如,如果您的数据库名称是todoExample,那么DB_NAME的值将为todoExample,

private static String DB_NAME =“todoExample”;

<强> 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

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;
    }

}

现在您可以使用它:

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();

答案 1 :(得分:0)

您无法写入Assets direcotry中的文件。数据库经常保存在这里:

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

可以加载例如(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;
}

答案 2 :(得分:0)

你可以这样做:

<强> DBAdapter.java

您必须更改两行:

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

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
}

活动片段

private DBAdapter mDbAdapter;

onCreate()

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

完成