简体   繁体   中英

Storing new city weather data and updating existing city weather data in Android SQLITE database

I am using OpenWeatherMap API to extract current weather data in JSON format.

The following data is an example:

{"coord":{"lon":-83.05,"lat":42.33},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":48.1,"pressure":1004.19,"humidity":100,"temp_min":48.1,"temp_max":48.1,"sea_level":1028.21,"grnd_level":1004.19},"wind":{"speed":15.23,"deg":315.508},"clouds":{"all":0},"dt":1477154497,"sys":{"message":0.1743,"country":"US","sunrise":1477137281,"sunset":1477175856},"id":4990729,"name":"Detroit","cod":200}
{"coord":{"lon":-87.65,"lat":41.85},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":51.38,"pressure":1009.38,"humidity":100,"temp_min":51.38,"temp_max":51.38,"sea_level":1031.85,"grnd_level":1009.38},"wind":{"speed":8.08,"deg":227.508},"clouds":{"all":48},"dt":1477154834,"sys":{"message":0.1714,"country":"US","sunrise":1477138345,"sunset":1477177000},"id":4887398,"name":"Chicago","cod":200}
{"coord":{"lon":-74.01,"lat":40.71},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"base":"stations","main":{"temp":48.14,"pressure":1008,"humidity":100,"temp_min":48.14,"temp_max":48.14,"sea_level":1011.38,"grnd_level":1008},"wind":{"speed":15.46,"deg":296.508},"rain":{"3h":2.2},"clouds":{"all":80},"dt":1477154848,"sys":{"message":0.1842,"country":"US","sunrise":1477134973,"sunset":1477173827},"id":5128581,"name":"New York","cod":200}

As "dummy entries" that can be removed at any time the user chooses, these three cities are inserted onCreate() (although now I see why that can be a bad idea)

My intention is to have these three dummy records update onCreate() or onResume() without creating new records of themselves which then are added to ListView.

Adding new cities will pull the current weather data and add it to the table, and subsequently updating with live data.

My idea was to check before insertion if the record already exist, and instead of inserting a new entry, it would find and set the temperature and any other pertinent fields to the new data.

But I am quite clueless and how to begin the "check". Here is my insertion method:

 public void insertRow(CustomListData weather){
    SQLiteDatabase db = this.getWritableDatabase();
        ContentValues insertValues = new ContentValues();
        insertValues.put("TEMP", weather.getTemperature());
        insertValues.put("CITYNAME", weather.getCity());
        insertValues.put("ZIP", weather.getZip());
        db.insert("weather_data", null, insertValues);
        db.close();
}

EDIT:

SCHEMA:

CREATE TABLE weather_data(_id INTEGER PRIMARY KEY AUTOINCREMENT, TEMP VARCHAR(5), CITYNAME VARCHAR(255), ZIP VARCHAR(6) );

SECOND EDIT:

WeatherDataStorage -- helper class

If you need to check if the record does exist in the table, the fastest way to do that would be to check this way( Assuming the zip code is unique across all records ) :

     public static boolean checkIfRecordExists(Context context, String tableName, 
                                String tableAttribute, String attributeValue) {

            Cursor cursor = context.getContentResolver().query(tableName,
            new String[]{"1"},
            tableAttribute + "=?,
            new String[]{attributeValue},
            null);

            boolean recordExists = (cursor !=null && cursor.getCount() > 0);
            cursor.close();

            return recordExists;
     }

So you can call this method to check if record exists in your "weather_data" table.

public void insertRow(CustomListData weather){
SQLiteDatabase db = this.getWritableDatabase();

//(Context context, String tableName, String tableAttribute, String attributeValue) 

    boolean recordExists = checkIfRecordExists(context, "weather_data", "ZIP", weather.getZip());

    if(!recordExists) {
        ContentValues insertValues = new ContentValues();
        insertValues.put("TEMP", weather.getTemperature());
        insertValues.put("CITYNAME", weather.getCity());
        insertValues.put("ZIP", weather.getZip());
        db.insert("weather_data", null, insertValues);
        db.close();
    }
}

Try to follow the code carefully. You are trying to check if the record in the table exists with respect to ZIP code.

Hence, when you call the utility method checkIfRecordExists with these params checkIfRecordExists(context, "weather_data", "ZIP", "DUMMY_ZIP_1234"),

The query translates to SELECT 1 FROM weather_data WHERE ZIP = "DUMMY_ZIP_1234"

You run a select query, save the results in a cursor and check if the cursor holds any records. If cursor holds some records, then it means that the record already exists.

PS: if the zip code is unique, please use zip code as the primary key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM