【发布时间】:2011-11-23 01:42:23
【问题描述】:
首先我创建了一个表,它工作。第二个我以同样的方式做,仍然给出错误:没有这样的表 my_contacts。
所以这是代码:
[在主要活动中]
DBOperations.insert(this, TABLE_MY_CONTACTS, fields, vals);
DBOperations 类如下所示:
public class DBOperations implements Tables {
// inserting 1 contact into a table
public static boolean insert (Context context, String table, ArrayList <String> fields, ArrayList <String> vals) {
if (fields.size() != vals.size())
return false;
MySQLite_methods mysql = new MySQLite_methods (context, table); // creates the table!!!!!!!!!
ContentValues values = new ContentValues();
for (int i=0; i<fields.size(); i++)
values.put(fields.get(i), vals.get(i));
// checking if the card for that ulink already existed (if so, overwrite)
String[] COLUMNS = {ULINK};
SQLiteDatabase dbr = mysql.getReadableDatabase();
Cursor cursor = dbr.query(table, COLUMNS, null, null, null, null, null);
SQLiteDatabase dbw = mysql.getWritableDatabase();
if (cursor == null || cursor.moveToFirst() == false)
dbw.insertOrThrow(table, null, values);
else
if (cursor.moveToFirst()) {
String value_ulink = cursor.getString(0);
Log.d("geo", "val="+value_ulink);
dbw.update(table, values, ULINK+"='"+value_ulink+"'", null);
}
return true;
}
// ....
}
MySQLite_methods 类扩展了 SQLiteOpenHelper,如下所示:
公共类 MySQLite_methods 扩展 SQLiteOpenHelper 实现表 {
private static final String DATABASE_NAME = "my_database.db" ;
private static final int DATABASE_VERSION = 1;
private String TABLE_NAME;
/** Create a helper object for the Events database */
public MySQLite_methods (Context ctx, String table_name)
{
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.TABLE_NAME = table_name;
}
@Override
public void onCreate(SQLiteDatabase db)
{
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
" (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NAME + " TEXT NOT NULL," +
PHONE + " TEXT NOT NULL,"+
EMAIL + " TEXT NOT NULL,"+
FACEBOOK + " TEXT,"+
WEBSITE + " TEXT,"+
MAJOR + " TEXT NOT NULL,"+
ULINK + " TEXT NOT NULL" + ");" ;
Log.d("geo", sql);
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
最后界面 Tables 是这样的:
public interface Tables extends BaseColumns {
/*
* From the BaseColumns interface we inherit the constants:
* _ID - The unique ID for a row.
* _COUNT - The count of rows in a directory.
*/
//tables name
public static final String TABLE_MY_CARD= "my_card" ;
public static final String TABLE_MY_CONTACTS = "my_contacts" ;
// Columns
public static final String NAME = "name" ;
public static final String PHONE = "phone" ;
public static final String EMAIL = "email";
public static final String FACEBOOK = "facebook";
public static final String WEBSITE = "web";
public static final String MAJOR = "major";
public static final String ULINK = "ulink";
}
使用相同的步骤,我创建了另一个成功的表。但是这个我根本无法创建!
【问题讨论】:
-
为什么要动态创建表格?试试这个教程:devx.com/wireless/Article/40842