in this app I`m trying give different welcome message to each type of users
so here is the code in my DB helper class
public int loginCheck(String a,String b)
{
int ty;
SQLiteDatabase db=this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM users where user_name = '"+a+"'AND user_password = '"+b+"';", null);
ty= c.getInt(c.getColumnIndex("user_type"));
if (c.getCount()<=0)
{
c.close();
db.close();
return 2;
}
else
c.close();
db.close();
return ty;
}
it should check the user type whether 0 or 1 ,, and according to the return value the welcome message appears,what i got that this retrieves the number of the column , it retrieves 6 and "user_type" is the sixth column
You need to move to the first row first:
public int loginCheck(String a,String b) {
int ty;
SQLiteDatabase db=this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM users where user_name = '"+a+"' AND user_password = '"+b+"';", null);
if (c.moveToFirst()) {
ty = c.getInt(c.getColumnIndex("user_type"));
} else {
ty = 2;
}
c.close();
db.close();
return ty;
}
cursor.moveToFirst will return false if it wasn't able to move to the first row (e.g. the cursor is empty), so no need for the c.getCount() check
=====
The Android way of doing this (not using rawQuery unless have to):
public int loginCheck(String a,String b) {
int ty;
SQLiteDatabase db=this.getWritableDatabase();
Cursor c = db.query("users", new String[] { "user_type" }, "user_name = ? AND user_password = ?", new String[] {a, user_password}, null, null, null);
if (c.moveToFirst()) {
ty = c.getInt(0);
} else {
ty = 2;
}
c.close();
db.close();
return ty;
}
Related
I am trying to query all the users data that belong to him uniquely. through FK_ID of the user in the notes table.
// Listing all notes
public Cursor listNotes() {
SQLiteDatabase db = help.getReadableDatabase();
Cursor c = db.query(help.NOTE_TABLE, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Count how many Notes user has
public int NoteCount() {
String countQuery = "SELECT * FROM " + help.NOTE_TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public void editNote(long id, String title, String body) {
ContentValues edit = new ContentValues();
edit.put(help.COLUMN_TITLE, title);
edit.put(help.COLUMN_BODY, body);
open();
db.update(help.NOTE_TABLE, edit, help.NOTES_ID + "=" + id, null);
close();
}
// Deleting single note
public void deleteNote(long id) {
open();
db.delete(help.NOTE_TABLE, help.NOTES_ID + "=" + id, null);
close();
}
}
I have a tab that will then return all the users data uniquely to him. This tab is a fragment.the Method populateList() will be called onCreateView
public void populateList(){
Cursor cursor = control.listNotes();
getActivity().startManagingCursor(cursor);
//Mapping the fields cursor to text views
String[] fields = new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE};
int [] text = new int[] {R.id.item_title,R.id.item_body, R.id.item_date};
adapter = new SimpleCursorAdapter(getActivity(),R.layout.list_layout,cursor, fields, text,0);
//Calling list object instance
listView = (ListView) getView().findViewById(android.R.id.list);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
This is a null pointer. Am i passing the data wrong
Cursor cursor = control.listNotes();
Your listNotes method should look like :
public Cursor listNotes(long userId) {
Cursor c = getActivity().getContentResolver().query(yourTodoTableURI, new String[]{help.COLUMN_TITLE,help.COLUMN_BODY, help.COLUMN_DATE}, help.COLUMN_USER_ID + " = ?", new String[]{String.valueOf(userId)} , null);
return c;
}
try this:
public List<String> getAllTask(int userID){
String query = "Select * from tablename where ID =" + userID;
cursor = db.query(); //do your code here
int id = cursor.getInt(cursor.getColumnIndex(tablename.ID));
List<String> task = new ArrayList<String>();
String query = "Select * from tableTask where ID =" + id";
cursor = db.query(); //
if (cursor != null) {
cursor.movetofirst();
// do your code here
do{
String task = cursor.get......
task.add(task);
}while(cursor.movetonext);
}
return task;
}
I retrieve all the rows from my SQLite-DB Table
Cursor cursor = db.rawQuery("select * from table",null);
Then I want to add each row to an ArrayList
Please help!
IF you're using custom object array, then use like following :
public void fillDataToArray() {
ArrayList<BeanClass> arrayList = new ArrayList<BeanClass>();
DatabaseHandler db = new DatabaseHandler(getActivity());
db.open();
try
{
Cursor c = db.getImageNameForList();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Beanclass detail = new Beanclass ();
detail.setName(c.getString(c
.getColumnIndex(DatabaseHandler._ID)));
detail.setPath(c.getString(c
.getColumnIndexOrThrow(DatabaseHandler._PATH)));
arrayList.add(detail);
c.moveToNext();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
c.close();
db.close();
}
If you use this in activity, change getActivity() to local context or whichever way you use context in activities.
DATA RETRIEVAL METHOD IN DB ADAPTER CLASS :
> public Cursor getImageNameForList() {
return db.rawQuery("select " + IMAGE_PATH + " from "+ TABLE_PRODUCT_IMAGES , null);
}
Code to do that would look like this, depending on whats in your Table. You have to create a Class that is able to represent a Row in your table.
For example if there are people in your table, with name and age, you will need an object Human(String name, int age) to put into a list.
SQLiteDatabase db = helper.getReadableDatabase();
ArrayList<Human> results = new ArrayList<Human>();
try {
String rawQuery = "Select name, age from people";
Cursor c = db.rawQuery(rawQuery, null);
try {
if (!c.moveToFirst())
return null;
do {
results.add(new Human(c.getString(0),c.getInt(1)));
} while (c.moveToNext());
} finally {
c.close();
}
} finally {
db.close();
}
public class Human {
private String name;
private int age;
public Human (String name, int age) {
this.name = name;
this.age = age;
}
}
In your Db Adapter class, add this method
public ArrayList<String>getData()
{
ArrayList<String>names=new ArrayList<String>();
Cursor c = getReadableDatabase().rawQuery("Select * from tableName", null);
c.moveToFirst();
do
{
String s1=c.getString(c.getColumnIndex("<Column_Name>"));
names.add(s1);
}while(c.moveToNext());
return names;
}
after that in your activity class add this
ArrayList<String> cid;
DB_Adapter database = new DB_Adapter(getApplicationContext(), "<your schema name>", null, 1);
cid=database.getData();
After that add your arraylist to your array adapter which is set to ListView
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.
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()
I have a problem with "last_insert_rowid()".
In my DB-Helper-Class I am doing the following:
public int getLastID() {
final String MY_QUERY = "SELECT last_insert_rowid() FROM "+ DATABASE_TABLE5;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
But when I call this in my intent:
int ID = mDbHelper.getLastID();
Toast.makeText(this, "LastID: " + ID, Toast.LENGTH_SHORT).show();
I get always "0" back. That can not be, cause I have a lot of entries in my DB and the autoincrement value should be much higher.
What I am doing wrong?
OK, that was the right hint John ;-)
The query should look like this:
public int getHighestID() {
final String MY_QUERY = "SELECT MAX(_id) FROM " + DATABASE_TABLE5;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
You don't need to put table name with last_insert_rowid() it will automatically select last inserted id from session. so you can just simply use this function as well.
public int getHighestID() {
final String MY_QUERY = "SELECT last_insert_rowid()";
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}