简体   繁体   English

创建一个应用程序-Java-从.txt文件创建一个arraylist,并为arraylist的特定行

[英]Creating an app - Java - create an arraylist from a .txt file and toast specific line of arraylist

what I am trying to do is create an array of strings that has 1000 or so entries. 我想做的是创建一个包含1000个左右条目的字符串数组。 Instead of doing: 而不是做:

public void DefaultGeneric(View v) throws FileNotFoundException{
    Random rand = new Random();
    int i = rand.nextInt(4) + 0;
    int j = rand.nextInt(4) + 0;
    String[] SomeThingA = {"yep","okay","nope"};    //I need this array to be much much larger but want a better way of doing it.
    String[] SomeThingB = {"test","test1","test2"}; //I need this array to be much much larger but want a better way of doing it.

    Toast.makeText(getBaseContext(), SomeThingA[i]+SomeThingB[j], Toast.LENGTH_LONG ).show();

}

to declare my long array I've been researching how to create a .txt file with all of the array values and then using arraylist. 声明我的长数组,我一直在研究如何使用所有数组值创建一个.txt文件,然后使用arraylist。 But every time I try it fails. 但是每次尝试都会失败。 In addition, once I figure out how to use arraylist I then need to use the: Toast.makeText(getBaseContext(), variable, Toast.LENGTH_SHORT).show to call out a specific row of my arraylist. 另外,一旦弄清楚如何使用arraylist,我就需要使用: Toast.makeText(getBaseContext(), variable, Toast.LENGTH_SHORT).show调用我的arraylist的特定行。

Any help will be gratefully appreciated. 任何帮助将不胜感激。 Thank you! 谢谢!

I would recommend you to create a JSON file as below 我建议您如下创建JSON文件

[
  "entryOne",
  "entryTwo",
  "...",
  "entryN"
]

Now store this file within the assets, and load it as below (thanks to https://stackoverflow.com/a/13814551/7274758 ) 现在将此文件存储在资产中,并按如下所示加载它(感谢https://stackoverflow.com/a/13814551/7274758

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getAssets().open("file_name.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    }
    catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

Then you could try to create an Array of this JSON String via JSONArray 然后,您可以尝试通过JSONArray创建此JSON字符串的数组

JSONArray arr = new JSONArray(loadJSONFromAsset());

To retrieve a string from a row, simple call getString - arr.getString (rowNo) 要从行中检索字符串,只需调用getString - arr.getString (rowNo)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM