SimpleCursorAdapter principles and examples

Source: Internet
Author: User
Tags sqlite database sqlite db
SimpleCursorAdapter

1. For the principle, see the following code comments.

Cursor cursor = dbHelper. fetchAllCountries (); // The entries stored in the cursor that need to be loaded into the listView may consist of one or more rows. Each row may contain multiple columns of data (more than defined in listview) // the desired columns to be bound String [] columns = new String [] {CountryDb. KEY_CODE, CountryDb. KEY_NAME, CountryDb. KEY_CONTINENT}; // This data structure specifies that the columns in the cursor will be displayed in each row of the listview (select from multiple columns) // the XML defined views which the data will be bound to int [] to = new int [] {R. id. code, R. id. name, R. id. continent}; // This data structure defines the IDs of each component in the listview, which forms a map relationship with the colums above, that is, the column field of a row in cursor is mapped to the control in listview // create the adapter using the cursor pointing to the desired data // as well as the layout information SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter (this, r. layout. list_row, // listView xml control name cursor, // cursor columns of stored data, // field definition required by cursor to, // ING to definition 0 of each control in XML ); listView listView = (ListView) findViewById (R. id. listView1); // Assign adapter to ListView listView. setAdapter (dataAdapter); // Set the adapter. Data in all cursor is automatically loaded.
2. Attach an example of setting the row background color by implementing SimpleCursorAdapter getView ().

In this example, the basic listView is constructed by searching the SQLite database, but the row entries of the default listView do not carry a zebra line (the background color of adjacent rows is different ). You can achieve this by inheriting SimpleCursorAdapter and implementing the getView () method.

