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

我想从我的简单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"); 我需要将它们放入静态方法中,谁能告诉我如何处理这个问题?


慕仙森
浏览 47回答 1
1回答

一只斗牛犬

getAssets()需要context预先初始化应用程序,然后才能]调用它。下面的代码流程应该能够实现您的目标:public class MyContent extends Application {&nbsp; &nbsp; public static final Map<String, Element> ITEM_MAP;&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onCreate() {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate();&nbsp; &nbsp; &nbsp; &nbsp; ITEM_MAP = new HashMap<String, Element>();&nbsp; &nbsp; &nbsp; &nbsp; AssetManager assetManager = getAssets();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InputStream inputStream = getAssets().open("data.csv");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InputStreamReader inputStreamReader=new InputStreamReader((inputStream));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BufferedReader bufferedReader=new BufferedReader((inputStreamReader));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String tt="";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while ((tt=bufferedReader.readLine())!=null){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MyContent.addItemElement(MyContent.createElement(tt));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch (FileNotFoundException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}编辑1在你的里面AndroidManifest.xml,记得在标签下添加你的应用程序类application,例如<application&nbsp; &nbsp; &nbsp; &nbsp; android:name=". MyContent"&nbsp; &nbsp;...</application>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java