在 Weather App 中保存应用程序数据

Save app data in Weather App

我正在开发一个天气应用程序,所以我必须从某些 API 获取图标(如云)和其他信息。在这里,我使用 OpenWeatherMap API。 (这部分很简单)

但问题是,如果没有网络,那我要如何显示之前的数据呢?

它可能会从 phone 中的某个来源检索图标和数据,可能是 sqlite 数据库,或者 JsonStore or DictStore 或任何其他有效的方式,如果可能。

在 sqlite 中存储 image/icon 真的很痛苦,而且每次刷新应用程序时我都必须不断更改图标。(因此从数据库存储和检索不是一个好主意。)

我不知道如何在 JsonStore/DictStore 中保存 icons/images。 (可能是 base64)

也找到了 this link 但帮助不大。

欢迎任何建议或示例。

在这种情况下,我真的会考虑使用托管数据库,并结合使用 Picasso(图像缓存),因此一旦从数据库接收到图标,它就会被缓存并再次使用。也可以使用 Sqlite,但是存储图标会非常痛苦,因为您必须使用效率不高的 blob

虽然我没有尝试过,但我认为您可以按照以下步骤来实现。 由于您正在使用 OpenWeatherMap API,所以我假设您已经实现了一个名为 getImage(String code) 的方法,它将 return byte[] 中的图标(如示例 here 中所述).

  1. 第1步:调用getImage后(当应用程序可以访问互联网时),将byte[]写入internal/external存储中的文件并命名它与 WeatherId 相同或为文件指定一些唯一的名称。您可以参考 link 以能够写入 internal/external 存储。
  2. 第2步:将你希望在设备离线时能够获取的所有天气信息写入一个sqlite数据库。在图标栏中,只需输入您在步骤 1 中创建的文件的名称。
  3. 第三步:离线状态下,想获取天气信息,从sqlite DB中读取数据,从天气记录中获取图标文件名,读取文件content 获取图标作为 byte[] 并用它来显示图标。

我自己想出来的。这个答案供以后参考。 我所做的是,将我从 API( 已经是 JSON 格式 )获得的所有数据保存到 json 文件中。

写入文件weather.json

import json
from urllib import urlopen

url = urlopen('http://api.openweathermap.org/data/2.5/forecast/daily?q={}&mode=json&units={}'.format(getname,temp_type)).read()
#where getname is the name of city.
#and temp_type is either C(Celsius) or F(Fahrenheit)
result = json.loads(url)
out_file = open("weather.json","w")
json.dump(result,self.out_file, indent=4)
#indent = 4, just to make it easy to read.
out_file.close()

并从文件中读取 weather.json

in_file = open("weather.json", "r")
result = json.load(self.in_file)
in_file.close()

对于图标,我使用 requests 模块并用唯一名称保存每个图标,然后每次用户进行新搜索或刷新应用程序时,文件都会自动更新,新图标也会自动更新下载并替换为现有的。

import requests
conditions_image1 = "http://openweathermap.org/img/w/{}.png".format(result['list'][1]['weather'][0]['icon'])
#or whatever be the name of your image
response1 = requests.get(conditions_image1)
if response1.status_code == 200:
    f = open("./icons/wc1.png", 'wb')
    f.write(response1.content)
    f.close()

而且因为我正在使用 kivy,所以我想提一下您需要在 buildozer.spec 文件中添加 json(因为您可能已经在您的 PC 上尝试过第一)

source.include_exts = py,png,jpg,kv,atlas,json