SQLite search by name, show sum result in textfield - android

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

Related

rawQuery() exact match

I am using the following method to query my SQLite database with LIKE statement.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord.trim() + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
wordList.add(new Bean(english, bangla));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
I would like to change the above code for that it will query for exact match. I tried to modify the code as below but I do not how to get the mal string.
public void getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{englishWord});
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
}
} finally {
if (cursor != null)
cursor.close();
}
}
Method getoneWords for what. You should return mal and english in this function.
return new Bean(english, mal);
If you need first word, just cursor.moveToFirst and delete while loop:
String english = cursor.getString(1);
String mal = cursor.getString(2);
return new Bean(english, mal);
I finally solved this problem myself.
public String getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
String meaning = "";
try {
cursor = db.rawQuery(sql, new String[] {englishWord});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
meaning = cursor.getString(2);
}
return meaning;
}finally {
cursor.close();
}
}
In your getoneWords() you are not returning the queried values.
As you have two return values you would either need to wrap them in a Pair or create a "holder" Object (e.g. class Words(String english, String mal)) for the return values.
If your Query returns multiple matches you would need to return a list of those Objects. Otherwise, your above Code would just return the last match.
So you need to alter your function to return the queried
public Pair<String,String> getoneWords(String englishWord) {
Pair<String,String> result = null;
...
if(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
result = new Pair<String,String>(english, mal);
}
...
return result;
}

Retrieving specific data based on ID from SQLite in ANDROID

I wrote a code in which i can retrieve the data from the database but when i run it and try to search something. The application crashes as soon as i press Submit
public class search extends AppCompatActivity {
Button SearchButton;
EditText SearchText;
TextView SearchResult;
SQLiteDatabase db;
String builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
SearchButton=(Button)findViewById(R.id.searchbutton);
SearchText=(EditText)findViewById(R.id.Searchtext);
SearchResult=(TextView)findViewById(R.id.SearchCourse);
db=this.openOrCreateDatabase("Courses", Context.MODE_PRIVATE,null);
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int GetID = Integer.valueOf(SearchText.getText().toString());
Cursor TuplePointer = db.rawQuery("Select from Course where ID="+GetID+"",null);
TuplePointer.moveToFirst();
String Course = TuplePointer.getString(TuplePointer.getColumnIndex("Course"));
SearchResult.setText(Course);
}
});
}
}
Replace this line
Cursor TuplePointer = db.rawQuery("Select from Course where ID=" + GetID + "", null);
with
Cursor TuplePointer = db.rawQuery("Select Course from Course where ID=" + GetID + "", null);
Where Course is your column name
Write your code within try catch first. Afterthat try to catch exact exception. you will be clear what are you doing wrong.
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " Where " + KEY_APP_BOOKINGID + " = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Please Try this
SQLiteDatabase db = this.getReadableDatabase();
String GetID = SearchText.getText().toString();
Cursor cursor = db.rawQuery("SELECT * FROM Course WHERE ID = ?", new String[]{String.valueOf(GetID)}, null);
if (cursor.moveToFirst()) {
do {
String Course = cursor.getString(cursor.getColumnIndex("Course"));
SearchResult.setText(Course);
} while (cursor.moveToNext());
}
Thank You everyone I figured out what i was doing wrong on the get Column index i targeted course but what i didnt realize is that there was no such field as course :)
Keep practice like below code you will debug proper
public void getFirstName(String id) {
String sql = "select first_name from basic_info WHERE contact_id="+ id;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
Log.e("Result =>",FirstName);
}
c.close();
}
return data;
}
public Cursor fetchData(String sql) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(sql, null);
}

How to retrieve the sum of the selected category from SQLite category_column?

My table contains these columns:
1 - id integer
2 - car_model text`
3 - car_value int
4 - car_color
Code:
public static final String CREATE_query = "create table car" + "(id integer primary key autoincrement,carmodel text not null,carvalue integer not null,carcolor text not null)";
The problem I face is how to get the total value of selected car model in a Spinner and display the value using a TextView
I use this to query the database
public float getCarModelValue(SQLiteDatabase db, String selectedmodel) {
float amount = 0;
db = this.getReadableDatabase();
String query = "select sum(carvalue) from car where carmodel = '"+ selectedmodel;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
amount = cursor.getInt(0);
}
while (cursor.moveToNext());
}
db.close();
return amount;
}
but it fails.
Also I tried the following code
public float getAccountValue(SQLiteDatabase db, String selected) {
float amount = 0;
db = this.getReadableDatabase();
String query = "select sum(carvalue) from car group by carmodel where carmodel = " + selected;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
amount = cursor.getInt(0);
}
while (cursor.moveToNext());
}
db.close();
return amount;
}
And use this code to display value
dbhelper = new DbHelper(getApplicationContext());
sqlitedatabase = dbhelper.getReadableDatabase();
try {
valueofcar = dbhelper.getCarModelValue(sqlitedatabase, model_selected);
total_value.setText("" + valueofcar);
} catch (Exception e) {
e.printStackTrace();
}
any help appreciated
You need to close the string delimiter:
Wrong:
String query = "select sum(carvalue) from car where carmodel = '"+ selectedmodel;
Correct:
String query = "select sum(carvalue) from car where carmodel = '"+ selectedmodel + "'";
Similarily, in the other method, the correct query is
String query = "select sum(carvalue) from car group by carmodel where carmodel = '" + selected + "'";
In both methods, you don't need this: group by carmodel, nor the do ... while loop - since you are only retrieving a single value.
One way of doing this is to store result in a new column and read from it
and get the result
public float getCarModelValue(SQLiteDatabase db, String selectedmodel) {
float amount = 0;
db = this.getReadableDatabase();
String query = "select sum(carvalue) from car as totalcar where carmodel = '"+ selectedmodel + "'";
Cursor cursor = db.rawQuery(query, null);
String query = "select totalcar from car";
Cursor cursor = db.rawQuery(query, null);
cursor=cursor.moveToFirst();
amount=cursor.getInt(getColumnIndex(totalcar));
db.close();
return amount;
}

How to get row count in sqlite using Android?

I am creating task manager. I have tasklist and I want when I click on particular tasklist name if it empty then it goes on Add Task activity but if it has 2 or 3 tasks then it shows me those tasks into it in list form.
I am trying to get count in list. my database query is like:
public Cursor getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
if(cursor!=null && cursor.getCount()!=0)
cursor.moveToNext();
return cursor;
}
In My activity:
list_tasklistname.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
Cursor c = db.getTaskCount(id);
System.out.println(c.getCount());
if(c.getCount()>0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
task = adapter.getItem(position);
int taskList_id = task.getTaskListId();
taskListID.putExtra("TaskList_ID", taskList_id);
startActivity(taskListID);
}
else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
});
db.close();
}
but when I am clicking on tasklist name it is returning 1, bot number of tasks into it.
Using DatabaseUtils.queryNumEntries():
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
or (more inefficiently)
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
In Activity:
int profile_counts = db.getProfilesCount();
db.close();
Use android.database.DatabaseUtils to get number of count.
public long getTaskCount(long tasklist_Id) {
return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);
}
It is easy utility that has multiple wrapper methods to achieve database operations.
c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.
public int getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery(
"SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) }
);
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
}
db.close();
return count;
}
I know it is been answered long time ago, but i would like to share this also:
This code works very well:
SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
BUT what if i dont want to count all rows and i have a condition to apply?
DatabaseUtils have another function for this: DatabaseUtils.longForQuery
long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
The longForQuery documentation says:
Utility method to run the query on the db and return the value in the first column of the first row.
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
It is performance friendly and save you some time and boilerplate code
Hope this will help somebody someday :)
Change your getTaskCount Method to this:
public int getTaskCount(long tasklist_id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
cursor.moveToFirst();
int count= cursor.getInt(0);
cursor.close();
return count;
}
Then, update the click handler accordingly:
public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
// Get task list id
int tasklistid = adapter.getItem(position).getTaskListId();
if(db.getTaskCount(tasklistid) > 0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
taskListID.putExtra("TaskList_ID", tasklistid);
startActivity(taskListID);
} else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
In order to query a table for the number of rows in that table, you want your query to be as efficient as possible. Reference.
Use something like this:
/**
* Query the Number of Entries in a Sqlite Table
* */
public long QueryNumEntries()
{
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "table_name");
}
Do you see what the DatabaseUtils.queryNumEntries() does? It's awful!
I use this.
public int getRowNumberByArgs(Object... args) {
String where = compileWhere(args);
String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
Cursor c = getWriteableDatabase().rawQuery(raw, null);
try {
return (c.moveToFirst()) ? c.getInt(0) : 0;
} finally {
c.close();
}
}
Sooo simple to get row count:
cursor = dbObj.rawQuery("select count(*) from TABLE where COLUMN_NAME = '1' ", null);
cursor.moveToFirst();
String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
looking at the sources of DatabaseUtils we can see that queryNumEntries uses a select count(*)... query.
public static long queryNumEntries(SQLiteDatabase db, String table, String selection,
String[] selectionArgs) {
String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : "";
return longForQuery(db, "select count(*) from " + table + s,
selectionArgs);
}
Once you get the cursor you can do
Cursor.getCount()

Database retrieval in android

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....

Categories

Resources