2011-03-11 64 views
0

以下是我的代碼來顯示數據到數據庫的列表視圖。但它不會工作和崩潰我的application.please爲我的這個問題提供完美的解決方案。從SQLite填充Listview時,我的代碼出了什麼問題?

我的代碼......

 public void onCreate(Bundle savedInstanceState) 
     { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.deletestudent); 
      // DisplayStudent(); 


     ArrayList<String > arrlst=new ArrayList<String>(); 
     ListView lst_stu=(ListView) findViewById(R.id.ListView01); 

      db.open(); 
      Cursor cur=db.GetStudent(); 

      for (int i=0;i<cur.getCount();i++) 
      { 
       cur.moveToFirst(); 

       String stunm=cur.getString(1); 
       arrlst.add(1, stunm); 
       lst_stu.setAdapter((ListAdapter) arrlst); 

       db.close(); 
      } 

    } 
+0

你爲什麼要設置適配器和關閉數據庫裏面的for循環? – Abhinav 2011-03-11 05:46:24

+0

現在,我要改變我的代碼。 – 2011-03-11 05:51:21

回答

1

請嘗試以下代碼

try 
    { 
     Cursor cursor = null; 

     db.OpenDatabase(); 
     cursor = db.GetStudent(); 

     // Here if condition check wheather the cursor returns record or not. 
     // If cursor has some records then it will return non zero number . 

     if (cursor.getCount() != 0) 
     { 
      // Here if condition check wheather the cursor move to first record or not 
      // If it moves to first record then it will return true. 
      if (cursor.moveToFirst()) 
      { 
       do 
       { 
        arrlst.add(cursor.getInt(cursor.getColumnIndex("your_field_in_database")).trim()); 

       }while (cursor.moveToNext()); 
      } 
     } 

     cursor.close(); 
     db.closeDatabase(); 
     lst_stu.setAdapter((ListAdapter) arrlst); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
+0

親愛的它不會給出任何錯誤,但它不顯示數據進入列表視圖。 – 2011-03-11 06:17:41

+0

錯誤是什麼?你可以發佈logcat錯誤? – 2011-03-11 07:00:05

+0

我得到了我的那個問題的輸出。 – 2011-03-11 07:03:27

2
 for (int i=0;i<cur.getCount();i++) 
     { 
      cur.moveToFirst(); 

      String stunm=cur.getString(1); 
      arrlst.add(1, stunm); 
      lst_stu.setAdapter((ListAdapter) arrlst); 

      db.close(); 
     } 

的問題是,你是關閉遊標在第一次迭代。

爲我的這個問題提供完美的解決方案。

你看起來像我的老闆,節選他支付每小時20美元....

不管結果如何,有很多的事情是在你的代碼不好,主要是因爲你不」不知道光標是如何工作的:

  • 爲什麼在每次迭代中調用moveToFirst?它是否爲你感覺?
  • 爲什麼你關閉光標裏面的for?
  • 爲什麼在每次迭代中設置適配器?
  • 爲什麼使用陣列適配器而不是CursorAdapter
+0

對不起親愛的。但是當人們犯錯時人們會學到一些東西。 – 2011-03-11 06:43:08

+0

現在我得到了我的問題的解決方案,它會因爲你的指導而工作。再次感謝。 – 2011-03-11 06:45:00

+0

哦,是的......這是一種試錯法。這很好,但你可以嘗試另一種更好的學習方法:閱讀。如果你有一天學會*閱讀*,你不僅會學習*某些東西*,而且還會節省很多時間。 – Cristian 2011-03-11 13:08:49

相關問題