我无法让Android将一个web资源加载到一个ArrayList中 - 无论我做什么,列表都是空的。如果我不在线程中运行它,logcat会显示一个StrictMode$AndroidBlockGuardPolicy.onNetwork
错误。在Java VM中,这是完美的工作;该网站被加载到列表中,我可以得到我想要的数据。Android没有从网站获取数据到ArrayList
下面是代码:
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是空的,它什么都不做。
'不能让Android将网站加载到ArrayList'。 Android的?你的意思是你的应用?你的Android应用程序? – greenapps
通常,您在Android中使用Asynctask进行联网 –
是的,当我运行应用程序时,它给了我“空值”。 – Rado