[gdal-dev] Editing attributes with ogr causing corrupt shapefile

Tom Jeffery tjeffery at gmail.com
Wed Aug 4 09:27:59 EDT 2010


I'm working with GDAL's Java bindings, and trying to simply add an index
field to a shapefile.  This is working, but the resulting shapefile gets
corrupted somehow, where viewing it in ArcMap causes the message "Warning,
inconsistent extent." and viewing it in ArcCatalog shows all the points in
the shapefile in the very upper left corner of the preview.  (Viewing the
metadata tab in ArcCatalog will crash the program.)

Below is the method where I'm adding the index field... is there anything
I'm missing / obviously wrong here?  Any help would be greatly appreciated!

Thanks,
-Tom Jeffery

	public static void addIndex(File input, String fieldName) throws Exception
{
		ogr.RegisterAll();
		DataSource dataSource = ogr.Open(input.getAbsolutePath(), true);
		
		if (dataSource == null) {
			throw new Exception("Error opening input file while trying to add
index.");
		}
		
		// Shapefiles have a single layer
		Layer layer = dataSource.GetLayer(0);
		
		// Creating an OFTInteger alone didn't seem to do the trick, but setting
the width to 9 created a "Long Integer" 
		// field (as viewed in ESRI)
		FieldDefn newField = new FieldDefn(fieldName, ogr.OFTInteger);
		newField.SetWidth(9);
		int result = layer.CreateField(newField);
		if (result != ogr.OGRERR_NONE)
			throw new Exception("Got OGR error code: " + result + " when trying to
add new field to shapefile.");
		
		for (int i = 0; i < layer.GetFeatureCount(); i++) {
			org.gdal.ogr.Feature feature = layer.GetFeature(i);
			feature.SetField(fieldName, i);
			layer.SetFeature(feature);
			feature.delete();
		}
		// you must call "delete" (or Destroy in c/c++) to properly close / write
the datasource.. 
		layer.delete();
		dataSource.delete();
	}
-- 
View this message in context: http://osgeo-org.1803224.n2.nabble.com/gdal-dev-Editing-attributes-with-ogr-causing-corrupt-shapefile-tp5372483p5372483.html
Sent from the GDAL - Dev mailing list archive at Nabble.com.


More information about the gdal-dev mailing list