0

what I am trying to do is create an array of strings that has 1000 or so entries. 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. 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.

Any help will be gratefully appreciated. Thank you!

Tyler
  • 1
  • 2
  • Are you looking for something like `Properties`? Bbasically a map of String to String so you can pull values by their keys, and you can easily load them from file. – Zircon Mar 21 '17 at 18:16
  • I'm not sure. I'm basically wanting to create a very large array and would like to pre-populate the values of the array on a text file first that way it doesn't clutter up my code (because there are 1000 plus entries). Once I have that array, I'd like to create a toast which (for simplicity) calls some specific entry by number. – Tyler Mar 21 '17 at 18:20

1 Answers1

0

I would recommend you to create a JSON file as below

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

Now store this file within the assets, and load it as below (thanks to 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 arr = new JSONArray(loadJSONFromAsset());

To retrieve a string from a row, simple call getString - arr.getString (rowNo)

Community
  • 1
  • 1
Libin Varghese
  • 1,506
  • 13
  • 19
  • Thank you so much for the information! I'm definitely a little lost right now with this new approach but I will work through it none the less. – Tyler Mar 21 '17 at 18:51