我无法让 Android 将 Web 资源加载到 ArrayList 中 - 无论我做什么,列表都是空的。如果我不在线程中运行它,logcat 将显示 StrictMode$AndroidBlockGuardPolicy.onNetwork
错误。在 java VM 中,这工作得很好;该网站已加载到列表中,我可以获得我想要的数据。
这是代码:
public class WeatherData {
public static String data() {
String[] tempsArr = new String[9];
String[] minArr = new String[9];
Calendar calendar = Calendar.getInstance();
String[] weekDay = new String[1];
SimpleDateFormat[] dayFormat = new SimpleDateFormat[1];
dayFormat[0] = new SimpleDateFormat("E");
weekDay[0] = dayFormat[0].format(calendar.getTime());
final ArrayList<String> list = new ArrayList<String>();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
System.setProperty("http.proxyHost", "cache.mrt.ac.lk");
System.setProperty("http.proxyPort", "3128");
//Document doc = Jsoup.connect(url).timeout(10000).get();
URL link = new URL("https://www.sinoptik.bg/shumen-bulgaria-100727233/10-days");
BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
String inputLine;
String[] arr;
int count = 0;
while ((inputLine = in.readLine()) != null) {
list.add(inputLine);
count++;
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
});
thread.start();
dayFormat[0] = new SimpleDateFormat("E");
weekDay[0] = dayFormat[0].format(calendar.getTime());
int idx = 0;
for (
int j = 0; j < list.size() - 550; j++)
{
if (list.get(j).contains(weekDay[0].toString())) {
tempsArr[idx] = getNum(list.get(j + 3));
minArr[idx] = getNum(list.get(j + 5));
idx++;
calendar.add(Calendar.DAY_OF_WEEK, 1);
weekDay[0] = dayFormat[0].format(calendar.getTime());
}
}
return tempsArr[1];
}
我知道它需要优化,但我想首先让它工作并给我至少一个值(这就是为什么我只使用一个具有一个索引的数组来返回)。我在调试时看到它正在连接到站点,但 ArrayList 是空的并且什么也没做。
最佳答案
thread.start();
启动线程后就不能再有代码,因为该代码将直接与线程中的代码并行执行。因此,该代码甚至可能在与网站建立连接之前就已完成。难怪你的数组列表是空的。
您必须将该代码放在一个单独的函数中,并且仅在线程完成后调用该函数。
关于java - Android 不从网站获取数据到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46667850/