android单选控件spinner与数据库结合综合实例

本示例说明:
1.实现单选按钮与后台数据绑定,通过Id绑定.

2.实现显示时默认选中项控制.

3.实现修改后保存,根据id保存.

4.数据库处理使用AHibernate1.1,详见: http://blog.csdn.net/lk_blog/article/details/8201449 

android使用Dialog实现复选功能与数据库结合综合实例见下篇博客: http://blog.csdn.net/lk_blog/article/details/8515403 

本示例效果图:




主要代码:spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="修改学生[李坤]所在班级" />

    <Spinner
        android:id="@+id/sprClass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
    <Button
        android:id="@+id/btnSave"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="保存"/>

</LinearLayout>
SpinnerActivity.java
package com.tgb.lk.demo;

import java.util.List;

import com.tgb.lk.demo.R;
import com.tgb.lk.demo.dao.impl.ClassesDaoImpl;
import com.tgb.lk.demo.dao.impl.StudentDaoImpl;
import com.tgb.lk.demo.model.Student;
import com.tgb.lk.demo.util.CItem;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinnerActivity extends Activity {
	private Spinner sprClass;
	private Button btnSave;

	private ClassesDaoImpl clsDao;
	private StudentDaoImpl stuDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.spinner);
		clsDao = (clsDao == null ? new ClassesDaoImpl(this) : clsDao);
		stuDao = (stuDao == null ? new StudentDaoImpl(this) : stuDao);

		sprClass = (Spinner) findViewById(R.id.sprClass);
		btnSave = (Button) findViewById(R.id.btnSave);
		btnSave.setOnClickListener(listener);

		List<CItem> items = clsDao.getCItemClasses();
		sprClass.setAdapter(buildSpinnerAdpater(this, items));
		sprClass.setPrompt("请选择");
		// 这个演示示例修改的学号为1的学生的信息,初始化数据中学号1没有自动生成主键,实际项目中可以根据查询的结果来传入id.
		int classesId = stuDao.get(1).getClassesId();
		setSpinnerInitId(sprClass, classesId, items);// 设置Spinner默认的选中项
	}

	// 得到spinner的选中的Id
	public int getSpinnerSelectId(Spinner spinner) {
		CItem item = (CItem) spinner.getSelectedItem();
		if (item != null) {
			return Integer.parseInt(item.getId());
		}
		return 0;
	}

	// 设置Spinner打开时默认的选中项
	public void setSpinnerInitId(Spinner spinner, int initId, List<CItem> items) {
		// 初始化默认选项
		if (initId != 0) {
			String id = String.valueOf(initId);
			for (int i = 0; i < items.size(); i++) {
				if (id.equals(items.get(i).getId())) {
					spinner.setSelection(i);// 设置默认选中项
					break;
				}
			}
		}

	}

	// 构建Spinner的Adapter
	public ArrayAdapter<CItem> buildSpinnerAdpater(Context context,
			List<CItem> list) {

		ArrayAdapter<CItem> adapter = new ArrayAdapter<CItem>(context,
				android.R.layout.simple_spinner_item, list);

		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		return adapter;
	}

	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnSave:
				stuDao = (stuDao == null ? new StudentDaoImpl(
						SpinnerActivity.this) : stuDao);
				// 这个演示示例修改的学号为1的学生的信息,初始化数据中学号1没有自动生成主键,实际项目中可以根据查询的结果来传入id.
				Student student = stuDao.get(1);
				student.setClassesId(getSpinnerSelectId(sprClass));// 设置学生所在班级的id.
				stuDao.update(student);// 调用AHibernate.jar中的修改方法.
				toastShow("保存成功!");
				SpinnerActivity.this.finish();// 关闭该Activity.
				break;
			default:
				break;
			}
		}
	};

	public void toastShow(String text) {
		Toast.makeText(this, text, 1000).show();
	}
}

其他代码:

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnInit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="初始化数据" />

    <Button
        android:id="@+id/btnSpinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="单选示例_修改学生所在班级" />

    <Button
        android:id="@+id/btnDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="多选示例_修改班级内学生" />

    <ListView
        android:id="@+id/lvStudent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
list.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/child"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:orientation="horizontal" >

    <!-- 若想隐藏id加入此属性: android:visibility="gone",这样做有点类似于Html中hidden域 -->

    <TextView
        android:id="@+id/idTo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff0000" />

    <TextView
        android:id="@+id/nameTo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="5px"
        android:paddingLeft="50px"
        android:paddingTop="5px"
        android:text="No data"
        android:textColor="#0000ff"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/classTo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="5px"
        android:paddingLeft="50px"
        android:paddingTop="5px"
        android:text="No data"
        android:textColor="#00ff00"
        android:textSize="20sp" />

</LinearLayout>

MainActivity.java:

package com.tgb.lk.demo;

import java.util.List;
import java.util.Map;

import com.tgb.lk.demo.dao.impl.ClassesDaoImpl;
import com.tgb.lk.demo.dao.impl.StudentDaoImpl;
import com.tgb.lk.demo.model.Classes;
import com.tgb.lk.demo.model.Student;
import com.tgb.lk.demo.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button btnInit;
	private Button btnSpinner;
	private Button btnDialog;
	private StudentDaoImpl stuDao;
	private ClassesDaoImpl classDao;
	private ListView lv = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btnInit = (Button) findViewById(R.id.btnInit);
		btnSpinner = (Button) findViewById(R.id.btnSpinner);
		btnDialog = (Button) findViewById(R.id.btnDialog);
		btnInit.setOnClickListener(listener);
		btnSpinner.setOnClickListener(listener);
		btnDialog.setOnClickListener(listener);

		lv = (ListView) findViewById(R.id.lvStudent);
		showData();
	}

	// 按钮事件处理
	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// 初始化数据
			case R.id.btnInit:
				System.out.println("btnInit");
				initData();// 初始化数据
				showData();
				break;
			case R.id.btnSpinner:// 打开spinner示例
				Intent sprIntent = new Intent();
				sprIntent.setClass(MainActivity.this, SpinnerActivity.class);
				startActivityForResult(sprIntent, 1);
				toastShow("单选示例");
				break;
			case R.id.btnDialog:// 打开Dialog示例
				Intent dlgIntent = new Intent();
				dlgIntent.setClass(MainActivity.this, DialogActivity.class);
				startActivityForResult(dlgIntent, 1);
				toastShow("多选示例");
				break;
			default:
				break;
			}

		}
	};

	// 数据库处理引用jar包AHibernate1.1处理.
	// AHibernate的详细使用教程示例地址:
	// http://blog.csdn.net/lk_blog/article/details/8201449
	// jar和源码下载地址:http://download.csdn.net/download/lk_blog/4786640
	private void initData() {
		classDao = (classDao == null ? new ClassesDaoImpl(this) : classDao);
		classDao.deleteAll();// 删除所有班级

		Classes cls1 = new Classes();
		cls1.setId(1);
		cls1.setName("四期提高班");
		// 调用insert(cls1)主键自增,调用insert(cls1,false)主键不自增须指定;
		classDao.insert(cls1, false);

		Classes cls2 = new Classes();
		cls2.setId(2);
		cls2.setName("五期提高班");
		Long clsId2 = classDao.insert(cls2, false);

		Classes cls3 = new Classes();
		cls3.setName("六期提高班");
		classDao.insert(cls3);// 主键自增

		stuDao = (stuDao == null ? new StudentDaoImpl(this) : stuDao);
		stuDao.deleteAll();// 删除所有学生

		Student student1 = new Student();
		student1.setId(1);
		student1.setName("李坤");
		student1.setClassesId(clsId2.intValue());
		stuDao.insert(student1, false);

		Student student2 = new Student();
		student2.setId(2);
		student2.setName("曹贵生");
		student2.setClassesId(clsId2.intValue());
		stuDao.insert(student2, false);

		Student student3 = new Student();
		student3.setName("柳波");
		student3.setClassesId(clsId2.intValue());
		stuDao.insert(student3);
		toastShow("初始化数据完成!");

	}

	public void toastShow(String text) {
		Toast.makeText(this, text, 1000).show();
	}

	private void showData() {
		stuDao = (stuDao == null ? new StudentDaoImpl(this) : stuDao);
		List<Map<String, String>> data = null;
		data = stuDao.queryAllStudent();
		SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.list,
				new String[] { "id", "stu_name", "cls_name" }, new int[] {
						R.id.idTo, R.id.nameTo, R.id.classTo });
		lv.setAdapter(adapter);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		showData();
	}

}
CItem.java:
package com.tgb.lk.demo.util;
//处理单选和多选框的工具实体类
public class CItem implements Cloneable{

	private String id = "";
	private String value = "";
	private boolean flag = false;//控制多选框默认是否选中状态.

	public CItem() {
	}

	public CItem(String _ID, String _Value) {
		id = _ID;
		value = _Value;
	}

	@Override
	public String toString() {
		// 这个必须重写才能保证显示正常,因为适配器在显示数据的时候,如果传入适配器的对象不是字符串的情况下,直接就使用对象.toString()
		return value;
	}

	public String getId() {
		return id;
	}

	public String getValue() {
		return value;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public boolean getFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

}
StudentDaoImpl.java:
package com.tgb.lk.demo.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.tgb.lk.ahibernate.dao.impl.BaseDaoImpl;
import com.tgb.lk.demo.model.Student;
import com.tgb.lk.demo.util.CItem;
import com.tgb.lk.demo.util.DBHelper;

import android.content.Context;

//本文数据库处理引用jar包AHibernate1.1处理.
//AHibernate的详细使用教程示例地址: http://blog.csdn.net/lk_blog/article/details/7455992
//AHibernate源码交流地址: http://blog.csdn.net/lk_blog/article/details/7456125
//AHibernate jar包下载及源代码下载地址: http://download.csdn.net/detail/lk_blog/4222048
public class StudentDaoImpl extends BaseDaoImpl<Student> {
	public StudentDaoImpl(Context context) {
		super(new DBHelper(context), Student.class);
	}

	public List<CItem> getCItemStudents(int classId) {
		String sql = "select _id,name,classesid from t_student";
		List<Map<String, String>> list = query2MapList(sql, null);
		List<CItem> retList = new ArrayList<CItem>();
		for (Map<String, String> map : list) {
			CItem item = new CItem();
			item.setId(map.get("_id"));
			item.setValue(map.get("name"));
			item
					.setFlag(map.get("classesid").equals(
							String.valueOf(classId)) ? true : false);
			retList.add(item);
		}
		return retList;
	}
	
	// 返回一个List,List中的对象是以sql中的列的小写形式为key的Map.(本例中 _id,name,classes为key)
	public List<Map<String, String>> queryAllStudent() {
		String sql = "select s._id id, s.name stu_name,c.name cls_name from t_student s left join t_classes c on s.classesid = c._id";
		return super.query2MapList(sql, null);
	}

	public void deleteAll() {
		super.execSql("delete from t_student", null);
	}
}
源代码下载地址: http://download.csdn.net/detail/lk_blog/5005962

限于本人水平有限,很多地方写的并不完美,希望大家不吝赐教.如果觉得本文对您有帮助请顶支持一下,如果有不足之处欢迎留言交流,希望在和大家的交流中得到提高.

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值