亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在簡單的類中,無法打開 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 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號