Android Arraylist项目ID

时间:2014-01-10 15:47:17

标签: android sqlite arraylist

我是一名.Net开发人员超过12年,并且是Android的新手,所以概念与我类似,但我一直在谷歌上搜索很多细节(和术语)...

这是我的问题 - 我正在查询SQLite以获取特定表的所有记录,使用Cursor来填充已经存储到我创建的Object的ArrayList。从那里我使用ArrayAdapter来填充ListView。从那里长按一下,我有一个监听器,它有一个上下文菜单,其中包含编辑和删除等选项。为了做到这些,你需要有原始的SQLite _id,我读到你可以通过使用AdapterView.AdapterContextMenuInfo信息然后简单地使用info.id来获得它。

在调试器中,我注意到这总是设置为0.所以当我在调试器中构建ArrayList时,我进一步回到查询的所有位置,每个项目都包含来自查询的所有字段信息EXCEPT _id 。它确实有一个id字段,但总是设置为0.我假设这是我必须设置的字段才能传递id,但是没有提供这样做的方法。 下面是我的SQLite查询:

public ArrayList<Books> getAllBooks(){
        ArrayList<Books> itemList = new ArrayList<Books>();

        String sqlQuery =
                "Select "
                + KEY_ID + ", "
                + title + ", "
                + description + ", "
                + genre + ", "
                + creation_dt + ", "
                + modification_dt
                + " From "
                + TABLE_Books;

        Cursor cursor = database.rawQuery(sqlQuery, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            //itemList.add(new Books(cursor.getInt(0), cursor.getString(1), cursor.getString(2)));
            String logId = String.valueOf(cursor.getInt(0));
            Log.i("Book ID", "Book Title: " + cursor.getString(1) + " KEY_ID: " + logId);
            itemList.add(cursorToBook(cursor));
            cursor.moveToNext();
        }
        cursor.close();
        return itemList;
    }

    private Books cursorToBook(Cursor cursor){
        Books book = new Books();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
        book.setId(cursor.getInt(0));
        book.setTitle(cursor.getString(1));
        book.setDescription(cursor.getString(2));
        book.setGenre(cursor.getString(3));
        return book;
    }

这是我的图书对象:

public class Books {
    public int _id;
    private String title;
    private String description;
    private String genre;
    private Date creation_dt;
    private Date modification_dt;

    public int getId(){ return _id;}
    public void setId(int Id){ this._id = _id;}

    public String getTitle(){ return title;}
    public void setTitle(String title){ this.title = title;}

    public String getDescription(){ return description;}
    public void setDescription(String description){ this.description = description;}

    public String getGenre(){ return genre;}
    public void setGenre(String genre){ this.genre = genre;}

    public Date getCreation_dt(){ return creation_dt;}
    public void setCreation_dt(Date creation_dt){ this.creation_dt = creation_dt;}

    public Date getModification_dt(){ return modification_dt;}
    public void setModification_dt(Date modification_dt){ this.modification_dt = modification_dt;}

}

非常感谢任何时间花在回复上! 谢谢。

更新 我的SQLiteOpenHelper -

public class SQLiteHelper extends SQLiteOpenHelper{

    //Database
    private static final String Database_Name = "novel.db";
    private static final int Database_Version = 1;

    // Table Names
    public static final String TABLE_Books = "books";
    public static final String TABLE_Chapter = "chapters";
    public static final String TABLE_major_Character = "master_character";

    //Common Columns
    public static final String column_id = "_id";

    //Book Columns
    public static final String book_title = "title";
    public static final String book_description = "description";
    public static final String book_genre = "genre";
    public static final String book_creation_dt = "creation_dt";
    public static final String book_modification_dt = "modification_dt";

    //Chapter Columns
    public static final String chapter_chapter_num = "chapter_num";
    public static final String chapter_chapter_title = "chapter_title";
    public static final String chapter_start_page = "start_page";
    public static final String chapter_end_page = "end_page";
    public static final String chapter_total_pages = "total_pages";
    public static final String chapter_synopsis = "synopsis";
    public static final String chapter_book_id = "book_id";

