1. 程式人生 > >android單選控制元件spinner與資料庫結合綜合例項

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
限於本人水平有限,很多地方寫的並不完美,希望大家不吝賜教.如果覺得本文對您有幫助請頂支援一下,如果有不足之處歡迎留言交流,希望在和大家的交流中得到提高.