首页 > 代码库 > 赵雅智_SimpleCursorAdapter

赵雅智_SimpleCursorAdapter

项目步骤

  1. 声明listView控件并获取显示的视图
  2. 获取显示的数据
  3. 设置显示的adapter
  4. 注册点击事件

具体案例

实现效果:

查找的方法

	public Cursor findCursor() {

		SQLiteDatabase db = dh.getWritableDatabase();
		Cursor c = db
				.rawQuery(
						"select userid as _id,username,userage,usersalary,userphone from users",
						null);
		return c;
	}


布局文件

同BaseAdapter的布局文件activity_main.xml
http://blog.csdn.net/zhaoyazhi2129/article/details/29636669

ArrayAdapter实现类(主程序)

package com.example.android_sqlite;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.example.android_sqlite.dao.impl.UserDaoImpls;
import com.example.android_sqlite.database.DatabaseHelper;

/**
 * SimpleCursorAdapter
 * 
 * @author zhaoyazhi
 * 
 */
public class MainActivitysss extends Activity implements OnItemClickListener {
	private ListView lv_users;// 视图层

	// model层 相关的对象的声明
	private DatabaseHelper dh;
	private UserDaoImpls userDao;
	private Cursor c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 创建数据库
		dh = new DatabaseHelper(this);
		// 获取显示数据 model
		userDao = new UserDaoImpls(dh);
		// 查询获取数据
		c = userDao.findCursor();
		// 设置视图层
		lv_users = (ListView) findViewById(R.id.lv_users);

		// 上下文对象,资源文件,数据,显示的字段,显示的字段插入位置
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.item_phone, c, new String[] { "username", "userphone",
						"_id", "userage" }, new int[] { R.id.tv_name,
						R.id.tv_phone, R.id.tv_id, R.id.tv_age });

		// adapter作为控制层
		lv_users.setAdapter(adapter);

		// 注册点击事件
		lv_users.setOnItemClickListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long arg3) {

		// 获取点击我的数据
		Toast.makeText(this, parent.getItemAtPosition(position) + "", 0).show();

	}

}


注意:


用Cursor查询必须给userid取_id的别名