SimpleCursorAdapter 原理和实例
SimpleCursorAdapter
1. 原理参见下面代码注释
Cursor cursor = dbHelper.fetchAllCountries(); //cursor中存储需要加载到listView中的条目,可能由一行或者多行组成。每一行可能包含多列数据(多于listview中定义的) //the desired columns to be bound
String[] columns = new String[] {
CountryDb.KEY_CODE,
CountryDb.KEY_NAME,
CountryDb.KEY_CONTINENT
}; //这个数据结构指定cursor中的那些列将显示到listview每一行中(从多列中挑选需要的) //the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code,
R.id.name,
R.id.continent
};//这个数据结构定义listview中各组件的id,由此和上面的的colums形成了map关系,即cursor中某一行的列字段映射到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控件名
cursor, //所存数据的cursor
columns,//cursor需要的字段定义
to, //映射到XML每个控件的定义
0); ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter); //设置adapter,所有cursor中的数据将自动加载
2. 附上一个通过实现SimpleCursorAdapter getView()方法设置行背景颜色的例子
该例子通过检索SQLite数据库构建了基本的listView,但是默认的listView的行条目是不带有斑马线的(相邻行背景颜色不同)。通过继承SimpleCursorAdapter并实现getView()方法可以达到目的。
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="Medium 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);
} @Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(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.execSQL("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, null, 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 原理和实例的更多相关文章
- MATLAB神经网络原理与实例精解视频教程
教程内容:<MATLAB神经网络原理与实例精解>随书附带源程序.rar9.随机神经网络.rar8.反馈神经网络.rar7.自组织竞争神经网络.rar6.径向基函数网络.rar5.BP神经网 ...
- Camera图像处理原理及实例分析-重要图像概念
Camera图像处理原理及实例分析 作者:刘旭晖 colorant@163.com 转载请注明出处 BLOG:http://blog.csdn.net/colorant/ 主页:http://rg ...
- 分布式一致性协议Raft原理与实例
分布式一致性协议Raft原理与实例 1.Raft协议 1.1 Raft简介 Raft是由Stanford提出的一种更易理解的一致性算法,意在取代目前广为使用的Paxos算法.目前,在各种主流语言中都有 ...
- C语言与汇编语言相互调用原理以及实例
C语言与汇编语言相互调用原理以及实例 1.原理 其实不管是C语言还是汇编语言想要执行都是最终编译链接成为二进制文件. 这里一定要明确编译和链接是两个步骤,生成的文件格式也是不一样的. 编译生成的文件是 ...
- Webservice工作原理及实例
Web Service工作原理及实例 一.Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从Internet或者In ...
- Camera图像处理原理及实例分析
Camera图像处理原理及实例分析 作者:刘旭晖 colorant@163.com 转载请注明出处 BLOG:http://blog.csdn.net/colorant/ 主页:http://rg ...
- Jsonp跨域访问原理和实例
>>什么是跨域 出于安全方面的考虑,页面中的JavaScript无法访问其他服务器上的数据,当前域名的js只能读取同域下的窗口属性,即同源策略.而跨域就是通过某些手段来绕过同源策略限制,实 ...
- js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)
最近做了一个项目,需要用子域名调用主域名下的一个现有的功能,于是想到了用jsonp来解决,在我们平常的项目中不乏有这种需求的朋友,于是记录下来以便以后查阅同时也希望能帮到大家,需要了解的朋友可以参考下 ...
- Android Touch事件原理加实例分析
Android中有各种各样的事件,以响应用户的操作.这些事件可以分为按键事件和触屏事件.而Touch事件是触屏事件的基础事件,在进行Android开发时经常会用到,所以非常有必要深入理解它的原理机制. ...
随机推荐
- 32、最长有效括号 | 算法(leetode,附思维导图 + 全部解法)300题
零 标题:算法(leetode,附思维导图 + 全部解法)300题之(32)最长有效括号 一 题目描述 二 解法总览(思维导图) 三 全部解法 1 方案1 1)代码: // 方案1 "滑动窗 ...
- 5.基于二进制部署kubernetes(k8s)集群
1 kubernetes组件 1.1 Kubernetes 集群图 官网集群架构图 1.2 组件及功能 1.2.1 控制组件(Control Plane Components) 控制组件对集群做出全局 ...
- 如何在Docker容器中使用Arthas
Arthas(阿尔萨斯) 能为你做什么? Arthas 是Alibaba开源的Java诊断工具,深受开发者喜爱. 当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决: 这个类从哪个 jar ...
- CF1004D Sonya and Matrix
不要想当然. 考虑到我们一定有存在个数为\(4\)的倍数的数. 否则第一个不是的数即为\(x\). 那么我们设\(b\)为所有的数的最大值. 那么显然有\(|n - x| + |m - y| = b\ ...
- CF1542E2 Abnormal Permutation Pairs (hard version)
CF1542E2 Abnormal Permutation Pairs (hard version) good tea. 对于两个排列 \(p,q\),如果 \(p\) 的字典序小于 \(q\),则要 ...
- R语言矩阵相关性计算及其可视化?
目录 1. 矩阵相关性计算方法 base::cor/cor.test psych::corr.test Hmisc::rcorr 其他工具 2. 相关性矩阵转化为两两相关 3. 可视化 corrplo ...
- Atom编辑器速查
简介 Atom 是 Github 开源的文本编辑器,相当于半个IDE.其特点如下: (1)免费开源,多平台支持(Windows.Mac.Linux): (2)界面美观.现代化,使用舒适: (3)多文件 ...
- centos yum安装mongodb,php扩展
一,安装mongodb,php扩展 ? 1 [root@localhost ~]# yum install php-pecl-mongo mongodb mongodb-devel mongodb-s ...
- PC端申请表
公司项目需求中要做用html做一个PDF申请表的样式出来.有点意思,贴上来大家看看. 先上效果图: 附上源代码: HTML:<div id="form"> <h2 ...
- 商业创新不能等?用友低代码开发平台YonBuilder为您加速!
随着云计算.人工智能.物联网.大数据.5G等新一代技术的快速发展,越来越多的企业希望借助技术的力量加速数智化转型,期许通过更加敏捷和强大的应用系统推动企业的商业创新速度.但传统软件开发周期长.开发成本 ...