I am new to programming in Android and I am trying to create an app where a user can choose some options from 2 spinners and after tapping on the search button, the app will search through a database based on the options selected and the results will show. The problem is I’m not sure what parameters to put into db.rawQuery to search using the values of the selected spinner options. I have tried to put in a rough guess below, but it is not working and I’m not sure how to make it search using both criteria.
Here is the coding for the spinner:
public class First extends Activity {
private Spinner foodSpinner, locationSpinner;
private Button btnSubmit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
addListenerOnButton();
}
public void addListenerOnButton() {
foodSpinner = (Spinner) findViewById(R.id.foodSpinner);
locationSpinner = (Spinner) findViewById(R.id.locationSpinner);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(First.this.getApplicationContext(), MainActivity.class);
intent.putExtra("FOODSPINNER", foodSpinner.getSelectedItem().toString());
intent.putExtra("LOCATIONSPINNER", locationSpinner.getSelectedItem().toString());
First.this.startActivity(intent);
}
});
}
Here is the coding for the search:
public class MainActivity extends ListActivity {
protected SQLiteDatabase db;
protected Cursor cursor;
protected ListAdapter adapter;
protected String foodItemChosen;
protected String locationItemChosen;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle extras = getIntent().getExtras();
foodItemChosen = getIntent().getExtras().getString("FOODSPINNER");
locationItemChosen = extras.getString("LOCATIONSPINNER");
db = (new DatabaseHelper(this)).getWritableDatabase();
}
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this, ResultDetails.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("FOOD_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
public void search(View view) {
cursor = db.rawQuery("SELECT _id, name, address FROM database WHERE food LIKE ?",
new String[]{"%" '+foodItemChosen+' "%"});
adapter = new SimpleCursorAdapter(
this,
R.layout.result_list_item,
cursor,
new String[] {"name", "address"},
new int[] {R.id.name, R.id.address});
setListAdapter(adapter);
}
}
Then it is better to use
querymethod instead ofrawQuery. It provides flexible way to select items from the database.Some useful articles
http://www.vogella.com/articles/AndroidSQLite/article.html
http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android