public class GameActivity extends ActionBarActivity {
private int highScore;
private String displayWord = "";
private String answerWord;
private String guessList = "";
private EditText userGuess;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game2);
int i =0;
ImageView mainImage = (ImageView) findViewById(R.id.gallows);
mainImage.setImageResource(R.drawable.gallow);
try {
randWord(readFile());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(answerWord);
while (i < answerWord.length()){
displayWord += "-";
i++;
}
TextView displayText = (TextView) findViewById(R.id.display_word);
displayText.setText(displayWord);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private List readFile() throws Exception {
List<String> list = new ArrayList<>();
FileInputStream in = (FileInputStream) getAssets().open("food.txt");
Scanner scnr = new Scanner(in);
while (scnr.hasNext()){
list.add(scnr.next());
}
scnr.close();
return list;
}
private void randWord(List list) throws Exception{
Random rnd = new Random();
answerWord = (String) list.get(rnd.nextInt(list.size()));
}
}
I am trying to make a relatively simple hangman app in Android Studio but I have run into a problem with reading in a text file and handling IOExceptions for the file reading. The error that comes up in the console is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at cisc181.myproject_1.GameActivity.onCreate(GameActivity.java:44)
From that error, I know that answerWord is never having a value assigned to it. So, how can I fix this problem? Could it be the way that I am reading in the file?