[英]In simple class, not able to open file in Assets folder to load to array in Android app
I want to read from my simple java class "MyContent", and there is a static method with no arguments, as once you call the variable inside, it will do the codes inside the static method. I want to read from my simple java class "MyContent", and there is a static method with no arguments, as once you call the variable inside, it will do the codes inside the static method. I am trying to add code into it by reading the files in Assets folder and put into list so that the data adaptor will read it.
我正在尝试通过读取 Assets 文件夹中的文件并将代码添加到其中并放入列表中,以便数据适配器可以读取它。
MyContent class:我的内容 class:
public class MyContent extends Application {
public static final List<Element> ITEMS = new ArrayList<Element>();
private static Random random = new Random(System.currentTimeMillis());
public static final Map<String, Element> ITEM_MAP = new HashMap<String, Element>();
AssetManager assetManager = getAssets();
static {
try {
InputStream inputStream = getAssets().open("data.csv");
InputStreamReader inputStreamReader=new InputStreamReader((inputStream));
BufferedReader bufferedReader=new BufferedReader((inputStreamReader));
String tt="";
while ((tt=bufferedReader.readLine())!=null){
MyContent.addItemElement(MyContent.createElement(tt));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
The problem is that the AssetManager assetManager = getAssets();问题是 AssetManager assetManager = getAssets(); can't be static, but the InputStream inputStream = getAssets().open("data.csv");
不能是 static,而是 InputStream inputStream = getAssets().open("data.csv"); I need to put them into the static method, can anyone tell me how to deal with this issue?
我需要将它们放入 static 方法中,谁能告诉我如何处理这个问题?
getAssets()
need application context
initialised upfront before you can] call it. getAssets()
需要预先初始化应用程序context
,然后才能调用它。 Below code flow should be able to achieve your objective:下面的代码流应该能够实现您的目标:
public class MyContent extends Application {
public static final Map<String, Element> ITEM_MAP;
@Override
public void onCreate() {
super.onCreate();
ITEM_MAP = new HashMap<String, Element>();
AssetManager assetManager = getAssets();
try {
InputStream inputStream = getAssets().open("data.csv");
InputStreamReader inputStreamReader=new InputStreamReader((inputStream));
BufferedReader bufferedReader=new BufferedReader((inputStreamReader));
String tt="";
while ((tt=bufferedReader.readLine())!=null){
MyContent.addItemElement(MyContent.createElement(tt));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Inside your AndroidManifest.xml
, remember to add your app class under tag application
, eg在你的
AndroidManifest.xml
里面,记得在标签下添加你的application
class ,例如
<application
android:name=". MyContent"
...
</application>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.