我spinner
在我的应用程序中使用一个从 SQLite 数据库中获取值的应用程序。问题是每次我从 Eclipse 运行应用程序时,值都会一次又一次地加载。所以如果我第一次有 5 个值spinner
,第二次有 10 个值,然后是 15,然后是 20 等等。我该如何解决这个问题?
这是数据库部分:
在onCreate
:
createTable();
insertIntoTable();
ArrayList<String> my_array = new ArrayList<String>();
my_array = getTableValues();
My_spinner = (Spinner) findViewById(R.id.scelte);
My_spinner.setOnItemSelectedListener(this);
ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row, my_array);
My_spinner.setAdapter(my_Adapter);
接着:
// CREATE TABLE IF NOT EXISTS
public void createTable() {
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE
+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Errore durante la creazione della tabella",
Toast.LENGTH_LONG);
}
}
// THIS FUNCTION INSERTS DATA TO THE DATABASE
public void insertIntoTable() {
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Cibo e Bevande','cibo')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Trasporti','trasporti')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Svago','svago')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Acquisti vari','acquisti')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Sanità','sanità')");
mydb.execSQL("INSERT INTO " + TABLE
+ "(NAME, PLACE) VALUES('Altro','altro')");
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Error in inserting into table", Toast.LENGTH_LONG);
}
}
// THIS FUNCTION SHOWS DATA FROM THE DATABASE
public ArrayList<String> getTableValues() {
ArrayList<String> my_array = new ArrayList<String>();
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
System.out.println("COUNT : " + allrows.getCount());
if (allrows.moveToFirst()) {
do {
String ID = allrows.getString(0);
String NAME = allrows.getString(1);
String PLACE = allrows.getString(2);
my_array.add(NAME);
} while (allrows.moveToNext());
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Errore.",
Toast.LENGTH_LONG);
}
return my_array;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String selecteditem = My_spinner.getSelectedItem().toString();
TextView categorietext = (TextView) findViewById(R.id.sceltelabel);
categorietext.setText(selecteditem);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}