可点击的ListView项需要SQL函数新项,怎么样?

时间:2012-02-25 16:26:01

标签: android sql database android-listview

我创建了一个SQLiteDatabase,我可以在其中看到带有“查看”按钮的项目,然后单击它,我将整个数据库变为ListView。在这个ListView我希望这些项目是可点击的,如果我点击它们,我想为它添加一个具有相同名称的新条目,但是另一个id。到目前为止我的代码:

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。使用升级按钮我可以添加项目,所以我想我需要在这里做同样的事情。 在dbhelper createEntry函数中:

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我将EditTexts转换为Strings,然后将值放入数据库:

    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函数写什么?

1 个答案:

答案 0 :(得分:0)

onItemClick()方法中,您有position参数,该参数指示单击的列表行的位置(在适配器中)。然后,您可以使用getItemAtPosition上的ListView来获取行中的数据:

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的内容。