In my application i am showing data from database in a table view.My requirement is that from database i have to retrieve the data which will fall in the current month.I Have written the query but it is coming as 0.Actually i have 1 entry in the database with today's date,so my query should return that data,but it is showing as 0.Please help me.Thanks in advance.
My query is as follows:
public String addgroupincome(String grp) throws SQLException
{
long sum=0;
Cursor cursor1 = db.rawQuery(
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE date= Strftime('%Y-%m','now') AND category='Income' AND groups='"+grp+"'",null);
if(cursor1.moveToFirst())
{
sum = cursor1.getLong(0);
}
cursor1.close();
String housetotal=String.valueOf((long)sum);
return housetotal;
}
I am getting that total and showing in atextview in table layout..
final String houtotal=db.addgroupincome(group1);
housetotal.setText(houtotal);
Most probably nothing wrong with the query but the way you pass the query result to ListView. Can you show how you do it? Perhaps I could help.
Or you could take a look here or here
public int getCount() {
DBHelper dbHelper = DBHelper.getDBAdapterInstance(this);
int count = 0;
try {
dbHelper.openDataBase();
String query = "select count(1) from t_model where upper(brandName) = upper('"
+ selectedBrand + "') order by modelName ASC";
Cursor cursor = dbHelper.selectRecordsCursor(query, null);
if (cursor.moveToFirst()) {
count = cursor.getInt(0);
}
cursor.close();
cursor = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
dbHelper.close();
}
return count;
}
and for the TextView should be as simple as
TextView tvCount = (TextView) findViewById(R.id.tvCount);
tvCount.setText("Count : " + getCount);
If you are having trouble debugging your query. Try http://sqlitebrowser.sourceforge.net/ or http://www.sqliteexpert.com/
Why don't you try by giving column names of your table in your query..might it work out for you..specify the columns which you want to retrive..
if (cursor.moveToNext()) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
Log.i(ID, cursor.getInt(0) + "");
cursor.moveToNext();
}
cursor.close();
} else {
cursor.close();
return null;
}
Try This Method....
Related
I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !
I have created a Sugar ORM database successfully in my app, I can update, delete and also get all data from a row, but I want a single column data matched with another data...
I mean, I have a registration database with fields: username, password, first_name, last_name, email fields.
After login a user with right username and password, I want THAT User's First_Name in a Textview sent to the Next Activity...
How can I do this? Over last two days I have tried but failed, please help me...
Thanks in advance...
public static List<String> getResultWithRawQuery(String rawQuery, Context mContext) {
List<String> stringList = new ArrayList<>();
if (mContext != null) {
long startTime = System.currentTimeMillis();
SugarDb sugarDb = new SugarDb(mContext);
SQLiteDatabase database = sugarDb.getDB();
try {
Cursor cursor = database.rawQuery(rawQuery, null);
try {
if (cursor.moveToFirst()) {
do {
stringList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
Timber.d(cursor.getString(0), "hi");
} finally {
try {
cursor.close();
} catch (Exception ignore) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("total time query" + totalTime);
}
return stringList;
}
Another example that returns a List of values in the column. Use as such:
String rawQuery = ("SELECT feed_key FROM team_feed_key WHERE team_id = " + mTeam_id + " ORDER BY feed_key DESC");
Did you try to run a raw query like this?
List<Note> notes = Note.findWithQuery(Note.class, "Select * from Note where name = ?", "satya");
from: http://satyan.github.io/sugar/query.html
you can add function to SugarRecord.java forever
public static String Scaler(String Query) {
String Result = "";
SugarDb db = getSugarContext().getSugarDb();
SQLiteDatabase sqLiteDatabase = db.getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
or
public static String Scaler(String Query) {
String Result = "";
SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
Scaler("Select First_Name from Note where name ='ali' limit 1");
I had the same problem.
I hope this helps someone:
String firstName = Select.from(User.class).where("EMAIL = "+ user.getEmail()).first().getFirstName();
Hi this must work you can not edit the libraries but you can extend them so check this out:
public class DBUtils extends SugarRecord {
public static <T> List<Object> findByColumn(Context context, String tableName,T ColumnObjectType, String columnName) {
Cursor cursor = new SugarDb(context).getDB().query(tableName, new String[]{columnName}, null, null,
null, null, null, null);
List<Object> objects = new ArrayList<>();
while (cursor.moveToNext()){
if (ColumnObjectType.equals(long.class) || ColumnObjectType.equals(Long.class)) {
objects.add(cursor.getLong(0));
}else if(ColumnObjectType.equals(float.class) || ColumnObjectType.equals(Float.class)){
objects.add(cursor.getFloat(0));
}else if(ColumnObjectType.equals(double.class) || ColumnObjectType.equals(Double.class)){
objects.add(cursor.getDouble(0));
}else if(ColumnObjectType.equals(int.class) || ColumnObjectType.equals(Integer.class)){
objects.add(cursor.getInt(0));
}else if(ColumnObjectType.equals(short.class) || ColumnObjectType.equals(Short.class)){
objects.add(cursor.getShort(0));
}else if(ColumnObjectType.equals(String.class)){
objects.add(cursor.getString(0));
}else{
Log.e("SteveMoretz","Implement other types yourself if you needed!");
}
}
if (objects.isEmpty()) return null;
return objects;
}
}
The usage is simple use DBUtils.findByColumn(...);
Any where you like and from now on you can use only this class instead of SugarRecord and add your own other functions as well.
hint:
ColumnObjectType as the name Suggest tells the type of column like you send Integer.class
I have a code that would give me the sum of a column in a database, i have done the crud, but now i would like to do a search by a the name of a column and show the sum of all the records(that have the same name) and show in a textfield.
the following is my DatabasdeHandler:
public Cursor getSingleDespesaSum(String date) {
SQLiteDatabase db = this.getReadableDatabase();
int sum = 0;
Cursor cursor = db.rawQuery(
"select sum(valor) from despesas WHERE data = ?", null);
if (cursor.moveToFirst()) {
do {
sum = cursor.getInt(0);
} while (cursor.moveToNext());
}
return cursor;
}
And this is my activity;
btGetSum.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
try {
dia = (String) spinDia.getSelectedItem();
mes = (String) spinMes.getSelectedItem();
ano = (String) spinAno.getSelectedItem();
String dataSendTo = dia + "/" + mes + "/" + ano;
dbhelper.getSingleDespesaSum(dataSendTo); //missing code
} catch (Exception erro) {
mensagemExibir("Erro Ao Buscar", "" + erro.getMessage());
}
}
});
}
Content Providers are the way to go, don't access your database directly like this.
But... to answer your current question:
SQLiteDatabase db = this.getReadableDatabase();
int sum = 0;
Cursor cursor = db.rawQuery(
"select value from table WHERE date= ?", null);
while (cursor.moveToNext()) {
//Increment your counter
sum += cursor.getInt(cursor.getColumnIndex("value");
};
I've following table structure in my SQLite Database.
In my SqliteOpenHelper class, I wrote following method.
public Form getAllForms(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
int count = cursor.getCount();
String formID = cursor.getString(0);
Form form = new Form();
form.setId(formID);
cursor.close();
db.close();
return form;
}
I'm sure there's some data in it because I already watched count in debugging mode and I saw the quantity of row that actually existing in database. But CursorIndexOutOfBoundException shows up at cursor.getString(0). plus cursor.getInt(0) and cursor.getString(1) didn't work also. What's the problem might be?
You need to move the cursor to a valid row.
Valid rows are indexed from 0 to count-1. At first the cursor will point to row index -1 i.e. the one just before the first row.
The canonical way of looping through all rows is
if (cursor.moveToFirst()) {
do {
// now access cursor columns
} while (cursor.moveToNext());
}
Try this
try {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
Form form = new Form();
form.setId(formID);
cursor.moveToNext();
}
} finally {
// database.close();
cursor.close();
dbHelper.close();
}
You need to call moveToFirst() to get to the first row before asking for values:
if ((cursor!= null) && (cursor.getCount() > 0)) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
}
So Simply use your code as
public Form getAllForms(){
Form form = new Form();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+FORM_TABLE, null);
if ((cursor != null) && (cursor.getCount() > 0)) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
String formID = cursor.getString(0);
form.setId(formID);
cursor.moveToNext();
}
cursor.close();
}
db.close();
return form;
}
This question already has answers here:
How can i check to see if my sqlite table has data in it?
(13 answers)
Closed 4 years ago.
Well, I have a databse and it has lots of table. but generally tables are empty.
I want check if a database table is empty.
IF table is empty, program will fill it.
public static long queryNumEntries (SQLiteDatabase db, String table)
I will use it but it requre API 11.
you can execute select count(*) from table and check if count> 0 then leave else populate it.
like
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//leave
else
//populate table
Do a SELECT COUNT:
boolean empty = true
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM YOURTABLE", null);
if (cur != null && cur.moveToFirst()) {
empty = (cur.getInt (0) == 0);
}
cur.close();
return empty;
public boolean isEmpty(String TableName){
SQLiteDatabase database = this.getReadableDatabase();
long NoOfRows = DatabaseUtils.queryNumEntries(database,TableName);
if (NoOfRows == 0){
return true;
} else {
return false;
}
}
Optimal Solutions
public boolean isMasterEmpty() {
boolean flag;
String quString = "select exists(select 1 from " + TABLE_MASTERS + ");";
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(quString, null);
cursor.moveToFirst();
int count= cursor.getInt(0);
if (count ==1) {
flag = false;
} else {
flag = true;
}
cursor.close();
db.close();
return flag;
}
Here is a better option:
public boolean validateIfTableHasData(SQLiteDatabase myDatabase,String tableName){
Cursor c = myDatabase.rawQuery("SELECT * FROM " + tableName,null);
return c.moveToFirst();
}
This is how you can do it -
if(checkTable("TABLE"))
{
//table exists fill data.
}
Method to check table -
public static boolean checkTable(String table) {
Cursor cur2 = dbAdapter.rawQuery("select name from sqlite_master where name='"
+ table + "'", null);
if (cur2.getCount() != 0) {
if (!cur2.isClosed())
cur2.close();
return true;
} else {
if (!cur2.isClosed())
cur2.close();
return false;
}
}
I think, this solution is better:
boolean flag;
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext(), DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION);
try {
sqLiteDatabase = databaseHelper.getWritableDatabase();
} catch (SQLException ex) {
sqLiteDatabase = databaseHelper.getReadableDatabase();
}
String count = "SELECT * FROM table";
Cursor cursor = sqLiteDatabase.rawQuery(count, null);
if (cursor.moveToFirst()){
flag = false;
} else {
flag = true;
}
cursor.close();
sqLiteDatabase.close();
return flag;
moveToFirst() check table and return true, if table is empty. Answer that is marked correct - uses extra check.