使用数据库来存储值。有一张州桌和一张大学桌。在 Colleges 表中有一个用于存储状态的列 从 States 表中加载微调器并设置一个 onClik 侦听器。当用户点击 State 时,从 Colleges 表中搜索加载微调器,其中 State = selected State 列。
下面是来自http://www.androidhive.info/2012/06/android-populating-spinner-data-from-sqlite-database/的修改类
我建议通过他的教程。
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "spinnerExample";
// Labels table name
private static final String TABLE_STATES = "states";
private static final String TABLE_COLLEGES = "colleges";
// Labels Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_STATE = "state";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_STATES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_STATES_TABLE);
String CREATE_COLLEGES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT" + KEY_STATE + "TEXT)";
db.execSQL(CREATE_COLLEGES_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STATES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COLLEGES);
// Create tables again
onCreate(db);
}
/**
* Getting all labels
* returns list of labels
* */
public List<String> getAllStates(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public List<String> getCollegs(String state){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_COLLEGES + " WHERE " + KEY_STATE " EQUALS " + state;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}