简体   繁体   中英

How to assign database row id to a button

I'm creating a TableLayout UI while iterating over rows from the database. I want to have the functionality of removing a row from the UI as well as database on click of a button. How would I assign that id to the button (perhaps as a button attribute) so that I can fetch it when it's clicked and run the database query?

Activity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.abc.def.FeedHistory">    

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="14dp"
        android:id="@+id/todayTable">
    </TableLayout>

</RelativeLayout>

Java

// result is a Cursor which contains x number of rows
TableLayout table = (TableLayout) findViewById(R.id.todayTable);
while(result.moveToNext())
{
     int row_id = Integer.parseInt(result.getString(0));
     String value_from_db = result.getString(1).toString();
     TableRow row = new TableRow(this);

     TextView row_text = new TextView(this);
     row_text.setText(value_from_db+" units");

     Button delete_button = new Button(this);
     delete_button.setText("Remove");
     // how to set row_id here? 
     // is it okay to use `setId()` method or is there a more elegant way, like a custom attribute?

    row.addView(row_text);
    row.addView(delete_button);
    table.addView(row);
}

You could use View's setTag() and getTag() methods: tag is basically a way to allow views to have memory of some additional piece of data. In your case you can store the id with:

delete_button.setTag(row_id);

In the listener of your Button you can retrieve the id simply with:

Integer id = (Integer) delete_button.getTag();

And then do what your logic is supposed to do with this piece of information. See more here: https://developer.android.com/reference/android/view/View.html#Tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM