在文本文件中显示特定行-android/java
我正试图建立一个应用程序,显示有趣的事实,从一个文本文件。为此,我获取一个随机数,然后显示文件中的特定行号。当我运行应用程序并尝试按下按钮时,我得到的只是一个空白文本字段。这是我的密码:在文本文件中显示特定行-android/java,java,android,string,text,Java,Android,String,Text,我正试图建立一个应用程序,显示有趣的事实,从一个文本文件。为此,我获取一个随机数,然后显示文件中的特定行号。当我运行应用程序并尝试按下按钮时,我得到的只是一个空白文本字段。这是我的密码: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fun_facts); // Declar
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);
}
你有什么错误吗 检查这一行,可能是它的打字错误,但值得检查一下,并从路径中删除该空格。 旧的: fr=新文件阅读器(“facts.txt”); 新的:
fr=新文件阅读器(“facts.txt”)
“facts.txt”
包含空格键,模拟器只会说“FunFacts已停止”。logcat说它已经暂停了所有theades。Gradle什么都没有您授予的外部存储权限?