I'm trying to build an app which displays fun facts from a text file. To do this I get a random number and then display that specific line number from the file.When I run the app and try and press the button all I get is a blank text field. Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_facts);
// Declare and assign variables
final TextView factLabel = (TextView) findViewById(R.id.factTextView);
Button showFactButton = (Button) findViewById(R.id.showFactButton);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
/*
code here runs when button click is detected by line 29
code shows new fact
*/
String fact = "";
//get a random number to select a fact
Random randomNumberGenrator = new Random();//construct random object
int randomNumber = randomNumberGenrator.nextInt(391);
FileReader fr = null;
try {
fr = new FileReader("facts.txt ");//construct filereader and assign file
} catch (FileNotFoundException e) {
e.printStackTrace();//exception raised
}
LineNumberReader getFact = new LineNumberReader(fr);//construct lineNumberReader
getFact.setLineNumber(randomNumber);//set current line number to random number
try {
fact = getFact.readLine();//read current line and assign it to fact
} catch (IOException e) {
e.printStackTrace();
}
factLabel.setText(fact);
try {
getFact.close();//close lineReader
} catch (IOException e) {
e.printStackTrace();
}
try {
fr.close();//close fileReader
} catch (IOException e) {
e.printStackTrace();
}
}
};
showFactButton.setOnClickListener(listener);
}
Do you getting any errors?
check this line, maybe its typo but worth check it and remove that space from path. OLD: fr = new FileReader("facts.txt "); NEW: fr = new FileReader("facts.txt");