java - 想要从 android 应用程序小部件写入文件,但从小部件访问时 FileInputStream 为空
问题描述
我目前正在为我的应用程序创建一个小部件。在我的应用程序中,我有一个加载函数,它从文本文件中写入所有以前的数据,以创建一个对象,该对象记住用户以前使用的保存日期。当应用程序打开时调用此加载函数时,它会按预期工作。但是,当从小部件调用加载函数时,FileInputStream 为空。从我的小部件加载我必须采取任何预防措施吗?
private void load()
{
String fileName = "locationstorage.txt";
FileInputStream fis = null;
try
{
fis = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
StringTokenizer nl = new StringTokenizer(sb.toString(), "\n");
StringTokenizer colon;
double lng, lat;
String lbl;
String dateInString;
Location lo;
LocationListItem tmp;
Date curDt;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
while(nl.hasMoreTokens())
{
//long lat label
colon = new StringTokenizer(nl.nextToken(), "%");
lng = Double.valueOf(colon.nextToken());
lat = Double.valueOf(colon.nextToken());
lbl = colon.nextToken();
dateInString = colon.nextToken();
//curDt = formatter.parse(dateInString);
lo = new Location("");
lo.setLongitude(lng);
lo.setLatitude(lat);
tmp = new LocationListItem(lo, lbl, dateInString);
locList.add(tmp);
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally
{
if (fis != null) {
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
这是通过单击我的小部件调用的函数:
public void widgetSaveLocation()
{
if(locList == null)
{
locList = new ArrayList<LocationListItem>();
load(0);
}
Location location;
location = new Location("");
location.setLatitude(0);
location.setLongitude(0);
label = "test";
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
LocationListItem newItem = new LocationListItem(location, label, formatter.format(date));
locList.add(newItem);
saveTextAsFile(listToString());
}
解决方案
推荐阅读
- opengl - 计算着色器中与体素世界的粒子碰撞
- visual-studio - 即使 check_ipo_supported() 在 CMake 中工作,也未设置 INTERPROCEDURAL_OPTIMIZATION
- arrays - 为什么 val 不影响 KOTLIN 中的数组?
- java - 如何通过文本查找元素,忽略使用 Selenium 和 Xpath 的大小写
- r - 根据其他数据表列替换列的值
- splunk - 在 Splunk 中划分两个时间表
- python - 使用 zip() 迭代包含 4 个以上项目的元组的良好风格
- r - 如果所有值都是 NA,则计算总和或返回 NA 的有效方法
- c# - 如何在 AutoFac 中注册配置文件 AutoMapper?
- javascript - 如何从 Angular 组件中获取环境作为“库”?