次のコードに問題があります。まず、私はJavaの初心者で、他のいくつかの言語の経験があります。
Android で以下を実行すると、「in.close();」でエラーになり、catch ブロックにジャンプして Return ""; を実行します。問題は、関数が空の文字列を返さないことです。デバッガーが return json を実行していないと言い、return ""; を実行していると言っても、正しい json データを正常に返します。
public void fetch() {
// Get the JSON of the image gallery
String json = getJSON();
// json somehow has the actual correct json data and not an empty string!
};
private String getJSON() {
try {
// Create a URL for the desired page
URL url = new URL("http://imgur.com/gallery.json");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String json = in.readLine();
in.close();
return json; // <-- debugger doesn't break here!
}
catch(Exception e) {
Log.e("getJSON", e.getMessage());
return ""; // <-- debugger breaks here! Cat Log shows nothing!
}
}
まったく同じコードを Java コンソールにコピーして、エラー メッセージを出力し、ブレーク ポイントを使用してデバッガーで確認できるようにします。コードはエラーなしで実行されます。
try {
// Create a URL for the desired page
URL url = new URL("http://imgur.com/gallery.json");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String json = in.readLine();
in.close();
System.out.println(json);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
正確には何が起こっているのですか?Android でコードを実行すると、Java コンソールで問題なく実行できるのにエラーが発生するのはなぜですか? エラーが発生したときに、エラーが返すはずのものを返さないのはなぜですか。と空の文字列?Android でエラー メッセージを表示するにはどうすればよいですか?