martes, 24 de enero de 2012

Primera Aplicación. Parte 3

Cargando los datos en base de datos.

Para cargar los datos del fichero CSV en base de datos, es necesario añadir este fichero en el proyecto de Eclipse. Para ello es necesario importar este archivo en la carpeta assets del proyecto.

Para ello, hay que seleccionar "File>Import..." en el proyecto actual.

Posteriormente hay que seleccionar "File System":
Selecciono el directorio donde esta almacenado el fichero es-allcam.txt y se importa este fichero a la carpeta assets del proyecto. Una vez incluido este fichero en el proyecto, accedo a él para parsearlo e insertar la información en base de datos. El siguiente código accede al fichero es-allcam.txt, abre un flujo de lectura y parsea los datos fila por fila del fichero insertando los datos como una fila en la tabla de base de datos mediante el método insertRadar
 
 public boolean readCSV(String radarCSVFile) {
  try {
   InputStream is = context.getAssets().open("es-allcam.txt");
   InputStreamReader isr = new InputStreamReader(is);
   BufferedReader in = new BufferedReader(isr);
   in.readLine();
   String reader = "";
   String[] RowData;
   db.beginTransaction();
   while ((reader = in.readLine()) != null) {
    RowData = reader.split(",");
    Log.w(TAG, "Inserting... " + RowData[1] + " " + RowData[0]
      + " " + RowData[2] + " " + RowData[3] + " "
      + RowData[4] + " " + RowData[5] + " " + "...");
    
    insertRadar(RowData[1], RowData[0], RowData[2], RowData[3],
      RowData[4], RowData[5], "");

   }
   db.setTransactionSuccessful();

   db.releaseMemory();
   in.close();
  } catch (Exception e) {
   db.releaseMemory();
   e.printStackTrace();
  } finally {
   db.endTransaction();
  }
  return true;
 }

El método insertRadar luce como se muestra a continuación
 public void insertRadar(String latitude, String longitude,
   String radar_type, String speed, String direction_type,
   String direction, String postal_code) {
  rowSet[0] = latitude;
  rowSet[1] = longitude;
  rowSet[2] = radar_type;
  rowSet[3] = speed;
  rowSet[4] = direction_type;
  rowSet[5] = direction;
  rowSet[6] = postal_code;

  // return db.insert(DATABASE_TABLE, null, initialValues);
  db.execSQL(sqlInsertRadar, rowSet);

 
 }

Implemento unos cuantos métodos para tratar los datos de radar en tablas. El siguiente método actualiza los radars por id de radar en base de datos,

 // ---updates a Radar---
 public boolean updateRadar(long rowId, String latitude, String longitude,
   String radar_type, String speed, String direction_type,
   String direction, String postal_code) {
  Log.v(TAG, "update radar " + rowId);
  ContentValues args = new ContentValues();
  args.put(KEY_LATITUDE, latitude);
  args.put(KEY_LONGITUDE, longitude);
  args.put(KEY_RADARTYPE, radar_type);
  args.put(KEY_SPEED, speed);
  args.put(KEY_DIRECTION_TYPE, direction_type);
  args.put(KEY_DIRECTION, direction);
  args.put(KEY_POSTALCODE, postal_code);
  return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
 }

Este método sirve para recuperar los radares que se encuentren cerca de cierta localización dada por un objeto Location. Este método se utilizará posteriormente para buscar radares en el momento de que se actualice la localización del móvil mediante su localizador GPS.

 public Cursor getRadarsByLocation(Location location) {

  String sConditional = KEY_LATITUDE + " BETWEEN "
    + String.valueOf(location.getLatitude() + 0.001) + " AND "
    + String.valueOf(location.getLatitude() - 0.001) + " AND "
    + KEY_LONGITUDE + " BETWEEN "
    + String.valueOf(location.getLongitude() + 0.001) + " AND "
    + String.valueOf(location.getLongitude() - 0.001);

  Log.v(TAG, sConditional);

  if (location != null) {

   Log.v(TAG, "get radar by location: " + location.getLatitude() + " "
     + location.getLongitude());

   mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
     KEY_LATITUDE, KEY_LONGITUDE, KEY_RADARTYPE, KEY_SPEED,
     KEY_DIRECTION_TYPE, KEY_DIRECTION, KEY_POSTALCODE },
     sConditional, null, null, null, null, null);
  }
  if (mCursor != null) {
   mCursor.moveToFirst();
  }
  return mCursor;

 }

No hay comentarios:

Publicar un comentario