Make listview from SQLite database

耗尽温柔 提交于 2019-12-02 05:32:30

The best way to do this is to use a CursorAdapter or a SimpleCursorAdapter. This will give you the best performance and once you figure it out you'll find it's the simplest approach when using a SQLite db.

http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html

Below is a simple CustomCursorAdapter that I use frequently. Just add the CustomCursorAdapter class as an inner class.

    protected class CustomCursorAdapter extends SimpleCursorAdapter  {
        private int layout; 
        private LayoutInflater inflater;
        private Context context;

        public CustomCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) {
            super(context, layout, c, from, to);
            this.layout = layout;
            this.context = context;
            inflater = LayoutInflater.from(context);

        }


        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            Log.i("NewView", newViewCount.toString());

            View v = inflater.inflate(R.layout.list_cell, parent, false);

            return v;
        }

        @Override
        public void bindView(View v, Context context, Cursor c) {
                    //1 is the column where you're getting your data from
            String name = c.getString(1);
            /**
             * Next set the name of the entry.
             */
            TextView name_text = (TextView) v.findViewById(R.id.textView);
            if (name_text != null) {
                name_text.setText(name);
            }   
        }

Create an instance of the CustomCursorAdapter like so... You'll need to create your cursor just like you're already doing.

protected String[] from;
protected int[] to;

    //From is the column name in your cursor where you're getting the data
    //to is the id of the view it will map to
    from = new String[]{"name"};
    to = new int[]{R.id.textView};

CustomCursorAdapter adapter = new CustomCursorAdapter(this, R.layout.list, cursor, from, to);
listView.setAdapter(adapter);

I found working with the notepad tutorial very useful for learning about this. It shows you how to implement the listview using the sqlite database in very easy steps.

http://developer.android.com/resources/tutorials/notepad/index.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!