如何根据android中的数据库填充listview

时间:2015-01-29 10:56:36

标签: android android-layout

我正在上课以获取所有MessageThread:

public List<ChatMessageThread> getAllMessageThread() {

        List<ChatMessageThread> chatMessageThreads = new ArrayList<ChatMessageThread>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_ChatMessageThread;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                ChatMessageThread td = new ChatMessageThread();
                td.setChatMessageThreadId(c.getInt((c.getColumnIndex(KEY_ChatMessageThreadId))));
                td.setMessageThreadTitle((c.getString(c.getColumnIndex(KEY_MessageThreadTitle))));
                td.setMessageThreadURL(c.getString(c.getColumnIndex(KEY_MessageThreadURL)));
                td.setMessageThreadSnippet(c.getString(c.getColumnIndex(KEY_MessageThreadSnippet)));

                // Adding contact to list
                chatMessageThreads.add(td);
            } while (c.moveToNext());
        }
        return chatMessageThreads;
    }

如何在布局文件

中的ListView的列表视图中填充此列表

1 个答案:

答案 0 :(得分:0)

我使用这种方法:

private void populateListView() {
        ArrayAdapter<ChatMessageThread> adapter = new MyListAdapter();
        ListView list = (ListView) findViewById(R.id.lv);
        list.setAdapter(null);
        list.setAdapter(adapter);
    }

也是MyListAdapter方法:

private class MyListAdapter extends ArrayAdapter<ChatMessageThread> {
        public MyListAdapter() {
            super(MainActivity.this, R.layout.listitem, ChatMessageThreadObject);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Make sure we have a view to work with (may have been given null)
            View itemView = convertView;
            if (itemView == null) {
                itemView = getLayoutInflater().inflate(R.layout.listitem,
                        parent, false);
            }

            // Find the object to work with
            ChatMessageThread working_object = ChatMessageThreadObject.get(position);

            // set a textview from the listitem layout
            TextView startTime = (TextView) itemView
                    .findViewById(R.id.t_v_startTime);
            startTime.setText(working_object.getID());
            return itemView;
        }
    }

P.S。我编辑了我的对象来引用你的答案。我希望这可以帮助你:)