pietomb
pietomb

Reputation: 27

Android SQLite storing lat and long as 0

I'm attempting to store a location in latitude and longitude in an SQLite database for an android app. I'm able to store the name of the location, the location's address, a SSID and password, but the latitude and longitude seem to be always stored as 0.

I know it's attempting to write the values to the database correctly, but something isn't right between that stage and retrieving them.

This is the definition of my table, I'm using REAL datatype to sore the lat and long - is this correct?

private static final String DATABASE_CREATE = "create table "
        + INFO_TABLE + " (" + COLUMN_NAME + " TEXT PRIMARY KEY NOT NULL, "
        + COLUMN_ADDRESS + " TEXT, "
        + COLUMN_LAT + " REAL, "
        + COLUMN_LONG + " REAL, "
        + COLUMN_SSID + " TEXT, "
        + COLUMN_PASSWORD + " TEXT);";

And the section entering the data, at this point "values" is a list which contains the correct lat and long:

public Info enterInfo(String name, String address, double lat, double lng, String ssid, String password){
    ContentValues values = new ContentValues();
    values.put(SQLiteHelper.COLUMN_NAME, name);
    values.put(SQLiteHelper.COLUMN_ADDRESS, address);
    values.put(SQLiteHelper.COLUMN_LAT, lat);
    values.put(SQLiteHelper.COLUMN_LONG, lng);
    values.put(SQLiteHelper.COLUMN_SSID, ssid);
    values.put(SQLiteHelper.COLUMN_PASSWORD, password);

    long insertId = database.insert(SQLiteHelper.INFO_TABLE, null, values);
}

And finally this is where the list is created by reading from the database, here the values are 0:

public List<Info> getAllInfo(){
    List<Info> infos = new ArrayList<Info>();

    Cursor cursor = database.query(SQLiteHelper.INFO_TABLE, allColumns, null,null,null,null,null);

    cursor.moveToFirst();
    while(!cursor.isAfterLast()){
        Info info = cursorToInfo(cursor);
        infos.add(info);
        cursor.moveToNext();
    }
    //Close the cursor
    cursor.close();
    return infos;
}

Not sure if perhaps it's due to the while(!cursor.isAfterLast()) possibly coming out of the loop to early? Or the toString in cursorToInfo? The code for cursorToInfo(cursor) is:

private Info cursorToInfo(Cursor cursor){
    Info info = new Info();
    info.setName(cursor.getString(0));
    return info;
}

Upvotes: 1

Views: 464

Answers (1)

laalto
laalto

Reputation: 152867

Your cursorToInfo() is only retrieving the first column value, discarding any other possible columns in the cursor. Java object fields are default-initialized to zeros/nulls so that explains why the fields you don't explicitly set come out as zeros.

Upvotes: 2

Related Questions