Android SQLite插入有效,查询无效

前端之家收集整理的这篇文章主要介绍了Android SQLite插入有效,查询无效 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这是我第一次在该网站上发帖,希望这将是一次积极的经历.我有一个Android sqlite / ContentProvider问题,在过去3个小时中,我一直在犹豫不决.以下是ContentProvider代码

  1. public class IncidentProvider extends ContentProvider {
  2. private static final UriMatcher sUriMatcher;
  3. private static final HashMap<String,String> projectionMap;
  4. private static final int INCIDENTS = 1;
  5. public static final String AUTHORITY = "com.test.providers.IncidentsProvider";
  6. public static final String TABLE_NAME = "incidents";
  7. private static class DatabaseHelper extends sqliteOpenHelper {
  8. public DatabaseHelper(Context context) {
  9. super(context,context.getString(R.string.database_name),null,Integer.parseInt(context.getString(R.string.database_version)));
  10. }
  11. @Override
  12. public void onCreate(sqliteDatabase db) {
  13. db.execsql("CREATE TABLE " + TABLE_NAME + " ("
  14. + Incidents.INCIDENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
  15. + Incidents.NAME + " VARCHAR(30),"
  16. + Incidents.CREATE_TIME + " LONG,"
  17. + Incidents.LAST_UPDATE + " LONG,"
  18. + Incidents.IS_ACTIVE + " VARCHAR(30)" + ");");
  19. }
  20. @Override
  21. public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
  22. db.execsql("DROP TABLE IF EXISTS " + TABLE_NAME );
  23. onCreate(db);
  24. }
  25. }
  26. private DatabaseHelper dbHelper;
  27. /**
  28. * Delete a row from the database
  29. */
  30. @Override
  31. public int delete(Uri uri,String where,String[] whereArgs) {
  32. sqliteDatabase db = dbHelper.getWritableDatabase();
  33. int count;
  34. switch(sUriMatcher.match(uri)) {
  35. case INCIDENTS:
  36. count = db.delete(TABLE_NAME,where,whereArgs);
  37. break;
  38. default:
  39. throw new IllegalArgumentException("Unknown URI " + uri);
  40. }
  41. getContext().getContentResolver().notifyChange(uri,null);
  42. db.close();
  43. return count;
  44. }
  45. /**
  46. * Return the content type managed by this ContentProvider
  47. */
  48. @Override
  49. public String getType(Uri uri) {
  50. switch(sUriMatcher.match(uri)) {
  51. case INCIDENTS:
  52. return Incidents.CONTENT_TYPE;
  53. default:
  54. throw new IllegalArgumentException("UNKNOWN URI " + uri);
  55. }
  56. }
  57. /**
  58. * Insert new content into a row in the database
  59. */
  60. @Override
  61. public Uri insert(Uri uri,ContentValues initialValues) {
  62. if(sUriMatcher.match(uri) != INCIDENTS)
  63. throw new IllegalArgumentException("UNKNOWN URI " + uri);
  64. ContentValues values;
  65. if(initialValues != null) {
  66. values = new ContentValues(initialValues);
  67. } else {
  68. values = new ContentValues();
  69. }
  70. sqliteDatabase db = dbHelper.getWritableDatabase();
  71. long rowId = db.insert(TABLE_NAME,Incidents.NAME,values);
  72. if(rowId > 0) {
  73. Uri incidentUri = ContentUris.withAppendedId(Incidents.CONTENT_URI,rowId);
  74. getContext().getContentResolver().notifyChange(incidentUri,null);
  75. db.close();
  76. return incidentUri;
  77. }
  78. db.close();
  79. throw new sqlException("Failed to insert row into " + uri);
  80. }
  81. /**
  82. * Called when creating this ContentProvider
  83. */
  84. @Override
  85. public boolean onCreate() {
  86. dbHelper = new DatabaseHelper(getContext());
  87. return false;
  88. }
  89. /**
  90. * Called when making a query to this content provider
  91. */
  92. @Override
  93. public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder) {
  94. sqliteQueryBuilder qb = new sqliteQueryBuilder();
  95. switch(sUriMatcher.match(uri)) {
  96. case INCIDENTS:
  97. qb.setTables(TABLE_NAME);
  98. qb.setProjectionMap(projectionMap);
  99. break;
  100. default:
  101. throw new IllegalArgumentException("UNKNOWN URI " + uri);
  102. }
  103. sqliteDatabase db = dbHelper.getWritableDatabase();
  104. Cursor c = qb.query(db,projection,selection,selectionArgs,sortOrder);
  105. c.setNotificationUri(getContext().getContentResolver(),uri);
  106. db.close();
  107. return c;
  108. }
  109. /**
  110. * Called when updating a row through this content provider
  111. */
  112. @Override
  113. public int update(Uri uri,ContentValues values,String[] whereArgs) {
  114. sqliteDatabase db = dbHelper.getWritableDatabase();
  115. int count;
  116. switch(sUriMatcher.match(uri)) {
  117. case INCIDENTS:
  118. count = db.update(TABLE_NAME,values,whereArgs);
  119. break;
  120. default:
  121. throw new IllegalArgumentException("UNKNOWN URI " + uri);
  122. }
  123. getContext().getContentResolver().notifyChange(uri,null);
  124. db.close();
  125. return count;
  126. }
  127. static {
  128. sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  129. sUriMatcher.addURI(AUTHORITY,TABLE_NAME,INCIDENTS);
  130. projectionMap = new HashMap<String,String>();
  131. projectionMap.put(Incidents.INCIDENT_ID,Incidents.INCIDENT_ID);
  132. projectionMap.put(Incidents.NAME,Incidents.NAME);
  133. projectionMap.put(Incidents.CREATE_TIME,Incidents.CREATE_TIME);
  134. projectionMap.put(Incidents.LAST_UPDATE,Incidents.LAST_UPDATE);
  135. projectionMap.put(Incidents.IS_ACTIVE,Incidents.IS_ACTIVE);
  136. }

}

