【发布时间】:2018-09-05 15:14:08
【问题描述】:
我需要检查我的微调器是否为空。但是当微调器内部有数据时,它仍然向我显示吐司它是空的,不包含任何数据。主要问题是微调器已经包含数据库中的数据,但程序在再次打开应用程序后不断添加新数据。
主要活动
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
databaseHelper db = new databaseHelper(getApplicationContext());
if (spinner.getCount() == 0){
Toast.makeText(MainActivity.this,"Spinner will be populated now",Toast.LENGTH_LONG).show();
db.insertData();
}else {
Toast.makeText(MainActivity.this,"Spinners is already populated",Toast.LENGTH_LONG).show();
}
loadData();
}
public void loadData(){
databaseHelper db = new databaseHelper(getApplicationContext());
List<String> labels = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, labels);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String label = adapterView.getItemAtPosition(i).toString();
Toast.makeText(adapterView.getContext(),"Selected: "+label,Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
数据库
public databaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_2 + " TEXT," + COLUMN_3 + " TEXT," + COLUMN_4 + " TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_2, "1");
contentValues.put(COLUMN_3, "2");
contentValues.put(COLUMN_4, "3");
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else
return true;
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
labels.add(cursor.getString(2));
labels.add(cursor.getString(3));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return labels;
}
}
【问题讨论】: