为Android ListView中的行分配ID

Chr*_*ris 8 android row android-listview

我有一个ListView.当点击ListView上的项目时,它会加载一个SubView.我想为ListView的每一行分配一个ID,所以我可以将该ID传递给SubView.如何为ListView中的每一行分配特定ID?

这是我当前加载ListView的方式:

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mArrayList));
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 8

这就是我解决问题的方法.我从本地SQLite数据库获得了employee_ids和employee_names,然后我同时创建了employeeNamesArray的ArrayList和employeeIdArray的ArrayList.因此,employeeIdArray [0]将匹配employeeNameArray [0],employeeIdArray [1]将匹配employeeNameArray [1]等.

创建ArrayLists后,我将employeeNameArray输入ListView.

稍后,在onListItemClick中,我检索所选ListView行的位置.这个'position'将与ArrayLists中的位置相对应 - 因此,如果我选择ListView中的第一行,则位置将为零,employeeNameArray [0]与employeeIdArray [0]匹配.我从employeeIdArray中获取了coroloating条目,并使用putExtra将其推送到下一个Activity.

public class MyFirstDatabase extends ListActivity {
    ArrayList<String> employeeIdArray = new ArrayList<String>(); // List of EmployeeIDs

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);                                                           

        // Open the database
        SQLiteDatabase db;
        db = openOrCreateDatabase("mydb.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);

        // Query the database
        Cursor cur = db.query("employee", null, null, null, null, null, "employee_lastname"); 

        cur.moveToFirst(); // move to the begin of the db results       

        ArrayList<String> employeeNameArray = new ArrayList<String>(); // Initialize mArrayList


        while (cur.isAfterLast() == false) {
            employeeNameArray.add(cur.getString(1)); // add the employee name to the nameArray
            employeeIdArray.add(cur.getString(0)); // add the employee id to the idArray
            cur.moveToNext(); // move to the next result set in the cursor
        } 

        cur.close(); // close the cursor


        // put the nameArray into the ListView  
        setListAdapter(new ArrayAdapter<String>(this,R.layout.list_item,employeeNameArray));          
        ListView lv = getListView();  
        lv.setTextFilterEnabled(true);
    }


    protected void onListItemClick(ListView l, View v, final int position, long id) { 
        super.onListItemClick(l, v, position, id);                
        Intent myIntent = new Intent(this, SubView.class); // when a row is tapped, load SubView.class

        Integer selectionID = Integer.parseInt(employeeIdArray.get(position)); // get the value from employeIdArray which corrosponds to the 'position' of the selected row
        myIntent.putExtra("RowID", selectionID); // add selectionID to the Intent   

        startActivityForResult(myIntent, 0); // display SubView.class  

    } 
}
Run Code Online (Sandbox Code Playgroud)