Android - Parameter to execute dynamic query
I have a query in my main application, that shows all the registers of my database.
I have a button in my application that gets into another activity. There, i can filter my query ( for example, i have a book table and i just want books from an author and with an specific price)
So with a spinner i select my options and with an intent and put extra i pass the variables to my principal activity, so i can show the query filtered.
Here is the example
String selGrado = this.getIntent().getExtras().getString("grado");
String query = "Select * FROM Incidentes WHERE 1=1";
if () query+= " AND codGr='"+selGrado+"'";
Cursor d = db2.rawQuery(query,null);
So, i want my query to execute with the parameter selGrado that i filled in my "filter" activity. Which condition should i put? Because when application starts, i want to show all registers so its no problem avoiding the filter, and i want to execute just Select * from Incidentes .. 开发者_开发问答and if i query trough FILTER activity, i want the query knows about which option i selected. is there any way to ask if the getExtra i receive is null or something like that? thanks
Yes you can check extras by using the intent method hasExtra:
this.getIntent().hasExtra("grado");
but you could also check to see if selGrado is null
if(selGrado!=null)
a better way to do this is with the regular query instead of rawquery
String selection = null;
String[] selectionArgs = null;
if(getIntent().hasExtra("grado"))
{
selection = "codGr=?";
selectionArgs = new String[]{getIntent().getStringExtra("grado")};
}
Cursor c = db2.query("Incidentes",null,selection, selectionargs, null);
精彩评论