Main Activity Layout-activity_main.xml
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" tools: context = ". mainActivity "android: padding =" 10dp "> <ListView android: id =" @ + id/listView1 "android: layout_width =" match_parent "android: layout_height =" wrap_content "android: layout_alignParentLeft = "true" android: layout_alignParentTop = "true"> </ListView> </RelativeLayout>
ListView Row Layout-list_row.xml
<? Xml version = "1.0" encoding = "UTF-8"?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: orientation = "vertical" android: padding = "5dip"> <TextView android: id = "@ + id/name" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_alignParentLeft = "true" android: layout_alignParentTop = "true" android: text = "Med Ium Text "android: textAppearance = "? Android: attr/textAppearanceMedium "android: textStyle =" bold "/> <TextView android: id =" @ + id/textView1 "android: layout_width =" wrap_content "android: layout_height = "wrap_content" android: layout_alignBottom = "@ + id/name" android: layout_toRightOf = "@ + id/name" android: text = "-" android: textAppearance = "? Android: attr/textAppearanceMedium "/> <TextView android: id =" @ + id/code "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentTop = "true" android: layout_toRightOf = "@ + id/textView1" android: text = "Medium Text" android: textAppearance = "? Android: attr/textAppearanceMedium "/> <TextView android: id =" @ + id/textView2 "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignParentBottom = "false" android: layout_alignParentLeft = "true" android: layout_below = "@ id/name" android: text = "Continent is" android: textAppearance = "? Android: attr/textAppearanceMedium "/> <TextView android: id =" @ + id/continent "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: layout_alignBaseline = "@ + id/textView2" android: layout_alignBottom = "@ + id/textView2" android: layout_toRightOf = "@ + id/textView2" android: text = "Medium Text" android: textAppearance = "? Android: attr/textAppearanceMedium "/> </RelativeLayout>
Country POJO-Country. java
Package com. as400samplecode; public class Country {String code = null; String name = null; String continent = null; public String getCode () {return code;} public void setCode (String code) {this. code = code;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getContinent () {return continent;} public void setContinent (String continent) {this. continent = continent ;}}
Country SQLite Db Adapter-CountryDb. java
Package com. as400samplecode; import android. content. contentValues; import android. content. context; import android. database. cursor; import android. database. SQLException; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteOpenHelper; import android. util. log; public class CountryDb {public static final String KEY_ROWID = "_ id"; public static final String KEY_CODE = "code "; Public static final String KEY_NAME = "name"; public static final String KEY_CONTINENT = "continent"; private static final String TAG = "CountriesDbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "World"; private static final String SQLITE_TABLE = "Country"; private static final int DATABASE_VERSION = 1; private final Context mCtx ; Private static final String DATABASE_CREATE = "create table if not exists" + SQLITE_TABLE + "(" + KEY_ROWID + "integer primary key autoincrement," + KEY_CODE + ", "+ KEY_NAME +", "+ KEY_CONTINENT +", "+" UNIQUE ("+ KEY_CODE +"); "; private static class DatabaseHelper extends SQLiteOpenHelper {DatabaseHelper (Context context) {super (context, DATABASE_NAME, null, DATABASE_VERSION) ;}@ Over Ride public void onCreate (SQLiteDatabase db) {Log. w (TAG, DATABASE_CREATE); db.exe cSQL (DATABASE_CREATE) ;}@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {Log. w (TAG, "Upgrading database from version" + oldVersion + "to" + newVersion + ", which will destroy all old data "); db.exe cSQL ("drop table if exists" + SQLITE_TABLE); onCreate (db) ;}} public CountryDb ( Context ctx) {this. mCtx = ctx;} public CountryDb open () throws SQLException {mDbHelper = new DatabaseHelper (mCtx); mDb = mDbHelper. getWritableDatabase (); return this;} public void close () {if (mDbHelper! = Null) {mDbHelper. close () ;}} public long createCountry (String code, String name, String continent) {ContentValues initialValues = new ContentValues (); initialValues. put (KEY_CODE, code); initialValues. put (KEY_NAME, name); initialValues. put (KEY_CONTINENT, continent); return mDb. insert (SQLITE_TABLE, null, initialValues);} public boolean deleteAllCountries () {int doneDelete = 0; doneDelete = mDb . Delete (SQLITE_TABLE, null, null); Log. w (TAG, Integer. toString (doneDelete); return doneDelete> 0;} public Cursor fetchAllCountries () {Cursor mCursor = mDb. query (SQLITE_TABLE, new String [] {KEY_ROWID, KEY_CODE, KEY_NAME, KEY_CONTINENT}, null, null); if (mCursor! = Null) {mCursor. moveToFirst ();} return mCursor;} public void insertSomeCountries () {createCountry ("AFG", "Afghanistan", "Asia"); createCountry ("CHN", "China ", "Asia"); createCountry ("ALB", "Albania", "Europe"); createCountry ("DZA", "Algeria", "Africa "); createCountry ("ASM", "American Samoa", "Oceania"); createCountry ("AND", "Andorra", "Europe"); createCountry ("AGO ", "Angola", "Africa"); createCountry ("AIA", "Anguilla", "North America"); createCountry ("USA", "United States ", "North America"); createCountry ("CAN", "Canada", "North America ");}}
Android Main Activity-MainActivity. java
Package com. as400samplecode; import android. OS. bundle; import android. app. activity; import android. content. context; import android. database. cursor; import android. graphics. color; import android. view. menu; import android. view. view; import android. view. viewGroup; import android. widget. listView; import android. widget. simpleCursorAdapter; public class MainActivity extends Activity {private CountryDb dbHelper; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); dbHelper = new CountryDb (this); dbHelper. open (); // Clean all data dbHelper. deleteAllCountries (); // Add some data dbHelper. insertSomeCountries (); // Generate ListView from SQLite Database displayListView () ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. activity_main, menu); return true;} private void displayListView () {Cursor cursor = dbHelper. fetchAllCountries (); // the desired columns to be bound String [] columns = new String [] {CountryDb. KEY_CODE, CountryDb. KEY_NAME, CountryDb. KEY_CONTINENT}; // the XML defined views which the data will be bound to int [] to = new int [] {R. id. code, R. id. name, R. id. continent}; // create the adapter using the cursor pointing to the desired data // as well as the layout information MyCursorAdapter dataAdapter = new MyCursorAdapter (this, R. layout. list_row, cursor, columns, to, 0); ListView listView = (ListView) findViewById (R. id. listView1); // Assign adapter to ListView listView. setAdapter (dataAdapter );} // extend the SimpleCursorAdapter to create a custom class where we // can override the getView to change the row colors private class MyCursorAdapter extends SimpleCursorAdapter {public MyCursorAdapter (Context context, int layout, cursor c, String [] from, int [] to, int flags) {super (context, layout, c, from, to, flags );} @ Override public View getView (int position, View convertView, ViewGroup parent) {// get reference to the row View view = super. getView (position, convertView, parent); // check for odd or even to set alternate colors to the row background if (position % 2 = 0) {view. setBackgroundColor (Color. rgb (238,233,233);} else {view. setBackgroundColor (Color. rgb (255,255,255) ;}return view ;}}}

 

SimpleCursorAdapter principles and examples

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.