我正在使用此代码,但我得到了运行时异常。我做了所有必要的工作并努力消除此错误。但它对我不起作用。我正在使用DatabaseHandler。 java和AndroidSpinnerFromSQLiteActivity.java类,我的xml是activity_databse_handler.xml。
public class AndroidSpinnerFromSQLiteActivity extends Activity implements OnItemSelectedListener {
// Spinner element
Spinner spinner;
// Add button
utton btnAdd;
// Input text
EditText inputLabel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_handler);
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner);
// add button
btnAdd = (Button) findViewById(R.id.btn_add);
// new label input field
inputLabel = (EditText) findViewById(R.id.input_label);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
/**
* Add new label button click listener
* */
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// inserting new label into database
db.insertLabel(label);
// making input filed text to blank
inputLabel.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
loadSpinnerData();
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
public void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// 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
spinner.setAdapter(dataAdapter);
}
@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
}
}
=============================================== ============================================
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
try {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
catch (Exception e) {
// TODO: handle exception
}
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
//数据库版本 private static int DATABASE_VERSION = 1;
// Database Name
private static String DATABASE_NAME = "spinnerExample";
//标签表名称 private static String TABLE_LABELS =“labels”;
// Labels Table Columns names
private static String KEY_ID = "id";
private static String KEY_NAME = "name";
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
* Getting all labels
* returns list of labels
* */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
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;
}
}
=============================================== ============================================
<!-- Label -->
<!-- Input Text -->
<!-- Add Button -->
<!-- Select Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select Label"
android:padding="8dip" />
<!-- Spinner Dropdown -->
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/spinner_title"
android:layout_marginTop="20dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
/>
</LinearLayout>
答案 0 :(得分:0)
您不希望数据库的应用程序上下文,您需要活动上下文,因此您的调用应该是:
DatabaseHandler db = new DatabaseHandler(this);