0

我已经使用Sqlite 数据库浏览器创建了我的数据库并将其放在我的资产文件夹中,但是当我使用call()方法时,它给了我错误: 没有这样的表 DailyWorks

这是创建代码

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    CopyDatabaseintheEmulatorMemory();  // Copy database in memory of emulator
     call();

}

private void call() 
{
    DBAdapter db = new DBAdapter(this);

     //---get all contacts---
    db.open();

    String sql="select * from DailyWorks";

    Cursor c = db.getAllContacts(sql);

    db.close();     
}

DBAdapter 类是:

public class DBAdapter {

    static final String DATABASE_NAME = "MyDB";
    static final int DATABASE_VERSION = 2;


    final Context context;

    DatabaseHelper DBHelper;
    SQLiteDatabase db;

    public DBAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static  class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {

        }

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

     }

    //---opens the database---
    public DBAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---
    public void close() 
    {
        DBHelper.close();
    }
    //---retrieves all the contacts---
    public Cursor getAllContacts(String sql)
    {
        return db.rawQuery(sql, null);
    }
}
4

1 回答 1

0

在从 assets 文件夹访问数据库之前,您必须将数据库复制到设备的包内存中。因为您的应用程序将仅从您的包中访问数据库。示例代码:

String DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";   
String DB_NAME = "database";
 InputStream myInput = context.getAssets().open(DB_NAME);
      String outFileName = DB_PATH + DB_NAME;
      OutputStream myOutput = new FileOutputStream(outFileName);
      byte[] buffer = new byte[1024];
      int length;
      while ((length = myInput.read(buffer)) > 0) {
       myOutput.write(buffer, 0, length);
      }
于 2013-05-16T12:18:50.453 回答