Android利用Spinner从数据库中读取数据并实现2级互动

以前学习Java EE的时候,经常会遇到一些下拉表单进行联动的实例。

例子:假如一个公司有三个部门,括号里面是职位

人力资源部(员工关系主管,招聘主管 )

财务部(财务总监、财务部经理、审计主管)

生产技术部(程序员,设计师,架构师)


我们将做个两级联动的spinner,当我第一级选择不同的部门,第二级将显示不同的职位


SQLiteOpenHelper类:

package org.jian.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "martin.db" ;
    private static final int VERSION = 3 ;
    
    SQLiteDatabase db ;
    private String job_sql = "CREATE TABLE IF NOT EXISTS job(" +
                             "_id INTEGER PRIMARY KEY ," +
                             "jobname VARCHAR(20) ," +
                             "did INTEGER" +
                             ")" ;
    private String dept_sql = "CREATE TABLE IF NOT EXISTS dept(" +
                              "_id INTEGER PRIMARY KEY ," +
                              "deptname VARCHAR(20)" +
                              ")" ;
    
    public DBHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        this.db = db ;
        db.execSQL(job_sql) ;
        db.execSQL(dept_sql) ;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        
    }

}




用sql插入数据(在sqlite里,用adb进入):

INSERT INTO job VALUES(null ,"员工关系主管" , 1) ;
INSERT INTO job VALUES(null ,"招聘主管 " , 1) ;
INSERT INTO job VALUES(null ,"财务总监" , 2) ;
INSERT INTO job VALUES(null ,"财务部经理" , 2) ;
INSERT INTO job VALUES(null ,"审计主管" , 2) ;
INSERT INTO job VALUES(null ,"程序员" , 3) ;
INSERT INTO job VALUES(null ,"设计师" , 3) ;
INSERT INTO job VALUES(null ,"架构师" , 3) ;

INSERT INTO dept VALUES(null ,"人力资源部" ) ;
INSERT INTO dept VALUES(null ,"财务部" ) ;
INSERT INTO dept VALUES(null ,"生产技术部" ) ;

处理数据的类:

package org.jian.service;

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

import org.jian.database.DBHelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Database {
    private DBHelper dbHelper;

    public Database(Context context) {
        dbHelper = new DBHelper(context);
    }

    /**
     * 查询数据库,返回一个Map 这个Map包括 1,spinner需要显示的字符串,以及其所组成的map 2,spinner需要显示的字符串
     * 
     * @return
     */
    public Map> getDepts() {
        String sql = "SELECT _id, deptname FROM dept";   //获取部门Id号与部门的名称
        SQLiteDatabase db = null;
        Cursor c = null;
        Map> DeptData = new HashMap>();
        try {
            db = dbHelper.getWritableDatabase(); // 获取数据库
            c = db.rawQuery(sql, null);
            List> collegeList1 = new ArrayList>();
            List collegeList2 = new ArrayList();
            while (c.moveToNext()) {
                Map provinceMap = new HashMap(); // 这个HashMap主要是用来白村学院的信息以及他的id
                String name = new String(c.getBlob(1), "GBK");
                provinceMap.put(name, c.getInt(0));
                collegeList1.add(provinceMap); // 保存这个Map
                collegeList2.add(name); // 保存这个名字的列表
            }
            DeptData.put(0, collegeList1);
            DeptData.put(1, collegeList2);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return DeptData;
    }

    /**
     * 返回一个List
     * 包含job的字符串所组成的数组
     * @param id
     * @return
     */
    public List getJobById(int id) {
        String sql = "SELECT jobname FROM job WHERE did = " + id;
        SQLiteDatabase db = null;
        Cursor c = null;
        List jobList = null;
        try {
            db = dbHelper.getWritableDatabase();
            c = db.rawQuery(sql, null);
            jobList = new ArrayList();
            while (c.moveToNext()) {
                String jobName = new String(c.getBlob(0),"GBK") ;  //解决乱码
                jobList.add(jobName);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return jobList;

    }
}



界面设计XML:spinner.xml




    

    

    

    




Activity类:

package org.jian.activity;

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

import org.jian.service.Database;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.example.spinner.R;

public class MainActivity extends Activity {
    List deptList = new ArrayList();

    List deptData = new ArrayList();

    List jobList = new ArrayList();
   
    Spinner job;
    Spinner dept;
    Database db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spanner);
        job = (Spinner) findViewById(R.id.job);
        dept = (Spinner) findViewById(R.id.dept);
        db = new Database(getApplicationContext());

        Map> data = database.getDepts();// 得到数据库数据

        deptList = data.get(1);
        deptData = data.get(0);

        ArrayAdapter deptAdapter = new ArrayAdapter(MainActivity.this,
                android.R.layout.simple_spinner_item, deptList);
        deptAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 样式

        dept.setAdapter(deptAdapter);

        dept.setOnItemSelectedListener(itemSelectedListener);
    }

    private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView parent, View view,
                int position, long id) {
            Spinner spdept = (Spinner) parent;
            String seldept = (String) spdept.getItemAtPosition(position);
            ArrayAdapter jobAdapter = null;
            Map data = (Map) deptData
                    .get(position);// 根据id,返回本门号的信息

            int pid = data.get(seldept);// 得到部门号的id
            List jobList = db.getJobById(pid); // 根据id查得工作类型的一个List

            jobAdapter = new ArrayAdapter(MainActivity.this,
                    android.R.layout.simple_spinner_item, jobList);
            jobAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            job.setAdapter(jobAdapter);
            job.setOnItemSelectedListener(jobSelectedListener);

        }

        @Override
        public void onNothingSelected(AdapterView parent) {
        }
    };

    String selectedJob = null;
    private OnItemSelectedListener jobSelectedListener = new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView parent, View view,
                int position, long id) {
            Spinner spjob = (Spinner) parent;
            selectedJob = (String) spjob.getItemAtPosition(position);

        }

        @Override
        public void onNothingSelected(AdapterView parent) {

        }
    };

}



运行结果:

当我选择部门为:财务部时:

Android利用Spinner从数据库中读取数据并实现2级互动_第1张图片

工作职位出现的为:

Android利用Spinner从数据库中读取数据并实现2级互动_第2张图片


你可能感兴趣的:(Android)