1、数据的获取
@Override
public List<User> findAll() {
List<User> entities=new ArrayList<User>();
SQLiteDatabase db=databaseHelper.getWritableDatabase();
Cursor c=db.rawQuery("select userid,username,userage,usersalary,userphone from user",null);
while(c.moveToNext()){
User entity=new User();
entity.setUserId(c.getInt(c.getColumnIndex("userid")));
entity.setUserName(c.getString(c.getColumnIndex("username")));
entity.setUserAge(c.getInt(c.getColumnIndex("userage")));
entity.setUserSalary(c.getDouble(c.getColumnIndex("usersalary")));
entity.setUserPhone(c.getString(c.getColumnIndex("userphone")));
entities.add(entity);
}
db.close();
return entities;
}
2、MVC层的实现
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置显示的视图
setContentView(R.layout.activity_main);
// 获取显示的控件对象
lv_user = (ListView) findViewById(R.id.lv_user);// 视图层V
databaseHelper = new DatabaseHelper(this);
userDao = new UserDaoImpl(databaseHelper);
// 获取显示的数据
entities = userDao.findAll();
// 创建自定义的adapter对象
MyAdapter adapter = new MyAdapter();
// adapter作为控制层
lv_user.setAdapter(adapter);
lv_user.setOnItemClickListener(this);
}
// 继承了BaseAdapter 这个BaseAdapter类实现了ListAdapter接口
// 控制层C
class MyAdapter extends BaseAdapter {
// 返回总条目的数量
@Override
public int getCount() {
// TODO Auto-generated method stub
return entities.size();
}
//返回当前条目对应的对象
@Override
public Object getItem(int position) {
return entities.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
// 返回每个条目
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 系统定义的item布局
// 注意:对应的布局中choiceMode(无关)
// return singleChoice(position);
//return multipleChoice(position);
// 自定义item布局
User entity = entities.get(position);
View v = View.inflate(MainActivity_myadaptor.this, R.layout.list_item_user,
null);
TextView tv_id = (TextView) v.findViewById(R.id.tv_id);
TextView tv_name = (TextView) v.findViewById(R.id.tv_name);
TextView tv_age = (TextView) v.findViewById(R.id.tv_age);
TextView tv_phone = (TextView) v.findViewById(R.id.tv_phone);
tv_id.setText("" + entity.getUserId());
tv_name.setText("姓名:" + entity.getUserName());
tv_age.setText("年龄:" + entity.getUserAge());
tv_phone.setText("电话:" + entity.getUserPhone());
return v;
}
3、结果显示