2012-02-25 32 views
0

我創建了一個SQLiteDatabase,我可以通過'查看'按鈕查看這些項目並點擊它,我將整個數據庫導入到ListView。在這ListView我希望項目是可點擊的,如果我點擊它們,我想添加一個新的條目與它相同的名稱,但另一個ID。到目前爲止我的代碼:Clickable ListView項目需要SQL函數新項目,怎麼樣?

ListView lv; 
ArrayList<String> todoItems = new ArrayList<String>(); 


    @Override 
    protected void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 


     setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, todoItems)); 
      ListView lv = getListView(); 
      lv.setTextFilterEnabled(true); 

     hornot info = new hornot(this); 
     info.open(); 

     Cursor c = info.getAllTitles(); 
     if (c.moveToFirst()) 
     { 
     do{ 


      todoItems.add(c.getString(0) + " " + c.getString(1) + " " + c.getString(2)); 
      }while (c.moveToNext()); 
     } 
      if (todoItems.size() > 0) 
      { 
     lv.setAdapter(new ArrayAdapter<String>(sqview.this,android.R.layout.simple_list_item_1, todoItems)); 
      } 


      lv.setOnItemClickListener(new OnItemClickListener(){ 
       public void onItemClick(AdapterView<?> parent, View view, 
         int position, long id) { 

         //-///////////////////////// 
        } 
        }); 

      info.close(); 

     } 

正如你看到的,我把數據庫項目到一個數組,然後我把它們放入一個ListView。使用升級按鈕我可以添加項目,所以我認爲我需要在這裏做同樣的事情。 在dbhelpercreateEntry功能:

public long createEntry(String name, String hotness) { 
     ContentValues cv = new ContentValues(); 
     cv.put(KEY_NAME, name); 
     cv.put(KEY_HOTNESS, hotness); 
     return ourDatabase.insert(DATABASE_TABLE, null, cv);   
    } 

main.java我轉換EditTextsStrings然後把值放進數據庫:

String name = sqlName.getText().toString(); 
    String hotness = sqlHotness.getText().toString(); 

    hornot entry = new hornot(dbhelp.this); 
    entry.open(); 
    entry.createEntry(name, hotness); 
    entry.close(); 

所以,我應該怎麼寫的onItemClick功能?

回答

0

onItemClick()方法中,您有位置參數,它指示被單擊的列表行(在適配器中)的位置參數。然後,您可以使用getItemAtPositionListView從該行獲得的數據:

lv.setOnItemClickListener(new OnItemClickListener(){ 
       public void onItemClick(AdapterView<?> parent, View view, 
         int position, long id) { 
    String rowData = (String) lv.getItemAtPosition(position); //you'll need to make the lv as final 
    String[] data = rowData.split(" "); //split the result using the spaces (so you could obtain the name, hotness and the other string you use) 
    entry.createEntry(data[0], data[1]); 
} 

我不知道你的數據庫結構,所以我不能建議更換你的東西有關唯一id

+0

我收到一個錯誤:數據庫沒有在行中打開: info.createEntry(data [0],data [1]); 但是它確實是開放的,因爲我只在setonitemclick之後關閉它。 – 2012-02-25 17:43:02

+0

@JaniBela在該行之前添加'entry.open();'。 ' – Luksprog 2012-02-25 17:44:33

+0

加入: info.open(); info.createEntry(data [0],data [1]); \t info.close();現在好了 – 2012-02-25 17:46:35