我的 java 代码在单独使用时可以正常工作,但在合并到 android 应用程序中时会失败。它的目的是从 url 中提取 JSON。(请注意,使用的 url 是测试 url,因此似乎缺少输入数据。这不是问题)。
public void onClick(View v)
{
try
{
final URL url = new URL("https://apps.bilis.ph/ar/?p={}&lat={}&lon={}&i={}&p={}");
final URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.connect();
final InputStream inputStream = urlConnection.getInputStream();
final StringBuilder sb = new StringBuilder();
while (inputStream.available() > 0)
{
sb.append((char) inputStream.read());
}
String result = sb.toString();
System.out.println(result);
Context context = getApplicationContext();
//CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast hgtoast = Toast.makeText(context, result, duration);
hgtoast.show();
} catch (Exception e) {
System.err.print(e);
String notwerk = "Internet connection failure";
Context context = getApplicationContext();
//CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast failtoast = Toast.makeText(context, notwerk, duration);
failtoast.show();
}
}
已使用允许 Internet 连接的 Android 权限。单击按钮时,将显示代码中的错误 toast。同样,代码(没有 toasts)在隔离类中运行完全正常。Eclipse 没有检测到错误。
谢谢