我正在尝试通过SQLite获取数据。在我自定义的SimpleCursorAdapter中,我编写了以下bindView方法。
@Override
public void bindView(View _view, Context context, Cursor cursor) {
//Get the properties of the todo item and create it.
int indexOfTask;
String task = null;
int indexOfDeadline;
Date deadline = null;
int indexOfPriority;
int priority = 0;
int indexOfStatus;
String status = null;
indexOfTask=cursor.getColumnIndexOrThrow(ToDoListProvider.KEY_TASK);
task=cursor.getString(indexOfTask);
indexOfDeadline=cursor.getColumnIndexOrThrow(ToDoListProvider.KEY_DEADLINE);
deadline=new Date(cursor.getLong(indexOfDeadline));
indexOfStatus=cursor.getColumnIndexOrThrow(ToDoListProvider.KEY_STATUS);
status=cursor.getString(indexOfStatus);
indexOfPriority=cursor.getColumnIndexOrThrow(ToDoListProvider.KEY_PRIORITY);
priority=cursor.getInt(indexOfPriority);
TodoItem todo = new TodoItem(task, deadline);
super.bindView(_view, context, cursor);
}
在MainActivity类中,onCreate方法如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_list);
final ListView todoList = (ListView) findViewById(R.id.todoListView);
final Button newTodoButton = (Button) findViewById(R.id.newTodoButton);
todoAdapter = new TodoArrayAdapter(this,
R.layout.todo_list_item, null,
new String[] { ToDoListProvider.KEY_PRIORITY, ToDoListProvider.KEY_DEADLINE, ToDoListProvider.KEY_TASK,ToDoListProvider.KEY_STATUS},
new int[] { R.id.todo_list_item_priority, R.id.todo_list_item_deadline, R.id.todo_list_item_task});
todoList.setAdapter(todoAdapter);
getLoaderManager().initLoader(0, null, this);
newTodoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(TodoListActivity.this,
NewTodoActivity.class);
startActivityForResult(intent, NEW_TODO_REQUEST);
}
});
todoList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(TodoListActivity.this,
EditTodoActivity.class);
intent.putExtra(TODO_ITEM_EXTRA, todoItems.get(position));
intent.putExtra(TODO_ITEM_INDEX_EXTRA, position);
startActivityForResult(intent, EDIT_TODO_REQUEST);
}
});
}
addTodoItem方法:
private void addTodoItem(TodoItem todo) {
todoItems.add(todo);
Collections.sort(todoItems);
todoAdapter.notifyDataSetChanged();
// Add a new student record
ContentValues values = new ContentValues();
values.put(ToDoListProvider.KEY_TASK,
todo.getTask());
values.put(ToDoListProvider.KEY_DEADLINE,
todo.getDeadline().toString());
values.put(ToDoListProvider.KEY_STATUS,
todo.getStatus().toString());
values.put(ToDoListProvider.KEY_PRIORITY,
todo.getPriority());
Uri uri = getContentResolver().insert(
ToDoListProvider.CONTENT_URI, values);
}
我还写了ContentProvider类和DBHelper类。 ToDoListProvider类:
public class ToDoListProvider extends ContentProvider{
public static final Uri CONTENT_URI=Uri.parse("content://com.example.todolistprovider/todolistitems");
public static final String KEY_ID="_id";
public static final String KEY_DEADLINE="deadline";
public static final String KEY_TASK="task";
public static final String KEY_STATUS="status";
public static final String KEY_PRIORITY="priority";
private static class ToDoListDatabaseHelper extends SQLiteOpenHelper{
private static final String TAG="ToDoListProvider";
private static final String DATABASE_NAME="todolist.db";
private static final int DATABASE_VERSION=1;
private static final String TODOLIST_TABLE="todolist";
private static final String DATABASE_CREATE="create table "
+ TODOLIST_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_DEADLINE
+ " DATE, " + KEY_TASK + " TEXT, " + KEY_STATUS
+ " TEXT, " + KEY_PRIORITY + " INTEGER);";
private SQLiteDatabase todolistDB;
public ToDoListDatabaseHelper(Context context,String name,CursorFactory factory,int version){
super(context,name,factory,version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG,"Upgrading database from version "+oldVersion + " to "
+newVersion+", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS "+ TODOLIST_TABLE);
onCreate(db);
}
}
private static final int TODOLISTITEMS=1;
private static final int TODOLISTITEM_ID=2;
private static final UriMatcher uriMatcher;
static {
uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("tr.edu.iyte.arf.ceng389.todolistprovider",
"todolistitems",TODOLISTITEMS);
uriMatcher.addURI("tr.edu.iyte.arf.ceng389.todolistprovider",
"todolistitems/#",TODOLISTITEM_ID);
}
ToDoListDatabaseHelper dbHelper;
@Override
public boolean onCreate() {
Context context=getContext();
dbHelper=new ToDoListDatabaseHelper(context,
ToDoListDatabaseHelper.DATABASE_NAME,null,
ToDoListDatabaseHelper.DATABASE_VERSION);
return true;
}
@Override
public String getType(Uri uri) {
switch(uriMatcher.match(uri)){
case TODOLISTITEMS:
return "vnd.android.cursor.dir/vnd.iyte.todolistitems";
case TODOLISTITEM_ID:
return "vnd.android.cursor.item/vnd.iyte.todolistitem";
default:
throw new IllegalArgumentException("Unsupported URI: "+uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase database=dbHelper.getWritableDatabase();
SQLiteQueryBuilder qb=new SQLiteQueryBuilder();
qb.setTables(ToDoListDatabaseHelper.TODOLIST_TABLE);
// If this is a row query, limit the result set to the passed in row.
switch(uriMatcher.match(uri)){
case TODOLISTITEM_ID:
qb.appendWhere(KEY_ID+ "="+uri.getPathSegments().get(1));
break;
default:
break;
}
// If no sort order is specified, sort by date / time
String orderBy;
if(TextUtils.isEmpty(sortOrder)){
orderBy=KEY_PRIORITY;
}
else{
orderBy=sortOrder;
}
// Apply the query to the underlying database.
Cursor cursor=qb.query(database,projection,selection,selectionArgs,
null,null,orderBy);
// Register the contexts ContentResolver to be notified if
// the cursor result set changes.
cursor.setNotificationUri(getContext().getContentResolver(),uri);
//Return a cursor to the query result.
return cursor;
}
@Override
public Uri insert(Uri _uri, ContentValues values) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
// Insert the new row. The call to database.insert will return the row
// number
// if it is successful.
long rowID = database.insert(ToDoListDatabaseHelper.TODOLIST_TABLE,"todolistitem",values);
// Return a URI to the newly inserted row on success.
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
//throw new SQLException("Failed to insert row into " + _uri);
return _uri;
}
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
int count;
switch (uriMatcher.match(uri)) {
case TODOLISTITEMS:
count = database.delete(ToDoListDatabaseHelper.TODOLIST_TABLE,
where, whereArgs);
break;
case TODOLISTITEM_ID:
String segment = uri.getPathSegments().get(1);
count = database.delete(ToDoListDatabaseHelper.TODOLIST_TABLE,
KEY_ID
+ "="
+ segment
+ (!TextUtils.isEmpty(where) ? " AND (" + where
+ ")" : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
当我运行应用程序时,ToDo任务,优先级和日期来到ListView但是当我想获取状态列时,我给出了以下错误:
12-03 03:16:45.026: E/AndroidRuntime(3679):
java.lang.IllegalArgumentException: column 'status' does not exist
12-03 03:16:45.026: E/AndroidRuntime(3679): at
android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
Waht可能是造成这个错误的原因?我在互联网上搜索,发现没有找到任何有用的解决方案。 任何帮助,将不胜感激。
答案 0 :(得分:0)
由于您已实现LoaderManager.LoaderCallbacks,因此您需要确保始终使用您更新的任何列更新投影数组,这通常用于创建CursorLoader。对于您需要使用额外列的任何查询也是如此。