在Android中加载文件

时间:2013-12-06 21:33:09

标签: android file-io

我有一个类(只是一个普通类),它包含我的应用程序使用的列表。这些列表从Web刷新并作为XML文件存储在本地。获取列表的代码如下所示:

private static List<String> list1;
public static List<String> getList1() {
    if (list1 == null) {

        //load it
        try {
            FileInputStream fis = openFileInput(FILE_NAME);
            //do stuff with the file here...
        } catch (FileNotFoundException e) {
            //if the file is missing load it from the web
        }

    }

    return list1;
}

所以这个方法会返回列表对象,如果它不存在则会从本地文件加载它,如果不存在则会从Web加载它。但我遇到的问题是openFileInput()在我的类中没有解决,因为它只是一个普通的类,需要从Context调用。做这个的最好方式是什么?使用Context作为getList1()的参数?但是,由于它被各种各样的类别调用,所以无处可去......

1 个答案:

答案 0 :(得分:0)

我使用新课程App解决了这个问题:

public class App extends Application {
    public static Context context;

    @Override 
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }
}

并添加android:name="path.to.App" Android清单。这样,您将始终拥有全局上下文,并且可以在任何地方使用它。