运行我的应用程序时,标题出现异常。它的作用是有一个.txt文件,其中包含适用于“ Hangman”游戏的单词,我认为访问该文件时会抛出异常。我的文件cuvinte.txt位于/ assets /中。这是我的代码(我跳过了layout / xml部分,效果很好):
public void onCreate() {
// all the onCreate() stuff, then this:
try {
AssetManager am = this.getAssets();
InputStream is = am.open("cuvinte.txt");
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader b = new BufferedReader(inputStreamReader);
String rand;
while((rand=b.readLine())!=null){
cuvinte.add(rand);
}
} catch (IOException e) {
Toast.makeText(this, "No words file", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
newGame(newG);
}
public void newGame(View view){
Random rand = new Random();
String stringCuvant = cuvinte.get(rand.nextInt(cuvinte.size()));
cuvant.setText("");
System.out.println(stringCuvant);
for(int i = 0; i< stringCuvant.length(); i++){
cuvant.append("_ ");
}
incercari.setText(valIncercari);
}
按下新游戏按钮时以及活动开始时,都会在onCreate()函数中调用newGame()函数。
(仅假设,较少的异常stacktrace信息)
我认为这一行incercari.setText(valIncercari);
抛出Exception,因为valIncercari
是int
应该是这样
incercari.setText(valIncercari+"");
要么
incercari.setText(Integer.toString(valIncercari));
甚至更好:
Integer.toString(valIncercari);
从上面的代码中,没有任何其他代码行导致此异常。只有我在回答中指出的那一行。
与String.valueOf()相同;确实会调用Integer.toString和其他相应的toString方法
我想知道为什么Android Studio不建议您。我在将int值设置为TextView.setText时遇到了相同的错误。
@bheatcoker-因为
setText(int)
还用于通过ID获取字符串资源。在Android中,所有资源ID都具有int
价值。