【问题标题】:How to find row number in database using primary key (Android SQLite Eclipse Java)如何使用主键查找数据库中的行号(Android SQLite Eclipse Java)
【发布时间】:2012-05-06 18:45:35
【问题描述】:

我在 ListView 中显示了一系列 sqlite 条目,并且它们的主键位于并行数组中。当用户选择一个项目时,该项目被发送到一个编辑器活动(因此用户可以编辑该条目)。按照我的编程方式,Editor 活动类使用 Cursor 的 moveToPosition 函数使用其行号(意思是位置)从数据库中检索条目。

如何使用条目的主键找出其行号?

编辑:
我找到了一个解决方案,我首先从数据库中检索条目的选择,然后返回并检索这些条目的主键。我将条目存储在一个数组中,将主键存储在另一个数组中。

希望您在看到代码后能够给出更清晰的响应。我正在寻找更优雅的解决方案,尽管这似乎可行。

这里是相关代码。

CalendarMenu.java

@Override
public void onCreate(Bundle savedInstance){
  incomeManager = new SQLManagerIncome(this);
incomeManager.open();

  //This method (see below) gets all of the SQLite entries between two dates
    incomeArray = incomeManager.getDatedEntriesString(
            currentDay.getTimeInMillis(), 
              nextDay.getTimeInMillis());

  //This method (see below) gets the primary keys of all the entries retrieved 
  //in the previous method

    incomeArrayKeys = incomeManager.getDatedKeys(
           currentDay.getTimeInMillis(),
            nextDay.getTimeInMillis());
    incomeManager.close();

    // Sending the SQL info to the ListViews
    incomeAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, incomeArray);
    dayList.setAdapter(incomeAdapter);
}


    @Override
public void onItemClick(AdapterView<?> listView, View view, int pos, long id) {
    Bundle basket = new Bundle();
    // we need to send the position of an entry inside the entire database to the
    // Editor class. So we'll use the primary key of an entry to retrieve its position.

    switch (listView.getId()) {
    case R.id.dayList:
        int entryPos = 0;
        //incomeArrayKeys holds all of the primary keys. It is a parallel
        //array to the array that is displayed in the listview 
        //(using a standard ArrayAdapter)
            incomeManager.open();
            entryPos = incomeManager.findPosByKey(incomeArrayKeys[pos]);
            incomeManager.close();

        basket.putLong("index", entryPos);
                    Class dayClass;
            try {
                dayClass = Class.forName("com.shulim.maaser.EditIncome");
                Intent dayIntent = new Intent(CalendarMenu.this, dayClass);
                dayIntent.putExtras(basket);
                startActivityForResult(dayIntent, 0);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        break;
}

SQLManagerIncome.java

public String[] getDatedEntriesString(Long firstDay, Long lastDay){
    String[] columns = new String[] { KEY_ROWID, KEY_DESCRIPTION,
            KEY_AMOUNT, KEY_DATE, KEY_OWED };
    String selection = KEY_DATE + " >=" + firstDay + " AND " + KEY_DATE
            + "<" + lastDay;
    Cursor c = ourDatabase.query(INCOME_TABLE, columns, selection, null, null, null, null);
    int iDescription = c.getColumnIndex(KEY_DESCRIPTION);
    int iAmount = c.getColumnIndex(KEY_AMOUNT);
    ArrayList<String> keys = new ArrayList<String>();

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        Long dateMillis = c.getLong(3);
        final Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dateMillis);
        int mYear = cal.get(Calendar.YEAR);
        int mMonth = cal.get(Calendar.MONTH)+1;
        int mDay = cal.get(Calendar.DAY_OF_MONTH);
        String date = mMonth + "-" + mDay + "-" + mYear;
        String result = "Desc: " + c.getString(iDescription) 
                + ". Amount: $"
                + c.getString(iAmount) + ". Date: "
                + date + "\n";
        keys.add(result);
    }
    String[] stringDateKeys = new String[keys.size()];
    stringDateKeys = keys.toArray(stringDateKeys);
    c.close();
    return stringDateKeys;
}

public Integer[] getDatedKeys(Long firstDay, Long lastDay) {
    String[] columns = new String[] { KEY_ROWID, KEY_DESCRIPTION,
             KEY_AMOUNT, KEY_DATE };
    String selection = KEY_DATE + " >=" + firstDay + " AND " + KEY_DATE
            + "<" + lastDay;
    Cursor c = ourDatabase.query(INCOME_TABLE, columns, selection, null,
            null, null, null);
    int iRow = c.getColumnIndex(KEY_ROWID);
    ArrayList<Integer> keys = new ArrayList<Integer>();

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        int result = c.getInt(iRow);
        keys.add(result);
    }

        Integer[] intKeys = new Integer[keys.size()];
        intKeys = keys.toArray(intKeys);
        c.close();
        return intKeys;
}

public int findPosByKey(Integer integer) {
    String[] columns = new String[] { KEY_ROWID, KEY_DESCRIPTION,
            KEY_AMOUNT, KEY_DATE };
    Cursor c = ourDatabase.query(INCOME_TABLE, columns, null, null,
            null, null, null);
    int iRow = c.getColumnIndex(KEY_ROWID);
    int position = 0;
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        if (c.getInt(iRow) == integer) {
            break;
        }
        position++;
    }
    c.close();
    return position;
}   

【问题讨论】:

  • 请发布一些您尝试过的相关代码。但是猜测您的 ListView 已连接到 cursorAdapter,您可以从 onItemClickListener 中的 cursorAdapter 中提取行 id。

标签: java android eclipse sqlite


【解决方案1】:

按照我的编程方式,Editor 活动类使用 Cursor 的 moveToPosition 函数使用其行号(表示位置)从数据库中检索条目。

您不需要使用光标的 moveToPosition 函数。相反,有一个更好的解决方案:使用您已有的主键。主键允许一个非常简单和高效的 SQL 查询,它只返回您想要的确切行。我不知道您的列名,但加载此行的示例 SQL 查询将是

SELECT foo, bar, baz
FROM FooBar
WHERE pk = userSelectedPrimaryKey;

userSelectedPrimaryKey 通过查询构建器插入到语句中。

当然,这只是一个粗略的草图,但重点是这个查询将只返回一行,这是用户选择的唯一具有主键值的行。这更简单,并且提高了性能,因为不需要遍历不必要的行。

【讨论】:

  • 感谢您的回答。如果我可以使用主键本身找到条目,我不知道为什么要先在数据库中获取位置?初学者的思维方式:)
  • 我是一名新开发人员,我也面临这样的问题。那么你能告诉我我是如何存储这个 foo、bar 和 baz 的吗?谢谢
【解决方案2】:

您提到I have their primary keys in a parallel array.您可以通过调用int pk= array[position] 并将此值传递给EditorActivity 来检索从该数组中选择的项目的主键。在 EditorActivity 中,您可以通过在 SQL query 的 where 条件中传递此主键来轻松检索要编辑的行,就像 Adam Mihalcin 在他的回答中提到的那样。

【讨论】:

    【解决方案3】:

    我找到了一个解决方案,我首先从数据库中检索选择的条目,然后返回并检索这些条目的主键。我将条目存储在一个数组中,将主键存储在另一个数组中。请参阅我在问题中发布的代码。

    我正在寻找一个更优雅的解决方案,尽管目前这似乎可行。我希望有更优化的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多