我的Android应用程序正确创建了一个包含单个表的数据库,但是当调用一个方法将另一行插入表中时,它会失败并且不会返回任何错误。
我的目标是让方法addOffice()
向我的SQLite数据库表Offices
添加一行,然后使用方法ifExists()
检查是否存在任何行。
(为了便于阅读,我只提供了相关代码。)
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getSimpleName();
TextView testText = null;
DBHelper dbHelper = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testText = (TextView) findViewById(R.id.testText);
dbHelper = new DBHelper(this, null, null, 1);
// Creates a new Office object, setting items _id, name, and acro.
Office office = new Office(1, "testOffice", "TEST");
dbHelper.addOffice(office);
testText.setText(String.valueOf(dbHelper.ifExists("Offices")));
}
DBHelper.java:
public class DBHelper extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String TAG = SQLiteOpenHelper.class.getSimpleName();
public static final String DATABASE_NAME = "emergency.db";
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
query = "CREATE TABLE Offices( " +
"_id INTEGER PRIMARY_KEY, " +
"acro TEXT, " +
"name TEXT);";
db.execSQL(query);
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Contacts;");
db.execSQL("DROP TABLE IF EXISTS Offices;");
onCreate(db);
}
public void addOffice (Office office){
ContentValues values = new ContentValues();
values.put("_id", office.get_id());
values.put("acro", office.get_acro());
values.put("name", office.get_name());
SQLiteDatabase db = getWritableDatabase();
db.insert("Offices", null, values);
db.close();
}
public boolean ifExists (String tableName) {
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT * FROM " + tableName;
Cursor c = db.rawQuery(query, null);
if(c.getCount() <= 0){
c.close();
return false;
}
c.close();
return true;
}
public String dbToString() {
String result = "default";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM Offices";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_id")) != null) {
result += c.getString((c.getColumnIndex("_id"))) + "\n";
} else {
result += "_id was NULL";
}
}
c.close();
db.close();
return result;
}
}
到目前为止,ifExists()
一直将false
返回testText
,当使用dbToString()
直接从表中返回数据时,只返回"default"
我知道这应该相对简单,但是我已经坚持了这个时间比我应该更长。任何帮助表示赞赏。
答案 0 :(得分:0)
为什么要关闭db.close();在所有覆盖方法?你不应该成功。它应该只在onPause()方法中添加。
试试这个网址http://www.vogella.com/tutorials/AndroidSQLite/article.html。这会对你有所帮助。