Eclipse Android配置文件始终返回null

时间:2013-07-15 23:23:22

标签: android eclipse

目前正在通过Eclipse和JUnit为Android创建测试框架。我正在实现的最后一件事是配置文件和阅读器,以便配置文件可用于在必要时更改各种属性。我的框架结构如下:

MainFramework (project)
  Base package
  Utility package
    Config class

Testing (project)
  examples package
    Artist testing class

Config类如下:

public class Config {

private static Config instance;
public Context context;
public static Properties prop;

public static StorefrontConfig getInstance(Context context) {

    if(instance == null)
        instance = new StorefrontConfig(context);
    return instance;
}

protected StorefrontConfig(Context cont) {
    context = cont;
    AssetManager manager = context.getAssets();
    try {
        InputStream instream = manager.open("config");
        readConfig(instream);
    }
    catch (Exception e) {
        Log.d("cool", "Failed to create properly initialized config class");
    }
}

private static void readConfig(InputStream instream) {

    try {
        String line = "";
        BufferedReader read = new BufferedReader(new InputStreamReader(instream));

        while ((line = read.readLine()) != null) {
            String[] split_line = line.split("=", 2);
            prop.setProperty(split_line[0], split_line[1]);
        }

        prop.store(new FileOutputStream("config.properties"), "Default and local config files");
        read.close();
    }
    catch (Exception e) {
        Log.d("cool", "Failed to create properly initialized config class");
    }
}

public String getProperty (String propertyKey) {

    try {
        return prop.getProperty(propertyKey);
    }
    catch (Exception e) {
        Log.d("cool", "Failed to access property");
        return null;
    }
}

public Context getContext () {
    return context;
}

当我在代码中调用getProperty()方法时,它总是返回null。但是,我不知道它是否未能最初读取和写入值或正在发生的事情。我所知道的是我的程序使用硬编码值但不是在使用这个类时,并且在需要的代码中通过config.getProperty()引用它(我的主框架有一个由所有测试继承的Config类)。

任何帮助都会非常感激。我唯一能想到的是Java的Properties类不能用于Android?

1 个答案:

答案 0 :(得分:0)

Java的属性可以与Android一起使用。

您似乎没有实例化prop,这可能会在您致电NullPointerException时产生prop.getProperty(propertyKey)。在某些时候,您需要使用prop实例化prop = new Properties();。查看these examples。数字2可能会让您的生活更轻松,因为您不需要像在readConfig()中那样手动解析属性文件。