当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Sqlite-No such table error

问题描述:

I have created my database with Sqlite database browser and put it in my assets folder, but when i use the call() method it gives me the error:

No Such Table DailyWorks

here is the on create code

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

}

And the DBAdapter class is:

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

}

}

网友答案:

Before accessing your database from assets folder you have to copy your database to your device's package memory. because your application will access databse from your package only. sample code:

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

For full code example please reffer here.

I hope this will help you.

分享给朋友:
您可能感兴趣的文章:
随机阅读: