本帖最后由 潘天功 于 2013-3-17 21:41 编辑
- package com.itheima.note.db.dao;
- import java.util.ArrayList;
- import java.util.List;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import com.itheima.note.db.NoteSQLiteOpenHelper;
- import com.itheima.note.domain.NoteBean;
- //对数据库进行增删改查操作
- public class NoteDao {
- //因为任何一个操作都需要得到NoteSQLiteOpenHelper hepler,所以把它放在构造方法中初始化
- private NoteSQLiteOpenHelper helper;
- public NoteDao(Context context){
- helper = new NoteSQLiteOpenHelper(context);
- }
- //添加一条账目信息到数据库
- public void add(String name,float money){
- SQLiteDatabase db = helper.getWritableDatabase();
- db.execSQL("insert into account (name,money) values (?,?)", new Object[]{name,money});
- db.close();
- }
- //从数据库删除一条信息
- public void delete(int id){
- SQLiteDatabase db = helper.getWritableDatabase();
- db.execSQL("delete from account where id=?", new Object[]{id});
- db.close();
- }
- //修改数据库信息
- public void update(int id,float newmoney){
- SQLiteDatabase db = helper.getWritableDatabase();
- db.execSQL("update account set money =? where id =?", new Object[]{newmoney,id});
- db.close();
- }
- //查询数据库所有信息
- public List<NoteBean>findAll(){
- SQLiteDatabase db = helper.getWritableDatabase();
- List<NoteBean> list = new ArrayList<NoteBean>();
- //获取数据库查询的结果游标
- Cursor cursor = db.rawQuery("select id,money,name from account ", null);
- while(cursor.moveToNext()){
- int id = cursor.getInt(cursor.getColumnIndex("id"));
- String name = cursor.getString(cursor.getColumnIndex("name"));
- float money = cursor.getFloat(cursor.getColumnIndex("money"));
- NoteBean bean = new NoteBean(id, name, money);
- list.add(bean);
- bean = null;
- }
- db.close();
- return list;
-
- }
- }
- 这段代码 用以下测试类测试总是报空指针异常
- <div class="blockcode"><blockquote>package com.itheima.note.test;
- import com.itheima.note.db.dao.NoteDao;
- import android.test.AndroidTestCase;
- //对数据库操作进行测试
- public class TestNoteDao extends AndroidTestCase {
- NoteDao dao = new NoteDao(getContext());
- public void testAdd()throws Exception{
- for(int i=0;i<10;i++){
- dao.add("我是你"+i+"大爷", i);
- }
- }
- }
复制代码 |
|