簡體   English   中英

通過刷新listView出現問題:UnsupportedOperationException

[英]Problem by refreshing listView: UnsupportedOperationException

為什么我不能刷新/重新加載ListView? 我已經編寫了一個應用程序,該應用程序讀取html網站,將信息保存在String-Array中,然后將其顯示在ListView中。 但是,每次我關閉並重新打開該應用程序時,新內容就會追加到現有內容中。 在第一輪中,我得到“ 1 2 3 4”,在第二輪中,我得到“ 1 2 3 4 1 2 3 4”,然后是“ 1 2 3 4 1 2 3 4 1 2 3 4”,依此類推。 我在Google上搜索了很多,找到了清除ArrayAdapter(aa)並用新數據重新填充的方法-> aa.clear()/ aa.setModifyDataChanged()/ aa.remove(String Object)/ aa.add(String)但每次我調用一個方法時,我的應用都會強制關閉,LogCat會顯示以下異常:java.lang.UnsupportedOperationException。 為什么? 這真的讓我感到煩惱。 整個星期六下午,我都嘗試進行修復-但沒有成功...也許有人可以幫助我!

這是我的代碼片段

公共類視區擴展了ListActivity {

private static final int AKTUALISIEREN = 0;

private static ArrayList<String> al = new ArrayList<String>();
static String[] TST;
static ArrayAdapter<String> ad;

public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId())
    {
    case AKTUALISIEREN:
    getIt();
        //here a ad.close does a force close 
        setListAdapter(ad);
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }

}

public void onCreate(Bundle savedInstanceState) {  

    super.onCreate(savedInstanceState);
    getIt();
    ad = new ArrayAdapter<String>(this, R.layout.list_item, TST);
    setListAdapter(ad);
    // here, when I try ad.clear() my app does a force close
    ListView lv = getListView();
    lv.setTextFilterEnabled(true);   
}

public static void getIt ()
{
    // Here I get the source-code of the html-site and parse my content
    // All necessary Information I write in my String Array TST, declared above in a static way        
}

我希望有人能幫助我...非常感謝,星期天愉快。

您需要通過ArrayListList而不是固定大小的數組來支持ArrayAdapter固定大小的數組的大小不能更改,也不能清除(無需重新創建,這將使整個目的缺省)

因此,將適配器的內容設置為al而不是TST (注意,您確實需要使用明智的名稱來命名變量)。 然后調用al.clear()al.add(String)來修改支持適配器的數據集。 更改數據集后,請調用ad.notifyDataSetChanged這將導致列表適配器和列表更新顯示。

同樣, 您的適配器也不應該是靜態的TSTal可能也不是)–這將導致內存泄漏,因為適配器會保留對當前上下文的引用。 切勿使上下文靜態任何內容(繪圖,適配器等)。 除非您知道為什么要使某些內容為靜態,否則請將其保留為普通變量。

始終在更新列表視圖時清除TST

暫無
暫無

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

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