Question

I am trying to get the data by SQLite.In my customized SimpleCursorAdapter I wrote the following bindView method.

 @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);
             }

In MainActivity class, onCreate method like this:

@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 method:

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);


      }

I wrote also the ContentProvider class and DBHelper class. ToDoListProvider Class:

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;
}

When I run the application, ToDo task, priority, and the date comes to the ListView but when I want to get the status column I gives me the following error:

       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 can be the reason for this error?I searched on the internet, bu couldn't found any helpful solution. Any help would be appreciated.

Was it helpful?

Solution

Since you have implemented the LoaderManager.LoaderCallbacks, you want to make sure that you always update the the projections array with any columns that you update, which is usually used to create your CursorLoader. Same goes for any query that you need to make which will makes use of the extra column.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top