我一直试图让应用程序工作,允许我从URL读取,然后使用我从URL获取的文本用于应用程序中的其他目的。
我遇到的问题是文本未被“保存”。
我知道我的#getText方法有效,因为我在IntelliJ中运行了一个基本的命令行应用程序:
String textFromUrl;
public static void main(String[] args) {
textFromUrl = Vars.getEngUrlText();
System.out.println(textFromUrl);
}
结果是它打印出应该的确切文本。这是在我的Android项目的主要活动类中编写的,我只是将main方法作为普通的Java应用程序运行,而不是从我的USB设备运行实际的apk。
现在,我试着在Android设备上做同样的事情 在Vars类中:
String textFromUrl;
在第一项活动的#onCreate中:
Vars.textFromUrl = Vars.getEngUrlText();
TextView tx = (TextView) findViewById(R.id.titletext);
tx.setText(Vars.textFromUrl);
它只显示空白,没有文字,没有任何内容。其余的布局很好,其他一切都显示,没有错误。我假设textFromUrl的值为null,我不知道为什么。
是的我在AndroidManifest中拥有访问网络的适当权限,因为我使用的是WebView,它运行正常。我甚至尝试过运行线程,让它有一些时间等待(大约5秒钟),然后再更改文本,它仍然无法正常工作。
发生了什么事?
getEngUrlText调用getText:
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static String getEngUrlText() {
try {
textFromUrl = getText("url that is supposed to be here removed");
} catch (Exception e) {
e.printStackTrace();
}
return textFromUrl;
}
答案 0 :(得分:0)
通过定位较低的SDK来解决此问题。显然我没有看到logcat正在显示的NetworkOnMainThreadException,因为我只是在查找错误而不是所有警告等等。