有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java希望从安卓应用程序小部件写入文件,但从小部件访问FileInputStream时为空

我目前正在为我的应用程序创建一个小部件。在我的应用程序中,我有一个load函数,它从文本文件中写入所有以前的数据,以创建一个对象,该对象可以记住用户以前使用时保存的日期。当在应用程序打开时调用此加载函数时,它将按预期工作。但是,当从小部件调用load函数时,FileInputStream为null。从我的小部件加载时,是否需要采取任何预防措施

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());
}

共 (0) 个答案