我一直在尝试让一个应用程序能够运行,允许我从 URL 读取内容,然后将从 URL 获取的文本用于应用程序中的其他目的。
我遇到的问题是文本没有被“保存”。
我知道我的 #getText 方法有效,因为我在 IntelliJ 中运行了一个基本的命令行应用程序:
String textFromUrl;
public static void main(String[] args) {
textFromUrl = Vars.getEngUrlText();
System.out.println(textFromUrl);
}
结果是它打印了它应该打印的确切文本。这是在我的 Android 项目的主 Activity 类中编写的,我只是将 main 方法作为普通 Java 应用程序运行,而不是从 USB 设备运行实际的 apk。
现在,我尝试在 Android 设备中执行相同的操作 在 Vars 类中:
String textFromUrl;
在第一个 Activity 的#onCreate中:
Vars.textFromUrl = Vars.getEngUrlText();
TextView tx = (TextView) findViewById(R.id.titletext);
tx.setText(Vars.textFromUrl);
它只是显示空白,没有文本,什么也没有。布局的其余部分很好,其他一切都显示并且没有错误。我假设 textFromUrl 的值为 null,但我不知道为什么。
是的,我确实拥有在 AndroidManifest 中访问网络的适当权限,因为我正在使用 WebView 并且它工作正常。我什至尝试过运行线程,在更改文本之前给它一些等待时间(大约 5 秒),但它仍然无法工作。
发生什么事了?
下面的 getText 和 #getEngUrlText。
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;
}
最佳答案
通过定位较低的 SDK 修复了此问题。显然,我没有看到 logcat 显示的 NetworkOnMainThreadException,因为我只是在查找错误,而不是所有警告等。
关于java - 文本未保存到字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15424065/