开发者

Getting the ID of the ListView Item when it is populated from a database

I am developing an android app in which user fills a form by selecting CREATE NEW from a list view and the form is stored in a SQLite database and appears on listview. It is like this

Starting only CREATE NEW After filling a forms ListView will be like

CREATE NEW

FORM1

FORM2

Each form refers a record in a database table

Now What I want 开发者_开发技巧to do is. If I click on Form1 it should open for the user to edit and so on. I am using the position of the listview to match with primary id of the record and showing the respective record

But the whole problem is coming when I delete records

Is there any more elegant method to get the ID of the ListView Item when it is populated from database?


When an item is clicked, you can get it's id in this way: Set an OnItemClickListener to the listView and then you get the id:

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> av, View v, int pos, long id) 
        {
            // Do whatever you want. "id" as the id in the db.
        }
    });


If you select all the records inside your db, I mean without any conditions then the position of the form in the query will be the same position inside the database, but if you have condition in your query than you only get the position of your form inside the you conditional query. You've mentioned clicking, so in the setOnItemClickListener() you have int position variable that specifies item position in the ListView, sometimes there are cases where you have half visible items, then you can apply the formula positon = position - listView.getFirstVisiblePosition(); thus you avoid scrambling the data with the position. Also in the getView() also you can make a use of the same int position variable. I hope this is reasonable.

When you delete records you can signal the ListView to repopulate itself. With the current and new data (same data minus deleted record form the adapter) also you can signal (execute query to delete that record) the database to delete the record, if this is what you are looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