2012-03-05 52 views
0

我的應用程序有一個列表視圖,它列出講座列表。StaleDataException:重建ListView時訪問關閉的光標錯誤

cursor = myDbHelper.getReadableDatabase().rawQuery(sql, null);  
startManagingCursor(cursor); 
adapter = new Lectures_Adapter(this,R.layout.menu_item,cursor,FROM,TO);   
menuList.setAdapter(adapter); 

在我的自定義接口的代碼是 - - 根據類型它們顏色編碼,我用它來做到這一點,自定義適配器是由下面的代碼稱爲

public class Lectures_Adapter extends SimpleCursorAdapter { 
    private Context appContext; 
    private int layout; 
    private Cursor mycursor; 

    public Lectures_Adapter(Context context, int layout, Cursor c, String[] from,int[] to) { 
      super(context, layout, c, from, to); 
      this.appContext=context; 
      this.layout=layout; 
      this.mycursor=c;    
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent)  
    { 
      View view = super.getView(position, convertView, parent); 
      try {    
      if (position > 0) 
      {    
       RelativeLayout rowFill = (RelativeLayout) convertView.findViewById(R.id.rowFill); 
       String title = mycursor.getString(1);     
       int myColor = 0; 
       int myPos = title.indexOf("Nursing"); 
       int myPos2 = title.indexOf("Masterclass"); 
       if (myPos >= 0) 
       { 
        myColor = Color.parseColor("#99FF66"); 
       } 
       else if (myPos2 >= 0) 
       { 
        myColor = Color.parseColor("#FF99FF"); 
       } 
       else 
       { 
        myColor = Color.parseColor("#FFFF66"); 
       } 
       convertView.findViewById(R.id.rowFill).setBackgroundColor(myColor);     
       }   
      }catch(Exception e) { 

      } 

      if (convertView == null) { 
       LayoutInflater inflator = (LayoutInflater) this.appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       convertView = inflator.inflate(this.layout,null); 
      } else { 
       convertView = (View) convertView; 
      } 
      return view; 
     } 

    } 

我有一個按鈕,顯示一個對話框,該對話框提供了以四種不同方式重新排列Listview的選項。當他們選擇了我重新排序的選項使用下面的代碼列表視圖 -

 Cursor newCursor = myDbHelper.getReadableDatabase().rawQuery(sqlStr, null); 
     adapter.changeCursor(newCursor);     
     adapter.notifyDataSetChanged(); 

這一切似乎工作正常,除非我重新排列和上面的代碼被調用,當它運行getView我得到以下錯誤'StaleDataException:訪問關閉遊標'。這顯然是因爲光標被關閉了,我做錯了什麼?

回答

0

使用getCursor()獲取當前遊標值時,問題得以解決。