我已经编写了这段代码来使用 android 中的现有数据库。
我所拥有的是:
- 数据库:测试
- 表:t1
我已将数据库保存在asset
文件夹中,如果我运行我的项目,它会给我force-close
错误。
我哪里错了?
public class BDAdapter extends SQLiteOpenHelper {
private Context mycontext;
int id=0;
private String DB_PATH = "data/data/com.example.dd9/databases/";
private static String DB_NAME = "test.sqlite";
// public static final String KEY_ROWID = "_id";
public static final String KEY_QUOTE = "name";
private static final String DATABASE_TABLE = "t1";
private static final String TAG = "BDAdapter";
private static final String DATABASE_CREATE =
"create table t1 ( "
+ "name text not null );";
private SQLiteDatabase db;
public BDAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.mycontext = context;
boolean dbexist = checkdatabase();
if (dbexist) {
} else {
System.out.println("Database doesn't exist");
try {
createdatabase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if (dbexist) {
} else {
this.getReadableDatabase();
try {
copydatabase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkdatabase() {
boolean checkdb = false;
try {
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
checkdb = dbfile.exists();
} catch (SQLiteException e) {
System.out.println("Database doesn't exist");
}
return checkdb;
}
private void copydatabase() throws IOException {
// Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
@SuppressWarnings("unused")
String outfilename = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream(
"data/data/com.example.dd9/databases/test.sqlite");
// transfer byte to inputfile to 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();
}
public void open() {
// Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null,
SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close() {
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS t1");
onCreate(db);
}
public long insertQuote(String Quote)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_QUOTE, Quote);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public int getAllEntries()
{
Cursor cursor = db.rawQuery(
"SELECT COUNT(name) FROM t1", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
public String getRandomEntry()
{
id = getAllEntries();
Random random = new Random();
int rand = random.nextInt(getAllEntries());
if(rand == 0)
++rand;
Cursor cursor = db.rawQuery(
"SELECT name FROM t1 ", null);
//"SELECT * FROM tblRandomQuotes",null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
}
return cursor.getString(0);
}
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_QUOTE,
},
null,
null,
null,
null,
null);
}
}
//---------------------------Main class------------------------
public class MainActivity extends Activity
{
BDAdapter db = new BDAdapter(this);
EditText name;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Capture our button from layout
Button setButton = (Button)findViewById(R.id.go);
Button getButton = (Button)findViewById(R.id.genRan);
// Register the onClick listener with the implementation above
setButton.setOnClickListener(mAddListener);
getButton.setOnClickListener(mAddListener);
}
// Create an anonymous implementation of OnClickListener
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v)
{
switch(v.getId())
{
case R.id.go:
db.open();
long id = 0;
// do something when the button is clicked
try
{
name = (EditText)findViewById(R.id.Quote);
db.insertQuote(name.getText().toString());
id = db.getAllEntries();
Context context = getApplicationContext();
CharSequence text = "The quote '" + name.getText() + "' was added successfully!\nQuotes Total = " + id;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
name.setText("");
}
catch (Exception ex)
{
Context context = getApplicationContext();
CharSequence text = ex.toString() + "ID = " + id;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
db.close();
break;
case R.id.genRan:
db.open();
//long id1 = 0;
// do something when the button is clicked
try
{
//String quote = "";
//quote = db.getRandomEntry();
//Context context = getApplicationContext();
//CharSequence text = quote;
//int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
db.open();
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db.close();
}
catch (Exception ex)
{
Context context = getApplicationContext();
CharSequence text = ex.toString();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
db.close();
}
}
};
public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"NAME: " + c.getString(0) + "\n" ,
Toast.LENGTH_LONG).show();
}
}