簡體   English   中英

Android未從網站獲取數據到ArrayList

[英]Android not fetching data from website into ArrayList

我無法讓Android將網絡資源加載到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();

啟動線程后,您將無法獲得代碼,因為該代碼將直接並與線程中的代碼並行執行。 因此,即使在與網站建立連接之前,該代碼也有可能完成。 難怪您的arraylist為空。

您必須將該代碼放在單獨的函數中,並且僅在線程完成后才調用該函數。

我已經解決了。 問題出在“ https”連接上,當我將其更改為“ http”時,它下載了該站點。 但是還有另一個問題-它加載了移動版本?!? 我花了一些時間才弄清楚-“ http://m.sinoptik.bg/shumen-bulgaria-100727233/10-days ”,我不得不對數據提取算法進行一些調整以匹配移動站點,但是現在沒事。 數據與原始站點相同,減去了約700行數據,甚至更好:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM