0

我有一个问题,我为所有活动创建了数据库,并且在每个活动中我都应该向数据库中插入信息,所以对于第一个活动,插入完成,对于第二个活动,我用新的插入更新行以完成所有信息和依此类推,我的问题是我不知道如何引用最后一行,我的意思是我应该怎么做才能使第二个活动的更新发生在第一个活动中插入的最后一行,你呢?有什么建议吗???

4

2 回答 2

1

那么你可以只使用主键。当您将某些内容插入数据库时​​,您将获得主键作为返回值。您可以将其添加到打开另一个 Activity 的 Intent 中,然后参考您之前插入的行。

编辑:

我不知道您是使用 SQLiteDatabase 对象还是使用 ContentProvider,但无论如何代码几乎相同。在此示例中,我将直接使用 SQLiteDatabase 对象,即使在大多数情况下使用 ContentProviders 是更好的选择。

在您的第一个活动中:

// When you perform an insert you get the id of the row which was just inserted.
long id = sqliteDatabase.insert("some_table", null, contentValues);

// The id will be -1 if an error occured
if(id >= 0) {
    ...
}

...

// When you start your second Activity you can add the id to the Intent 
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);

// The String is a tag with which you can later retrieve the id from the Intent.
// Note that you should never hardcode String like that, use constants in your app.
intent.putExtra("rowId", id);

在第二个 Activity 的 onCreate 方法中,您可以检索 id:

@Override
protected void onCreate (Bundle savedInstanceState) {
    // Check if the Activity has been created for the first time
    if(savedInstanceState == null) {

        // Retrieve the Intent with which the Activity was started
        Intent intent = getIntent();

        long id = intent.getLongExtra ("rowId", -1);

        // If id is valid proceed
        if(id >= 0) {
            Cursor cursor = sqliteDatabase.query("some_table", columns, "_id = ?", 
                                                 new String[] { String.valueOf(id) }, null, null, null, null);

            // Check if Cursor is valid and if yes read your data.
            if(cursor != null) {
                ...
            }           
        }
    }
}
于 2013-11-06T01:15:03.917 回答
0

最好的方法是在数据库中添加一列,该列将保存插入行的时间。然后,当您需要最新的行时,查询具有最新时间的行。一个示例 SQL 字符串是:

SELECT * FROM my_table WHERE 1 ORDER BY time_stamp LIMIT 1
于 2013-11-06T01:13:37.300 回答