Make listview from SQLite database

后端 未结 2 2087
小蘑菇
小蘑菇 2021-01-25 06:04

I\'m trying to populate listview from my SQLite database... this is how I get my data from database:

    Cursor c = database.rawQuery(\"SELECT * FROM \" + TableN         


        
相关标签:
2条回答
  • 2021-01-25 06:26

    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

    0 讨论(0)
  • 2021-01-25 06:28

    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);
    
    0 讨论(0)
提交回复
热议问题