    //Master Character Columns
    public static final String mc_name = "name";
    public static final String mc_role = "role";
    public static final String mc_age = "age";
    public static final String mc_pertinent_info = "pertinent_info";
    public static final String mc_relevant_backstory = "relevant_backstory";

    public static final String book_create = "create table " + TABLE_Books
            + " ("
            + column_id + " integer primary key autoincrement, "
            + book_title + " varchar(1000), "
            + book_description + " varchar(100), "
            + book_creation_dt + " datetime, "
            + book_modification_dt + " datetime, "
            + book_genre + " varchar(250) "
            + ")";

    public static final String chapters_create = "create table " + TABLE_Chapter
            + " ("
            + column_id + " integer primary key autoincrement, "
            + chapter_chapter_num + " int, "
            + chapter_chapter_title + " varchar(1000), "
            + chapter_start_page + " int, "
            + chapter_end_page + " int, "
            + chapter_total_pages + " int, "
            + chapter_synopsis + " varchar(1000), "
            + chapter_book_id + " int"
            + ")";
    public static final String master_character_create = "create table " + TABLE_major_Character
            + " ("
            + column_id + " integer primary key autoincrement, "
            + mc_name + " varchar(1000), "
            + mc_role + " varchar(1000), "
            + mc_age + " int, "
            + mc_pertinent_info + " varchar(1000), "
            + mc_relevant_backstory + " varchar(1000) "
            + ")";

public SQLiteHelper(Context context){
    super (context, Database_Name, null, Database_Version );
}

    @Override
    public void onCreate(SQLiteDatabase database){
        database.execSQL(book_create);
        database.execSQL(chapters_create);
        database.execSQL(master_character_create);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(SQLiteHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ", THIS WILL DESTROY ALL OLD DATA!");
        db.execSQL("drop table if exists " + TABLE_Books);
        db.execSQL("drop table if exists " + TABLE_Chapter);
        db.execSQL("drop table if exists " + TABLE_major_Character);
        onCreate(db);
    }
}

更新 我的插入方法

public void createBook(Books book){
        SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
        String newDate = s.format(new Date());
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(title, book.getTitle());
        values.put(description, book.getDescription());
        values.put(genre, book.getGenre());
        values.put(creation_dt, newDate);

        long book_id = db.insert(TABLE_Books, null, values);
    }

3 个答案:

答案 0 :(得分:1)

使用CursorAdapter代替ArrayAdapter,可以节省大量代码。

类似的东西:

String sqlQuery =
            "Select "
            + KEY_ID + ", "
            + title + ", "
            + description + ", "
            + genre + ", "
            + creation_dt + ", "
            + modification_dt
            + " From "
            + TABLE_Books;

    Cursor cursor = database.rawQuery(sqlQuery, null);

    String[] from = {KEY_ID, title}; // _id mandatory
    int[] to = new int[]{android.R.id.text1};

    CursorAdapter adapter = new SimpleCursorAdapter(
       context,
       android.R.layout.simple_list_item_1,
       cursor,
       from,
       to,
       CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

    ListView listView = ....
    listView.setAdapter(adapter);

答案 1 :(得分:1)

错误在setId中。This._id = _id它应该是This._id = Id

此外,键值为long而不是int 最佳做法是避免在cursor.getLong(0)上使用0

更改

book.setId(cursor.getInt(0));

cursor.getLong(cursor.getColumnIndexOrThrow(KEY_ID)); 

然后将getIdsetId方法签名更改为long。

所有更改后,课程书将如下:

public class Books {

    public long _id;

    ........

    public long getId(){ return _id;}
    public void setId(long Id){ this._id = Id;}

    ........
}

答案 2 :(得分:0)

itemList.add(cursorToBook(cursor));添加此代码段后,

Book testBook = itemList.get(itemList.size()-1);
Log.i("ID of recently inserted book is " + testBook.getId());

检查是否仍然打印值“0”。

AdapterView.AdapterContextMenuInfo的id是ListAdapter对象(在您的情况下为ArrayAdapter)中项目的rowid(即Book对象)。如果上面的Log.i打印出正确的id,那么不是使用ArrayAdapter,而是创建BaseAdapter的新子类(并正确覆盖getItemId方法)或者只使用CursorAdapter。

相关问题