【问题标题】:Android Listview onListItemClick get Sqlite IdAndroid Listview onListItemClick 获取Sqlite Id
【发布时间】:2013-10-08 06:02:47
【问题描述】:

我只是从 sqlite 表中显示一个列表。我没有使用任何 BDHelper 类。仅使用此代码,我如何获得 id。


当我点击第一项时,它显示 0,在表格中它的 id 为 1。下面是我的代码。

SQLiteDatabase myDB;
        try {
            myDB = openOrCreateDatabase(DB_NAME,
                    SQLiteDatabase.CREATE_IF_NECESSARY, null);          
            myDB.execSQL("create table if not exists " + COUNTRY_TABLE
            + "(country_id INTEGER PRIMARY KEY,"
            + "country_title text," 
            + "country_status int(11));");          

             /*myDB.execSQL("insert into " + COUNTRY_TABLE +" values "+
             "(null,'India',1)," +
             "(null,'China',1)," +
             "(null,'Australia',1)," +
             "(null,'Japan',1)," +
             "(null,'Germany',1)");*/


            Cursor c = myDB.rawQuery("select country_id,country_title from "
                    + COUNTRY_TABLE + " where country_status=1", null);
            if (c != null) {
                if (c.moveToFirst()) {
                    do {
                        int id = c.getInt(c.getColumnIndex("country_id"));
                        String name = c.getString(c.getColumnIndex("country_title"));                       
                        clist.add(id + ") " + name);
                    } while (c.moveToNext());
                    //int itemcount = clist.size();
                    //Toast.makeText(MainActivity.this, itemcount, Toast.LENGTH_LONG).show();
                    setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, clist));
                }
            }

        } catch (SQLiteException se) {
            Toast.makeText(MainActivity.this, se.getMessage().toString(),Toast.LENGTH_LONG).show();
        }

protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Toast.makeText(MainActivity.this,String.valueOf(id),Toast.LENGTH_LONG).show();
    }

请建议我应该怎么做才能从表中获取 id 而不是位置。

【问题讨论】:

  • 您可以使用 CursorAdapter 或其他 ArrayList 来存储 Country id,然后使用 Item 点击位置作为country_ids.get(id) 检索

标签: android sqlite android-listview


【解决方案1】:

试试下面的代码:

把你的id和name数据放到clist的ArrayList中,先生成getter、setter方法,当你拿到数据的时候在那个方法里设置你的id和name,每次把数据加到ArrayList中,然后像下面这样使用。

protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Toast.makeText(MainActivity.this,clist.get(position).getId(),Toast.LENGTH_LONG).show();
    }

【讨论】:

  • 我用自定义代码做了另一个例子。检查下面的代码: public void onItemClick(AdapterView> arg0, View arg1, int arg2,long arg3) { int id=arg0.getId(); Toast.makeText(MainActivity.this,id,Toast.LENGTH_SHORT).show();在 toast 中,它来了,false 而不是 id。
  • 你必须从你的 sqlite 数据中获取你的 id。将该数据存储在 arraylist 或 hashmap 中,然后通过以下方式获取: int id=arraylist.get(arg2);你一定会得到它。
  • 我无法在评论框中发布整个代码,所以我发布了我将删除的答案。请检查我的答案。
  • int id=list_data.get(arg2).getId();写下这一行。
  • 它给出了这个错误。 android.content.res.Resources$NotFoundException: 字符串资源 ID #0x3
【解决方案2】:
public List<Emp> AllRecords() 
{
    List<Emp> dataset = new ArrayList<Emp>();
    Cursor cursor = database.query(DatabaseHelper.TABLE_EMPLOYEE,allColumns, null, null,null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Emp obj = cursorToContact(cursor);
        dataset.add(obj);
      cursor.moveToNext();
    }
    cursor.close();
    return dataset;
}

private Emp cursorToContact(Cursor cursor) 
{
    Emp obj = new Emp();
    obj.setId(cursor.getInt(0));
    obj.setName(cursor.getString(1));
    obj.setDesig(cursor.getString(2));
    return obj;
}


//--------------
list_data = (ArrayList<Emp>) qh.AllRecords();
CustomListAdapter adapter = new CustomListAdapter(MainActivity.this,list_data);
//---------
int id=list_data.get(arg2); //Type mismatch: cannot convert from Emp to int

请告诉我应该写什么来获取国家/地区 ID。

【讨论】:

    【解决方案3】:

    看看如何没有公认的答案...... 我这样做了,它似乎有效。

    我正在使用 ListView Activity、SQLiteDatabase 和 ArrayAdapter

    在我的 onListItemClick 方法中,我实例化了一个新对象并使其等于适配器中当前位置的任何项目。 任务task = adapter.getItem(arg3);

    在我的任务类中,我有一个名为 id 的 long 类型的私有变量,以及该变量的 setter 和 getter。

    因此,我可以这样做: long taskId = task.getId();

    用 Toast 检查这个结果,得到了 SQLite 生成的 id,而不是我需要的 ListView 中的位置。

    希望这对某人有所帮助!

    【讨论】:

      【解决方案4】:

      您可以使用 id 在列表项上设置标签,之后您可以在 onItemClick 上调用 getTag()。

      【讨论】:

        【解决方案5】:

        ((TextView)v).getText();通过这个我们会得到view的text,然后我们可以再次查询table得到对应text的id并toast。

         String country_title=((TextView)v).getText();
        
         Cursor c = myDB.rawQuery("select country_id from "+ COUNTRY_TABLE + " where  country_title='"+country_title+"'", null);
          Toast.makeText(MainActivity.this,c.getString(c.getColumnIndexorThrow("country_title")),Toast.LENGTH_LONG).show();
        

        【讨论】:

        • 我认为这不是正确的方法,因为在这里我将不得不触发查询并从表中获取,因此会增加响应时间。此外,在任何其他情况下,如果标题相同,则将获取多条记录。
        【解决方案6】:

        这不是我想要的方式,而是通过其他方式得到了解决方案。在游标循环中,将数据添加到列表中,获取另一个 ArrayList 并仅向其添加 id。

        clist1.add(id);
        

        现在,在 onListItemClick 上,您可以获得项目的位置。所以,使用这个位置并从另一个 ArrayList clist1 中获取 id

        int country_id=clist1[position];
        

        希望这会有所帮助。

        【讨论】:

          【解决方案7】:

          我晚了几年,但它可能对其他人有所帮助:基本上在您设置单个视图的任何位置设置标签。

            // Find fields to populate in inflated template
          
              TextView productName = (TextView) view.findViewById(R.id.product_name);
              TextView productPrice = (TextView) view.findViewById(R.id.product_price);
              TextView productQuantity = (TextView) view.findViewById(R.id.product_quantity);
          
              // Extract properties from cursor
          
              String name = cursor.getString(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_NAME));
              int price = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_PRICE));
              int quantity = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_QUANTITY));
              int id = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.ID));
          
              // Set Tag
              productName.setTag(id);
          

          然后你可以通过调用 getTag() 来访问它:

              int id = (Integer)((TextView)findViewById(R.id.product_name)).getTag();
          
              Log.d("LETSEE",String.valueOf(id));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-01-16
            • 2019-10-09
            • 1970-01-01
            • 1970-01-01
            • 2011-03-27
            • 2011-06-13
            • 2011-12-23
            • 1970-01-01
            相关资源
            最近更新 更多