Почему ListView, вызванный из обработчика, не может показать элемент - PullRequest
0 голосов
/ 13 апреля 2020

Я пытаюсь получить некоторые данные с веб-страницы и надеюсь показать данные в телефоне. Данные могут быть получены и проанализированы, но не могут отображаться в ListView. Я пробовал много способов решить проблему, которую данные не могут показать в списке, но тщетно. Я не получаю никаких ошибок и исключений из моего кода. Поэтому я не знаю, где проблема. Ниже моя основная деятельность: я открываю поток, чтобы получить данные с веб-страницы, и использую обработчик, чтобы обновить sh интерфейс основного потока

public class SelectStockActivity extends AppCompatActivity {
    private String newsUrl = "https://goodinfo.tw/StockInfo/StockList.asp?MARKET_CAT=%E8%87%AA%E8%A8%82%E7%AF%A9%E9%81%B8&INDUSTRY_CAT=%E6%88%91%E7%9A%84%E6%A2%9D%E4%BB%B6&FILTER_ITEM0=%E6%88%90%E4%BA%A4%E5%BC%B5%E6%95%B8+%28%E5%BC%B5%29&FILTER_VAL_S0=5000&FILTER_VAL_E0=20000&FILTER_ITEM1=%E6%88%90%E4%BA%A4%E5%83%B9+%28%E5%85%83%29&FILTER_VAL_S1=40&FILTER_VAL_E1=60&FILTER_ITEM2=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S2=&FILTER_VAL_E2=&FILTER_ITEM3=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S3=&FILTER_VAL_E3=&FILTER_ITEM4=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S4=&FILTER_VAL_E4=&FILTER_ITEM5=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S5=&FILTER_VAL_E5=&FILTER_ITEM6=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S6=&FILTER_VAL_E6=&FILTER_ITEM7=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S7=&FILTER_VAL_E7=&FILTER_ITEM8=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S8=&FILTER_VAL_E8=&FILTER_ITEM9=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S9=&FILTER_VAL_E9=&FILTER_ITEM10=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S10=&FILTER_VAL_E10=&FILTER_ITEM11=---%E8%AB%8B%E9%81%B8%E6%93%87%E9%81%8E%E6%BF%BE%E6%A2%9D%E4%BB%B6---&FILTER_VAL_S11=&FILTER_VAL_E11=&FILTER_RULE0=---%E8%AB%8B%E6%8C%87%E5%AE%9A%E9%81%B8%E8%82%A1%E6%A2%9D%E4%BB%B6---&FILTER_RULE1=KD%7C%7C%E9%80%B1K%E5%80%BC+%E2%86%97%40%40%E9%80%B1KD%E8%B5%B0%E5%8B%A2%40%40K%E5%80%BC+%E2%86%97&FILTER_RULE2=---%E8%AB%8B%E6%8C%87%E5%AE%9A%E9%81%B8%E8%82%A1%E6%A2%9D%E4%BB%B6---&FILTER_RULE3=---%E8%AB%8B%E6%8C%87%E5%AE%9A%E9%81%B8%E8%82%A1%E6%A2%9D%E4%BB%B6---&FILTER_RULE4=---%E8%AB%8B%E6%8C%87%E5%AE%9A%E9%81%B8%E8%82%A1%E6%A2%9D%E4%BB%B6---&FILTER_RULE5=---%E8%AB%8B%E6%8C%87%E5%AE%9A%E9%81%B8%E8%82%A1%E6%A2%9D%E4%BB%B6---&FILTER_RANK0=%E4%BA%A4%E6%98%93%E7%8B%80%E6%B3%81%7C%7C%E7%B4%AF%E8%A8%88%E6%8C%AF%E5%B9%85+%28%E7%95%B6%E9%80%B1%29%40%40%E7%B4%AF%E8%A8%88%E6%8C%AF%E5%B9%85%40%40%E7%95%B6%E9%80%B1%7C%7C100&FILTER_RANK1=%E4%BA%A4%E6%98%93%E7%8B%80%E6%B3%81%7C%7C%E7%B4%AF%E8%A8%88%E4%B8%8A%E6%BC%B2%E5%B9%85%E5%BA%A6+%28%E7%95%B6%E9%80%B1%29%40%40%E7%B4%AF%E8%A8%88%E4%B8%8A%E6%BC%B2%E5%B9%85%E5%BA%A6%40%40%E7%95%B6%E9%80%B1%7C%7C100&FILTER_RANK2=---%E8%AB%8B%E6%8C%87%E5%AE%9A%E6%8E%92%E5%90%8D%E6%A2%9D%E4%BB%B6---&FILTER_SHEET=%E4%BA%A4%E6%98%93%E7%8B%80%E6%B3%81&FILTER_SHEET2=%E6%97%A5&FILTER_MARKET=%E5%8F%AA%E6%9C%89%E4%B8%8A%E5%B8%82&FILTER_QUERY=%E6%9F%A5++%E8%A9%A2";
    public static Context context;
    private FileWriter fr;
    public static List<String> stockNameList, stockNumberList, stockYesterdayPriceList;
    public static ListView lv;
    static Stock[] stockArray = new Stock[100];


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_stock);
        context = this;
        lv = findViewById(R.id.myList);
        MainThread mt = new MainThread(newsUrl);
        final Thread t = new Thread(mt, "MainThread");
        t.start();

    }

    public static void analyseHTML() {
        String[] textArray, textArray2;

        stockNumberList = new ArrayList();
        stockNameList = new ArrayList();
        stockYesterdayPriceList = new ArrayList();
        if (NetWorkHttpUrlConnection.stringResult != null) {

            textArray = new String[100];
            textArray2 = new String[100];

            Document document = Jsoup.parse(NetWorkHttpUrlConnection.stringResult);
            //解析HTML字串

            Elements element = document.getElementsByAttributeValueContaining("href", "StockDetail.asp?STOCK_ID=");//拿到屬性href裡面包含"StockDetail.asp?STOCK_ID="的值
            Elements element2 = document.getElementsByAttributeValueContaining("href", "ShowK_Chart.asp?STOCK_ID=");//拿到屬性href裡面包含"ShowK_Chart.asp?STOCK_ID="的值
            String text = element.text();//得到這個節點的文字部分
            String text2 = element2.text().replaceAll("    ", "");//得到這個節點的文字部分

            Log.e("AAA", text);
            Log.e("AAA2", text2);
            textArray = text.split(" ");
            textArray2 = text2.split("  ");
            //將資料一個一個取出放到List裡面
            for (int i = 0; i <= (textArray.length) / 2 - 2; i += 2) {
                stockNumberList.add(textArray[i]);
            }
            for (int i = 1; i <= (textArray.length) / 2; i += 2) {
                stockNameList.add(textArray[i]);
            }
            for (int i = 0; i <= textArray2.length - 1; i += 1) {
                stockYesterdayPriceList.add(textArray2[i]);
            }
            Log.e("BBB", stockNameList.toString());
            Log.e("CCC", stockNumberList.toString());
            Log.e("DDD", stockYesterdayPriceList.toString());

        }
    }

    class MainThread implements Runnable {
        private String url, content;
        public MyHandler handler = new MyHandler();

        public MainThread(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            //NetWorkClass netWorkClass = new NetWorkClass();//new 了一個network類
            NetWorkHttpUrlConnection netWorkClass = new NetWorkHttpUrlConnection();
            try {
                content = netWorkClass.POST(url);//接收這個類返回的那個字串也就是需要解析的那一串
                //將得到的HTML資料寫到HtmlContent.txt的檔案中並存在安裝目錄下(為了確認是否有抓到所有網頁資料)
                File dir = context.getFilesDir();//得到安裝目錄下的路徑
                File outfile = new File(dir, "HtmlContent.txt");
                fr = new FileWriter(outfile, true);
                fr.write(content);
                fr.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d("StockContent", "讀完資料");
            handler.sendEmptyMessage(111);
        }
    }

    static class MyHandler extends Handler {
        StockAdapter adapter;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    analyseHTML();

                    //將資料放入Stock物件中
                    for (int i = 0; i <= stockNameList.size() - 1; i++) {
                        stockArray[i] = new Stock(stockNameList.get(i).toString(), stockNumberList.get(i).toString(), stockYesterdayPriceList.get(i).toString());
                        //    Log.e("EEE", stockNameList.get(i).toString()+stockNumberList.get(i).toString()+stockYesterdayPriceList.get(i).toString());
                    }
                    // Step 2 :將商品放入到List集合容器中
                    ArrayList<Stock> listItem = new ArrayList<Stock>();
                    for (int i = 0; i <= stockNameList.size() - 1; i++) {
                        listItem.add(stockArray[i]);
                    }
                    // Step 3 :設定 ListAdapter 資料接口
                    adapter = new StockAdapter(context, listItem);
                    // Step 4 :將資料接口注入到ListActivity
                    lv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                    lv.invalidate();
//                    if(isGetMore){
//                        adapter.notifyDataSetChanged();
///*每一次notifyDataSetChange()都會引起介面的重繪。當需要修改介面上View的相關屬性的時候,
//最後先設定完成再呼叫notifyDataSetChange()來重繪介面。*/
//                    }else {
//                        mainAdapter = new MainAdapter(MainActivity.this, list);
//                        pullListView.setAdapter(mainAdapter);
//                    }
//                    pullListView.refreshComplete();
//                    pullListView.getMoreComplete();
                    break;
            }
        }

    }
}

