private String[] words;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDecorView = getWindow().getDecorView();
loadWords();
TextView tv = (TextView) findViewById(R.id.word);
tv.setText(words[0]);
}
public void loadWords()
{
try {
InputStream file = new FileInputStream("words.txt");
InputStreamReader sr = new InputStreamReader(file);
BufferedReader br = new BufferedReader(sr);
int n = 0;
while(br.readLine() != null)
{
words[n] = br.readLine();
n++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
Ok, so I am only trying to print out the first element in the array, but the app crashes during launch and gives me the error "Attempt to read from null array"
EDIT - Solution
-I had not initialize the array.(I knew I had 100 lines)
-My input stream was incorrect (my file could not be found)
-I tried to update a TextView from a secound layout(that was not selected at the time)
String[] words = new String[100];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDecorView = getWindow().getDecorView();
loadWords();
}
public void changeView(View view) {
setContentView(R.layout.game_view);
TextView tv = (TextView) findViewById(R.id.word);
tv.setText(words[0]);
}
public void loadWords()
{
try {
BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("words.txt")));
for(int i = 0;i<words.length;i++)
{
words[i] = br.readLine();
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}