我还编写了一个db helper类,以使其易于与ContentProvider进行交互. 2个示例DBHelper方法如下(1用于插入,1用于查询).

  1. /**
  2. * Adds a new incident to the database
  3. **/
  4. public void addNewIncident(ContentResolver contentResolver,Incident incident) {
  5. ContentValues contentValues = new ContentValues();
  6. contentValues.put(Incidents.NAME,incident.getName());
  7. contentValues.put(Incidents.CREATE_TIME,incident.getCreateTime());
  8. contentValues.put(Incidents.LAST_UPDATE,incident.getLastUpdate());
  9. contentValues.put(Incidents.IS_ACTIVE,incident.isActive()?"true":"false");
  10. contentResolver.insert(Incidents.CONTENT_URI,contentValues);
  11. }
  12. /**
  13. * Retrieves all incidents from the database
  14. **/
  15. public ArrayList<Incident> getIncidents(ContentResolver contentResolver) {
  16. Cursor c = contentResolver.query(Incidents.CONTENT_URI,null);
  17. ArrayList<Incident> returnList = new ArrayList<Incident>();
  18. if(c!=null && c.moveToNext()) {
  19. for(int i=0; i<c.getCount(); i++) {
  20. c.moveToPosition(i);
  21. Incident incident = new Incident(c.getString(c.getColumnIndex(Incidents.NAME)));
  22. incident.setCreateTime(c.getLong(c.getColumnIndex(Incidents.CREATE_TIME)));
  23. incident.setLastUpdate(c.getLong(c.getColumnIndex(Incidents.LAST_UPDATE)));
  24. incident.setActive(c.getString(c.getColumnIndex(Incidents.IS_ACTIVE)).equalsIgnoreCase("true"));
  25. returnList.add(incident);
  26. }
  27. c.close();
  28. }
  29. return returnList;
  30. }

好的!所以这是我的问题.我可以毫无问题地插入数据库!如果我通过adb shell查询数据库,则可以看到所有正在插入的记录.当我使用sqliteQueryBuilder或sqliteDatabase.rawQuery或任何其他查询方法进行查询时,返回的游标以-1返回.无论查询单个记录还是查询整个数据库都没有关系.查询仍然返回-1.

有任何想法吗?我错过了一件非常简单的事情吗?

在此先感谢任何愿意帮助沮丧的人的人!

更新:

以下是用于插入(有效)和查询(无效)的示例代码

  1. /**
  2. * Following db insert works
  3. */
  4. IncidentsDB db = IncidentsDB.getInstance();
  5. workingIncident.setLastUpdate(System.currentTimeMillis()); // isActive,and createTime set in constructor
  6. db.addNewIncident(this.getContentResolver(),workingIncident);
  7. /**
  8. * Following db queries do not work,cursor ends up with mCount=-1
  9. */
  10. Cursor c = IncidentsDB.getInstance().getIncidents(this.getContentResolver());
最佳答案
好吧,看来我已经解决了.事实证明,最好使用finalize方法关闭数据库,而不是像上面发布的代码中那样在每个delete,insert,query和update方法中打开和关闭.这是像我一样遇到此问题的人员的代码片段:

  1. // add sqliteDatabase member variable to content provider
  2. private sqliteDatabase db;
  3. /**
  4. * Delete a row from the database
  5. */
  6. @Override
  7. public int delete(Uri uri,String[] whereArgs) {
  8. // use Content Provider's db member variable in the following code block
  9. int count;
  10. switch(sUriMatcher.match(uri)) {
  11. case INCIDENTS:
  12. count = db.delete(TABLE_NAME,null);
  13. return count;
  14. }

然后将以下完成代码添加到您的内容提供商

  1. @Override
  2. protected void finalize() throws Throwable {
  3. super.finalize();
  4. db.close();
  5. }

猜你在找的Android相关文章