Combination of simplecursoradapter and listview

Source: Internet
Author: User

The cursor is often used when we use SQLite to query data. We hope to bind the data pointed to by the cursor to the listview directly, this eliminates the trouble of retrieving and converting cursor data to simpleadapter. Today, we will demonstrate how to use this adapter.

Idea: Execute the query operation using the traditional method, return a cursor, put the cursor into the simplecursoraapter constructor, and finally setadapter

Mainactivity. Java

package com.kale.cursoradapter;import android.app.Activity;import android.database.Cursor;import android.os.Bundle;import android.widget.ListView;import android.widget.SimpleCursorAdapter;public class MainActivity extends Activity {    DatabaseManager dbManager;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //得到一个数据层操作对象        dbManager = new DatabaseManager(this);        //因为在数据库建立的时候我们已经建立一个表了,所以这里就可以直接插入数据了        String insertSql = "insert into test_table (name,age) values(‘kale‘,20)";        //用循环的方式来插入20条数据        for (int i = 0; i < 20; i++) {            dbManager.executeSql(insertSql);        }
// 这个游标查询到的数据中必须有一个列名为_id否则会报错,所以写sql语句的时候必须要查到_id。显不显示这个id到无所谓 String sql = "select _id,name,age from test_table";
//得到一个Cursor,这个将要放入适配器中 Cursor cursor = dbManager.executeSql(sql, null); // 最后一个参数flags是一个标识,标识当数据改变调用onContentChanged()的时候,是 // 否通知ContentProvider数据的改变,如果无需监听ContentProvider的改变,则可以传0。 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, new String[] { "name", "age" }, new int[] { R.id.name, R.id.age }, 0); ListView listView = (ListView) findViewById(R.id.listView); listView.setAdapter(adapter); }}

 

Note: The queried data must have a column named _ id. Otherwise, an error is returned. Therefore, this column should be created during table creation.

 

 

The following two classes are basically copied directly from my previous articles for future use.

Database Object Class-databasemanager

package com.kale.cursoradapter;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteException;public class DatabaseManager{         DatabaseHelper mDbHelper = null;       //操作数据库的实例     static SQLiteDatabase mDb = null;       Context mContext = null;            public DatabaseManager(Context context) {         mContext = context;           mDbHelper = DatabaseHelper.getInstance(mContext);           mDb= mDbHelper.getReadableDatabase();     }          /**     * 建立表     * SQLite内部只支持NULL,INTEGER,REAL(浮点),TEXT(文本),BLOB(大二进制)5种数据类型     * 建立表成功了,返回true     */    public boolean executeSql(String sql){         try {             mDb.execSQL(sql);             return true;         }         catch(SQLiteException e){            return false;         }     }        public Cursor executeSql(String sql,String[]args){         try {             return mDb.rawQuery(sql, args);         }         catch(SQLiteException e){             e.printStackTrace();         }         return null;     }        /**     * 关闭连接      */    public void closeDBhelper() {        if (mDbHelper != null) {            mDbHelper.close();        }    }     }

 

Databasehelper

package com.kale.cursoradapter;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DatabaseHelper extends SQLiteOpenHelper{        private static DatabaseHelper mInstance = null;    //数据库名字    public static final String DATABASE_NAME = "SQLite_db";    //版本号    private static final int DATABASE_VERSION = 1;    //建立默认表的语句,必须有_id这个列    private static final String CREAT_TABLE_TABLE_SQL = "create table test_table("            + "_id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT,age INTEGER);";        public DatabaseHelper(Context context) {        super(context, DATABASE_NAME, null, DATABASE_VERSION);    }            public DatabaseHelper(Context context, String name, int version) {        super(context, name, null, version);    }            public static synchronized DatabaseHelper getInstance(Context context) {        if (mInstance == null) {            mInstance = new DatabaseHelper(context);        }        return mInstance;    }    /*      * 初次使用时创建数据库表     */    @Override    public void onCreate(SQLiteDatabase db) {        //通过sql语句建立默认表        db.execSQL(CREAT_TABLE_TABLE_SQL);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        /**可以拿到当前数据库的版本信息 与之前数据库的版本信息   如果不同,那么就更新数据库**/            }    //删除数据库    public boolean deleteDatabase(Context context , String databaseName) {        return context.deleteDatabase(databaseName);    }}

 

Source code download: http://download.csdn.net/detail/shark0017/8026895

 

combination of simplecursoradapter and listview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.