简体   繁体   English

如何在listview之上添加项目并将其保存在数据库中

[英]How to add item on top of listview and save it in database

I'm trying to save data using listview and I want to store the next data at the top of the listview instead it is storing data in the bottom. 我正在尝试使用listview保存数据,我想将下一个数据存储在listview的顶部,而不是将数据存储在底部。 Here's my DatabaseHelper class 这是我的DatabaseHelper类

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";

public DatabaseHelper(Context context) {
    super(context, TABLE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COL2 +" TEXT)";
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("DROP INDEX IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public boolean addData(String item) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, item);


    Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);

    long result = db.insert(TABLE_NAME, null, contentValues);

    //if data as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

} }

There is no such thing as top bottom middle etc with SQLite, although the order of insertions will generally/likely match the rowid column or an alias thereof (your ID column is an alias of the rowid column and as AUTOINCREMENT has been specified then a new insert will have a higher rowid then any that exist). 尽管插入顺序通常/可能与rowid列或其别名匹配(您的ID列是rowid列的别名,并且已指定AUTOINCREMENT,然后是新的),但SQLite中没有顶部中间等等。 insert将具有更高的rowid然后存在任何存在的)。

If you need data in a particular order then you use ORDER BY when extracting the data. 如果需要特定顺序的数据,则在提取数据时使用ORDER BY In your case ORDER BY ID DESC should extract the latest first. 在您的情况下, ORDER BY ID DESC应该首先提取最新的。

As the code you use to extract the data is not present the actual code to be used cannot be provided. 由于用于提取数据的代码不存在,因此无法提供要使用的实际代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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