1. 按行读取assets下txt数据,并初始化到SQLiteDatabase
1. 进入project下,右击main创建assets文件夹,添加txt文件
2. 在SQLiteOpenHelper下:
(1) 写读取txt并插入数据库的方法:readFromAssets(SQLiteDatabase db) 并在onCreate( )里调用.
(2) getAllNation()用于之后获取数据库数据填充spinner
public class DBManager { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "users.db"; private final Context context; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + NationalityDBStructure.tableEntry.TABLE_NAME + " (" + " _id INTEGER PRIMARY KEY AUTOINCREMENT, " + NationalityDBStructure.tableEntry.COLUMN_NAME + " )"; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + NationalityDBStructure.tableEntry.TABLE_NAME; private NationalityOpenHelper myDBHelper; private SQLiteDatabase db; private String[] projection = { NationalityDBStructure.tableEntry.COLUMN_NAME}; // we can obtain a reference to it and call it // in the DBManager constructor public DBManager(Context ctx) { this.context = ctx; myDBHelper = new NationalityOpenHelper(context); } // open db public DBManager open() throws SQLException { db = myDBHelper.getWritableDatabase(); return this; } // close db public void close() { myDBHelper.close(); } /** * 2. Getting all labels * returns list of labels * */ public List<String> getAllNation(){ List<String> labels = new ArrayList<String>(); // SQLiteDatabase db = myDBHelper.getReadableDatabase(); Cursor cursor = db.query(NationalityDBStructure.tableEntry.TABLE_NAME, projection, null, null, null, null, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { //add first entry into labels labels.add(cursor.getString(0)); } while (cursor.moveToNext()); } // closing connection cursor.close(); db.close(); // returning lables return labels; }
private class NationalityOpenHelper extends SQLiteOpenHelper { public NationalityOpenHelper(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } // 1. this method private void readFromAssets(SQLiteDatabase db) { try { ContentValues values = new ContentValues(); InputStream is = context.getAssets().open("nationdata.txt"); InputStreamReader reader = new InputStreamReader(is); BufferedReader br = new BufferedReader(reader); String s1; while ((s1 = br.readLine()) != null) { //添加记录 values.put(NationalityDBStructure.tableEntry.COLUMN_NAME, s1); //调用insert()方法插入数据 db.insert(NationalityDBStructure.tableEntry.TABLE_NAME, null, values); } br.close(); reader.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onCreate(SQLiteDatabase db){ db.execSQL(SQL_CREATE_ENTRIES);
// call it here readFromAssets(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ // This database is only a cache for online data, so its upgrade policy is // to simply to discard the data and start over db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } } }
2. populating spinner from SQLiteDatabase(数据库数据填充spinner)
public class RegisterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { protected DBManager dbManager; Spinner msp_nation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); dbManager = new DBManager(this); // Spinner element msp_nation = (Spinner) findViewById(R.id.sp_nationality); mtv_showDoB = (TextView) findViewById(R.id.tv_showDoB); mtv_login = (TextView) findViewById(R.id.tv_login); // Spinner click listener msp_nation.setOnItemSelectedListener(this); // Loading spinner data from database loadSpinnerData(); } /** * Function to load the spinner data from SQLite database * */ public void loadSpinnerData(){
// 第一次open()会初始化数据库(调用onCreate()) try { dbManager.open(); } catch (SQLException e) { e.printStackTrace(); } // Spinner Drop down elements List<String> lables = dbManager.getAllNation(); // Creating adapter for spinner ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lables); // Drop down layout style - list view with radio button dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner msp_nation.setAdapter(dataAdapter); dbManager.close(); } // @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // On selecting a spinner item String label = parent.getItemAtPosition(position).toString(); // Showing selected spinner item Toast.makeText(parent.getContext(), "You selected: " + label, Toast.LENGTH_LONG).show(); } // @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }
效果: