I have created two string variables, 'questionString' and 'answerSetId' - the first of which I have assigned to a textview - the second of which I would like to pass to my db helper class:
public void showNextRandomQuestion3() {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion1();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
List<String> answerSetIds = listList.get(4);
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
//get answer description for randomly selected question
String questionString = questionStrings.get(rand);
String answerSetId = answerSetIds.get(rand);
questionView.setText(questionString);
}
In my db helper class, I want to use this string variable as pat of my query:
public List<List<String>> getAnswers() {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_ANSWERS + "WHERE " + ASID
+ " = " + ??answerSetId??;
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
String textdescr = c.getString(c.getColumnIndex(TDESCR));
String answersdescr = c.getString(c.getColumnIndex(ADESCR));
array1.add(textdescr);
array2.add(answersdescr);;
} while (c.moveToNext());
}
List< List<String> > listArray2 = new ArrayList< List<String> >();
listArray2.add(array1);
listArray2.add(array2);
return listArray2;
}
What would be the best way to achieve this?
In order to perform a SELECT, you can use this method
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
instead of raw query. In your case:
String selection = ASID+"=?";
String selectionArgs[] = new String[]{String.valueOf(answerSetId)};
Cursor c = db.query(TABLE_ANSWERS, null, selection, selectionArgs, null, null, null);
You can also select some specific columns, passing a list of columns name as second parameter (insted of null). Also, you can replace the last three null value in the example for adding the GROUP BY, HAVING and ORDER BY clauses.
For example, in your query you are interested only in the two columns TDESCR and ADESCR. So you could use this query:
String[] columns = new String[]{TDESCR, ADESCR};
String selection = ASID+"=?";
String[] selectionArgs = new String[]{String.valueOf(answerSetId)};
Cursor c = db.query(TABLE_ANSWERS, columns, selection, selectionArgs, null, null, null);
There are a lot of others override methods query. Take a look at the documentation here
However, if you prefer you can perform a raw query in this way:
String queryString = "SELECT * FROM " + TABLE_ANSWERS +
" WHERE "+ASID+"=?";
String[] selectionArgs = new String[]{String.valueOf(answerSetId)};
sqLiteDatabase.rawQuery(queryString, selectionArgs);
Related
I have the following function in android studio, which is supposed to return a sqlite cursor.
The problem comes in the selectionArgs argument. Whenever I am passing more than one value to it, it returns a cursor with 0 records.
public Cursor getCursor(String strListWhere, String strTable, String strCols) {
String strColsToReturn = mySqliteHandler.getWhereColNamesFromJsonString(strListWhere);
String strArgs = mySqliteHandler.getWhereColArgsFromJsonString(strListWhere);
Log.d(TAG, "qqqq9: " + strArgs);
String strTableName = strTable;
String[] strColumnsToReturn = { strCols };
String strSelectWhere = strColsToReturn ;
String[] strSelectArgs = { strArgs };
Cursor csrResult = sqLiteDatabase.query(true, strTableName, strColumnsToReturn, strSelectWhere, strSelectArgs, null, null, null, null);
Log.d(TAG, "qqqq9: " + csrResult.getCount());
return csrResult;
}
The value in strColsToReturn is animal_class = ? and province_name = ?
The value in strArgs is Bird, KwaZulu-Natal
So I want it to be animal_class = 'Bird' and province_name = 'KwaZulu-natal'
When I only pass one value it works, for example
The value in strColsToReturn is animal_class = ?
The value in strArgs is Bird
Can anyone assist?
EDIT: the following code works:
public Cursor getCursor(String strListWhere, String strTable, String strCols) {
String strColsToReturn = mySqliteHandler.getWhereColNamesFromJsonString(strListWhere);
List<String> arrWhere = new ArrayList<String>();
arrWhere = mySqliteHandler.getWhereArray(strListWhere);
String[] finalValue = new String[ arrWhere.size() ];
arrWhere.toArray( finalValue );
String strTableName = strTable;
String[] strColumnsToReturn = { strCols };
String strSelectWhere = strColsToReturn ;
Cursor csrResult = sqLiteDatabase.query(true, strTableName, strColumnsToReturn, strSelectWhere, finalValue, null, null, null, null);
return csrResult;
}
The value for strColumnsToReturn should be an array with the names of the columns that you want returned, like:
new String[] {column1, column2, column3}
where column1, column2, column3 are strings.
The value for strSelectWhere should be the string:
"animal_class = ? and province_name = ?"
and the value of strSelectArgs should be a string array with the parameters that you pass to each of the ? placeholders of strSelectWhere:
new String {"Bird", "KwaZulu-Natal"}
You can find more here
here my coding:-
DatabaseHelper.java
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String selection = Menu.NewMenuInfo.MENU_ID + "=" + a1;
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,null);
return cursor;
}
Menu1.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuset1);
s_id = (TextView) findViewById(R.id.idSet1);
s_name = (TextView) findViewById(R.id.nameSet1);
s_drink = (TextView) findViewById(R.id.drinkSet1);
s_price = (TextView) findViewById(R.id.priceSet1);
set1 = (Button) findViewById(R.id.buttonOrderSet);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getinnformationSet1(sqLiteDatabase);
if (cursor != null){
cursor.moveToFirst();
String id = cursor.getString(0);
String name = cursor.getString(1);
String drink = cursor.getString(2);
String price = cursor.getString(3);
s_id.setText(id);
s_name.setText(name);
s_drink.setText(drink);
s_price.setText(price);
}
}
}
basically i want to display id,name,drink,price according to id="f1".
example: if id="f1" then display all the information without using any searching or click button.
when i run this coding the application has stopped
You need to pass the selection arguments as an array, but in the selection string you should put ? mark. Change your getinnformationUser method like this:
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String selection = Menu.NewMenuInfo.MENU_ID + "= ?";
String[] selectionArgs = new String[] {a1};
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,selectionArgs,null,null,null,null);
return cursor;
}
You can read more about the query method here.
basically your select query is wrong....its like below
public Cursor getinnformationUser(SQLiteDatabase db) {
String a1="f1";
Cursor cursor;
String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
String whereclause = Menu.NewMenuInfo.MENU_ID + "= ?";
String where_args[] = {a1};
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,whereclause,where_args,null,null,null);
return cursor;
}
Will work perfectly...
Use orderBy. In orderBy pass any value for order the rows for example if you want to order by id then pass id and add limit 1
i.e
cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,"id limit 1");
This will select only one row.
Correction
You can use query() (link provided by Eric B.) also for passing limit as parameter
I have sqlite working and tested query.
i just want to convert it into sqlitedatabase.query(); function
select distinct id, date ,sum(goal) from goal where id=0 and date = 'Sep 15, 2015' group by id, date;
How to achieve this ?
Try following.
String table = "goal";
String[] columns = new String[] { "distinct id", "date", "sum(goal)" };
String selection = "id=? and date=?";
String[] arguments = new String[] { "0", "Sep 15, 2015" };
String groupBy = "id, date";
String having = null;
String orderBy = null;
db.query(table, columns, selection, arguments, groupBy, having, orderBy);
See the doc
Here is an other approach. In the query third "null" from right is groub by
// Get Alla Favorite
public List<Favorite> getAllFavorite() {
List<Favorite> foodList = new ArrayList<>();
Favorite food;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_ID_FAV, DBHelper.COLUM_NAME_FAV, DBHelper.COLUM_NAME_TARIFE,
DBHelper.COLUMN_CALORI_FAV, DBHelper.COLUMN_PROTEIN_FAV, DBHelper.COLUMN_CARBONHYDRAT_FAV,
DBHelper.COLUMN_FAT_FAV, DBHelper.COLUMN_ENERGY_FAV, DBHelper.COLUMN_TYPE_FAV};
Cursor cursor = database.query(DBHelper.TABLE_NAME_FAV, kolonlar, null, null, DBHelper.COLUM_NAME_FAV, null, null);
while (cursor.moveToNext()) {
food = new Favorite();
food.setId(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID_FAV)));
food.setName(cursor.getString(cursor.getColumnIndex(DBHelper.COLUM_NAME_FAV)));
food.setNameTarife(cursor.getString(cursor.getColumnIndex(DBHelper.COLUM_NAME_TARIFE)));
food.setCalVal(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_CALORI_FAV)));
food.setProtVal(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_PROTEIN_FAV)));
food.setcHdrt(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_CARBONHYDRAT_FAV)));
food.setFat(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_FAT_FAV)));
food.setEnergy(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ENERGY_FAV)));
food.setType(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_TYPE_FAV)));
foodList.add(food);
}
database.close();
cursor.close();
return foodList;
}
I need to read(query) a exact row of a column of my database. This is the relevant data of my provider:
public class TravelOrderProvider extends ContentProvider {
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/travelorder");
private static final int URI_TRAVELORDER = 1;
private static final int URI_TRAVELORDER_ITEM = 2;
private static final UriMatcher mUriMatcher;
static {
mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mUriMatcher.addURI(AUTHORITY, "travelorder", URI_TRAVELORDER);
mUriMatcher.addURI(AUTHORITY, "travelorder/#", URI_TRAVELORDER_ITEM);
}
public class TravelOrder implements BaseColumns {
public static final String NAME = "name";
public static final String GROUP = "group";
public static final String ORDER = "order";
}
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
database = mDbHelper.getWritableDatabase();
int match = mUriMatcher.match(uri);
SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
qBuilder.setTables(TravelOrderDatabaseHelper.TABLE_NAME);
switch (match){
case URI_TRAVELORDER:
//nothing
break;
case URI_TRAVELORDER_ITEM:
String id = uri.getPathSegments().get(1);
qBuilder.appendWhere(TravelOrder._ID + "=" + id);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
Cursor c = qBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
Now, this is what I'm trying to do in my Activity:
private static final String[] PROJECTION = {TravelOrder._ID, TravelOrder.NAME, TravelOrder.GROUP, TravelOrder.ORDER};
Cursor c = getContentResolver().query(TravelOrderProvider.CONTENT_URI, PROJECTION, null, null, null);
My question is: How can I get a especific row of the GROUP column? I now that this should be done in the last code line above, but I have tryed defining the column and the row in the selection and selectionArgs definitions without result.
Regarding the question:
How can I get a especific row of the GROUP column?
There is a pretty well explained example on how to "Read Information from a Database" on the Android training pages.
Quoting:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
FeedEntry._ID,
FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_UPDATED,
...
};
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_UPDATED + " DESC";
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
So, by altering the selection and selectionArgs parameters accordingly, you can surely get a especific row of the GROUP column of your database.
For example, let's say that you want to get the rows that match an specific value of your GROUP column. So you should set up your query like this:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
/* The columns used for the SELECT statement. */
String[] projection = {
"ID",
"GROUP"
};
/*
* The columns used for the WHERE statement,
* they should be formatted as a prepared statement.
*/
String selection = "`ID` = ? AND `GROUP` = ?";
/*
* The arguments that will be replaced for each ?
* in the above statement.
*/
String[] selectionArgs = {
desiredId, desiredGroup
};
String sortOrder = "`ID` ASC";
Cursor c = db.query(
"MY_TABLE", // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
I am trying to UNION two tables with the same fields to create a single cursor (through a content provider) that I am using to create my ListView.
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String groupBy = null;
switch (sUriMatcher.match(uri)) {
case LIST:
StringBuilder sb = new StringBuilder();
for (String s : projection)
sb.append(s).append(",");
String projectionStr = sb.toString();
projectionStr = projectionStr.substring(0,
projectionStr.length() - 1);
String[] subQueries = new String[] {
"SELECT " + projectionStr + " FROM " + Customer.TABLE_NAME,
"SELECT " + projectionStr + " FROM "
+ IndividualCustomer.TABLE_NAME };
String sql = qb.buildUnionQuery(subQueries, sortOrder, null);
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor mCursor = db.rawQuery(sql, null);
mCursor.setNotificationUri(getContext().getContentResolver(), uri);
return mCursor;
Even if the two tables are empty, I get two null rows, which creates two rows in my listview. How do I get rid of this problem?
Additionally, when I delete a row from the ListView, the cursor is not getting updated in spite of setNotificationUri()
Any pointers, will be most appreciated
Solved - I had to supply a group by clause as one of the columns (of the projection) had a "TOTAL(...)" function.