. Я также новый класс адаптера расширяет BaseAdapter, как показано ниже:

public class StockAdapter extends BaseAdapter {
    // 定義 LayoutInflater (因為會有 Layout 的 xml 轉成 Java 物件的需求)
    private LayoutInflater myInflater;
    // 定義 Adapter 內藴藏的資料容器
    private ArrayList<Stock> list;

    public StockAdapter(Context context, ArrayList<Stock> list) {
        //預先取得 LayoutInflater 物件以便提供給 getView() 方法使用!
        myInflater = LayoutInflater.from(context);
        this.list = list;
    }

    @Override
    public int getCount() { // 公定寫法(取得List資料筆數)
        return 0;
    }

    @Override
    public Object getItem(int position) {// 公定寫法(取得該筆資料)
        return null;
    }

    @Override
    public long getItemId(int position) {// 公定寫法(取得該筆資料的position)
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 1:將 R.layout.row 實例化
        convertView = myInflater.inflate(R.layout.liststock, null);

        // 2:建構view
        TextView stockName = (TextView) convertView.findViewById(R.id.name);
        TextView stockID = (TextView) convertView.findViewById(R.id.ID);
        TextView stockOpenPrice = (TextView) convertView.findViewById(R.id.price);


        // 3:取得Stock物件資料
         Stock stock = list.get(position);
        // 4:設定顯示資料
        stockName.setText(stock.getStockName());
        stockID.setText(stock.getStockID());
        stockOpenPrice.setText(stock.getStockOpenPrice());


        return convertView;
    }
}

У меня есть основной вид деятельности, просто есть текстовое представление и просмотр списка:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/selectLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="每日當沖精選股票"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.035" />


    <ListView
        android:id="@+id/myList"
        android:layout_width="409dp"
        android:layout_height="663dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

еще один xml файл для пользовательского интерфейса выглядит так:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.023"
        app:layout_constraintStart_toEndOf="@+id/name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.016" />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.034"
        app:layout_constraintStart_toEndOf="@+id/ID"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.015" />
...