GROUP BY query using sqlite.query() function - android

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;
}

Related

Android .query does not get the data from db when I used where clause

I used .query to select some specific row from SQLite db table but when I used the where clause it does not retrieve data, and if I use null instead of where clause, it retrieve the last row.
public String[] getAllData(){
hoqooqdb = this.getReadableDatabase();
String[] columns = new String[] {"_id", "title", "content"};
Cursor cursor = hoqooqdb.query("unmanshor", columns, "_id = 1", null, null, null, null);
String[] result = new String[2];
while (cursor.moveToNext()){
int iTitle = cursor.getColumnIndex("title");
int iContent = cursor.getColumnIndex("content");
result[0] = cursor.getString(iTitle);
result[1] = cursor.getString(iContent);
}
return result;
}
Try like this:
String where = "_id=?";
String[] whereArgs = new String[]{String.valueOf(1)};
String[] columns = new String[] {"_id", "title", "content"};
Cursor cursor = hoqooqdb.query("unmanshor", columns, where, whereArgs, null, null, null);
Sorry, but my stupid case, In db my id was in persian language and in my code it was english and the code had not any porblem.
Sorry Again

Pass string variable to db helper and use in query

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);

Get data from sqlite database

I have an activity and want to get data from my sqlite database. It works, but my activity only retrieves the last row and not the whole column. What can i do to get the whole column?
This is the code in my database:
public String getName() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
c.moveToFirst();
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(KEY_NAME));
c.moveToNext();
}
c.close();
return name;
}
This is the code in my activities to contact the database:
Database getdata = new Database(this);
getdata.open();
String data = getdata.getName();
getdata.close();
use cursor.moveToFirst() method example given below
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
list.add(cursor.getString(6));
} while (cursor.moveToNext());
}
See, As I said, Without seeing code I m helpless.. And after seeing your code..
You are returning only single String from that function getName() instead it return String[].
Note: this is only pseudo code.. Actual may be different..
public String[] getName() {
int i=0;
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
String name[] = new String[c.getCount()];
c.moveToFirst();
while(!c.isAfterLast()) {
name[i] = c.getString(c.getColumnIndex(KEY_NAME));
c.moveToNext();
i++;
}
c.close();
return name;
}
And this one,
Database getdata = new Database(this);
getdata.open();
String data[] = getdata.getName();
getdata.close();
Update your code...
public String[] getName() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
int i=0;
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
c.moveToFirst();
String[] names = new String[c.getCount()];
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(KEY_NAME));
names[i]=name;
c.moveToNext();
i++;
}
c.close();
return names;
}
Database getdata = new Database(this);
getdata.open();
String[] data = getdata.getName();
getdata.close();

Get all rows from SQLite

I have been trying to get all rows from the SQLite database. But I got only last row from the following codes.
FileChooser class:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
fileName.add(cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1)));
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
FileSQLiteAdapter class:
public Cursor queueAll() {
String[] columns = new String[] { KEY_ID, KEY_CONTENT1 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
null, null, null, null);
return cursor;
}
Please tell me where is my incorrect. Appreciate.
try:
Cursor cursor = db.rawQuery("select * from table",null);
AND for List<String>:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Using Android's built in method
If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
More details
The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.
selection Passing null will return all rows for the given table.
And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:
Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;
private static final String MYDATABASE_TABLE = "anyTableName";
Then, wherever you are trying to retrieve all table rows;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);
List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
while(cursor.moveToNext()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
}
}
cursor.close();
db.close();
Honestly, there are many ways about doing this,
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Update queueAll() method as below:
public Cursor queueAll() {
String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
return cursor;
}
Update readFileFromSQLite() method as below:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do
{
String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
fileName.add(name);
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
public List<String> getAllData(String email)
{
db = this.getReadableDatabase();
String[] projection={email};
List<String> list=new ArrayList<>();
Cursor cursor = db.query(TABLE_USER, //Table to query
null, //columns to return
"user_email=?", //columns for the WHERE clause
projection, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
// cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndex("user_id")));
list.add(cursor.getString(cursor.getColumnIndex("user_name")));
list.add(cursor.getString(cursor.getColumnIndex("user_email")));
list.add(cursor.getString(cursor.getColumnIndex("user_password")));
// cursor.moveToNext();
} while (cursor.moveToNext());
}
return list;
}
a concise solution can be used for accessing the cursor rows.
while(cursor.isAfterLast)
{
cursor.getString(0)
cursor.getString(1)
}
These records can be manipulated with a loop

Insert first column spinner into a table

I've a table (Categories) wich two columns (_id, name).
I've a spinner that shows the column name.
Now, I need to insert the column: "_id" into another table...but I don't know how to do it.
Any suggestions?
I paste the code I'm using:
public Cursor recuperaCategoria()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "Categorias";
String[] columns = {"_id","Nombre"};
return db.query(tableName, columns, null, null, null, null, null);
}
public void recCatSpinner() {
final Spinner addCatSpinner = (Spinner) findViewById(R.id.spIdCategoria);
catCursor = recuperaCategoria();
catCursor.moveToPosition(1);
catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
addCatSpinner.setAdapter(catAdapter);
if (catCursor.moveToFirst()) {
do {
catAdapter.add(catCursor.getString(1));
Valor = catCursor.getString(1);
Log.v("valor Add Cat 100", Valor);
}
while (catCursor.moveToNext());
int id = catCursor.getInt(0);
String name = catCursor.getString(1);
Log.v("Dentro cursor","1");
if (db != null) {
Toast.makeText(getBaseContext(),catCursor.getString(0),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(catCursor);
//catCursor.close();
addCatSpinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view2, int pos, long id) {
//recID();
valor = parent.getItemAtPosition(pos).toString();
Log.v("valor Add Cat", valor);
}
public void onNothingSelected(AdapterView<?> parent) {
// view.setText("nada");
}
});
catCursor.close();
}
I'd like that when I select one item from spinner (it shows the column "Nombre"), I save into one variable the first column from cursor "_id".
Read values to collection then write a script to insert them to another taBLE
SQLiteDatabase db = getReadableDatabase();
String[] columns = { _id };
String selection = "column_name" + "=?";
String orderBy = "_id ASC";
String[] selectionArgs = new String[] { "something" };
String groupBy = null;
String having = null;
Cursor cursor = db.query("table_name", "columns", selection, selectionArgs, groupBy, having, orderBy);
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
// Add values to a collection
}
if(db.isOpen()) db.close();
SQLiteDatabase db = getWritableDatabase();
for(int id : idCollection) {
ContentValues values = new ContentValues();
values.put("_id", id);
try {
int id = db.insertOrThrow(TABLE_NAME, null, values);
}
catch (SQLException sqlEx) {
// do something with exception
}
}
if(db.isOpen()) db.close();

Categories

Resources