欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Finalizing a Cursor that has not been deactivated or closed

程序员文章站 2022-04-01 16:09:36
...

Finalizing a Cursor that has not been deactivated or closed

 


先贴出代码:

 

 

public List<UnitInfo> findAllGroup() {
		List<UnitInfo> infos=new ArrayList<UnitInfo>();
		try {
			db = dbManager.openDatabase();
			String sql="SELECT * FROM dict_unit_display";
			System.out.println("-------db---open------:"+db.isOpen());
			cursor=db.query("dict_unit_display", null, null, null, null, null, null);
			System.out.println("---------------cursor--close---:"+cursor.isClosed());
			while (cursor.moveToNext()) {
				UnitInfo unit=new UnitInfo();
				unit.setId(cursor.getLong(cursor.getColumnIndex("ID")));
				unit.setUnitCode(cursor.getString(cursor.getColumnIndex("UNIT_CODE")));
				unit.setUnitName(cursor.getString(cursor.getColumnIndex("UNIT_NAME")));
				unit.setUnitSimpleName(cursor.getString(cursor.getColumnIndex("UNIT_SIMPLE_NAME")));
				unit.setUnitNode(cursor.getString(cursor.getColumnIndex("UNIT_NODE")));
				unit.setUnitFatherNode(cursor.getString(cursor.getColumnIndex("UNIT_NODE_FATHER")));
				System.out.println("----------------------------------");
				System.out.println("-----ID-----:"+ unit.getId());
				System.out.println("-----UNIT_CODE-----:" + unit.getUnitCode());
				System.out.println("-----UNIT_NAME-----:" + unit.getUnitName());
				System.out.println("-----UNIT_SIMPLE_NAME-----:" + unit.getUnitSimpleName());
				System.out.println("-----UNIT_NODE-----:" + unit.getUnitNode());
				System.out.println("-----UNIT_NODE_FATHER-----:" + unit.getUnitFatherNode());
				System.out.println("----------------------------------");
				infos.add(unit);
			}
		} catch (Exception e) {
			System.out.println("------findAllGroup-----数据读取错误");
		} finally {
			DBManager.closeDatabase(db, cursor);
		}
		return infos;
	}
 

代码写的看似没有任何问题,但是由于Cursor的独特性,不得不吐糟下,Cursor取值采用的是先取下标再根据下标去取对应的返回值,这里面就有个问题,如果当前字段在数据库中为 空值 那么通过Cursor  getString()或者getLong()的时候就会出现问题,进而导致一连串的错误。


解决方法就是直接用下标去取值就行了。