为了账号安全,请及时绑定邮箱和手机立即绑定

在简单的类中,无法打开 Assets 文件夹中的文件以加载到 Android 应用程序中的数组

在简单的类中,无法打开 Assets 文件夹中的文件以加载到 Android 应用程序中的数组

慕仙森 2024-01-05 15:20:26
我想从我的简单java类“MyContent”中读取,并且有一个没有参数的静态方法,因为一旦你调用里面的变量,它就会执行静态方法内的代码。我试图通过读取资产文件夹中的文件并将代码放入其中,以便数据适配器能够读取它。我的内容类: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();    }}}问题是 AssetManager assetManager = getAssets(); 不能是静态的,但 InputStream inputStream = getAssets().open("data.csv"); 我需要将它们放入静态方法中,谁能告诉我如何处理这个问题?
查看完整描述

1 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

getAssets()需要context预先初始化应用程序,然后才能]调用它。下面的代码流程应该能够实现您的目标:


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

        }

    }

}


编辑1

在你的里面AndroidManifest.xml,记得在标签下添加你的应用程序类application,例如


<application

        android:name=". MyContent"

   ...

</application>


查看完整回答
反对 回复 2024-01-05
  • 1 回答
  • 0 关注
  • 44 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信