Get row count from SQLite - android

I am trying to get a row count from sqlite for my android application but for some reason its always returning Zero even though I have a enough amount of rows in my DB.
Here is the Code:
DatabaseConnector database1 = new DatabaseConnector(getApplicationContext());
int TotalPosts = database1.getIds();
public int getIds()
{
String selectQuery = "SELECT COUNT(Pst_id) AS CountTotal FROM student_posts";
SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
count = c.getColumnIndex("CountTotal");
return count;
}
Thanks.

Try like below:
public int getIds()
{
String selectQuery = "SELECT Pst_id FROM student_posts";
SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
c.moveToFirst();
int total = c.getCount();
c.close();
return total;
}

Try c.getCount()..
Reference
Hope this helps..

Related

When I try to return the variable I am getting this error

I am trying to fetch and return last id from SQLite but I am getting the following error.
error: variable id might not have been initialized
Here is my method code inside databasehelper class.
public int getLastid() {
int id;
SQLiteDatabase db = this.getReadableDatabase();
String sql = "select * from sqlite_sequence where name='History'";
Cursor cursor = db.rawQuery(sql, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
id = Integer.parseInt(cursor.getString(1));
}
} else {
id = 0;
}
return id; // here error comes
}
You have to initiliaze your id variable, for your method :
int id = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from sqlite_sequence where name='History'",null);
if(cursor.getCount()==0) {
while (cursor.moveToNext()) {
id = Integer.parseInt(cursor.getString(1));
}
}
return id;
Before (your code) it was not sure that you have a value in id, because your cursor can be empty and id has no value.
Set int id=0 on line no 2.
You can then skip else condition also.

Sqlite Local database is not accurate

I'm developing android application and I'm storing some data in the local database using sqlite. When I save the database from the device file explorer and browse it using DB browser for sqlite it shows many records there which are correct. BUT i have implement a function that count number of records for specific table and it returns 0 which is wrong value.
I'm lost now cause I think the function is correct
public int numOfRecords(String tableName) {
int numOfRecords = 0;
try {
String query = "SELECT COUNT(*) FROM " + tableName ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
numOfRecords = cursor.getInt(0);
}
db.close();
}
catch (Exception ex ) {
Log.d("test" , "In exception");
}
return numOfRecords;
}
Try this code
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
Or
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;
}

Data was not inserting in SqLite DataBase but Row count is increasing

When I try to insert my data in my sqlite table, The inserted data is not inserting but the primary key is increasing and row count also increasing. Dont know what the exact problem is. Please some one help what the issue is. I will add my code here. Pls some one help me
here I am adding to database
mylistDataBaseModel = new MyListDataBaseModel();
mylistDataBaseModel.setItemId(0);
mylistDataBaseModel.setItemName("");
mylistDataBaseModel.setItemPrice(0.0);
mylistDataBaseModel.setItemGst(0.0);
mylistDataBaseModel.setCategoryId(0);
mylistDataBaseModel.setItemCategoryName("");
mylistDataBaseModel.setItemPicture("");
mylistDataBaseModel.setItemcount(0);
mylistDataBaseModel.setListName(createList.getText().toString().trim());
mylistDataBaseModel.setListItemcount(0);
mylistDataBaseModel.setItemisAdded(0);
// Log.d("==============", "====" + createList.getText().toString().trim());
sqLiteDatabase = sqlLiteController.getWritableDatabase();
SqliteController.addMyListNameToDataBase(sqLiteDatabase, mylistDataBaseModel);
sqlLiteController.close();
and opearation in database is
public static void addMyListNameToDataBase(SQLiteDatabase sqLiteDatabase, MyListDataBaseModel model) {
ContentValues contentValues = new ContentValues();
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN__ITEM_ID, model.getItemId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_NAME, model.getItemName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PRICE, model.getItemPrice());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_GST, model.getItemGst());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM__CATEGORY_ID, model.getCategoryId());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_CATEGORY_DESCRIPTION, model.getItemCategoryName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_PICTURE, model.getItemPicture());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_COUNT_ID, model.getItemcount());
Log.d("==============", "====" + model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_NAME, model.getListName());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_MY_LIST_COUNT, model.getListItemcount());
contentValues.put(SqliteItemsDataBase.NewUSerInfo.COLUMN_ITEM_IS_ADDED, model.getItemisAdded());
sqLiteDatabase.insert(SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null, contentValues);
System.out.println("Cart Summary one row has been inserted");
UserNotification.notify(Constants.NOTIFICATION_MY_LIST_ITEM_ADDED, null);
}
this is my get data from table method
public static ArrayList<MyListDataBaseModel> getMyListData(SQLiteDatabase db) {
ArrayList<MyListDataBaseModel> allMyLists = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from " + SqliteItemsDataBase.NewUSerInfo.MYLIST_TABLE, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
int localId = cursor.getInt(0);
Log.d("list","====localId====="+localId);
int itemId = cursor.getInt(1);
Log.d("list","====itemId====="+itemId);
String itemName = cursor.getString(2);
Log.d("list","====itemName====="+itemName);
Double itemPrice = cursor.getDouble(3);
Log.d("list","====itemPrice====="+itemPrice);
Double itemGst = cursor.getDouble(4);
Log.d("list","====itemGst====="+itemGst);
int categoryId = cursor.getInt(5);
Log.d("list","====categoryId====="+categoryId);
String catName = cursor.getString(6);
Log.d("list","====catName====="+catName);
String itemPicture = cursor.getString(7);
Log.d("list","====itemPicture====="+itemPicture);
int itemsCount = cursor.getInt(8);
Log.d("list","====itemsCount====="+itemsCount);
String listName = cursor.getString(9);
Log.d("list","====listName====="+listName);
int listItemCount = cursor.getInt(10);
Log.d("list","====listItemCount====="+listItemCount);
int itemIsAdded = cursor.getInt(11);
Log.d("list","====itemIsAdded====="+itemIsAdded);
allMyLists.add(new MyListDataBaseModel(localId, itemId, itemName, itemPrice,
itemGst, categoryId, catName, itemPicture, itemsCount, listName, listItemCount, itemIsAdded));
} while (cursor.moveToNext());
}
}
cursor.close();
return allMyLists;
}
I did a mistake that I got the data with some other column id instead of respected column id . That's my mistake

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets

i have an error in my application.
I'm new in making apps for android, so i donĀ“t now what's wrong...
this is in the log:
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM pets
i have a SQLite database in which is this method:
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
return petList;
}
and then i'am using this method from database in other activity to fill the ListView by the names of every pet....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
PetListView = (ListView)findViewById(R.id.list);
MyDatabaseHelper db = new MyDatabaseHelper(this);
String [] items = new String[db.getPetsCount()];
List<Pet> pets = db.getAllPets();
for (int i = 0; i < db.getPetsCount(); i++) {
items[i] = pets.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, items);
PetListView.setAdapter(adapter);
}
when this activity starts the application crashes down..
Please, can you tell me what's worng? How can i fix it? Thanks a much for help.
EDIT:
getPetsCount() method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
i solved this by myself at the end by replace the getPetsCount method:
public int getPetsCount() {
String countQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
First, you should close your cursor once you have finished to use it (that may solve your issue)
public List<Pet> getAllPets() {
List<Pet> petList = new ArrayList<Pet>();
String selectQuery = "SELECT * FROM " + TABLE_PETS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Pet pet = new Pet();
pet.setID(Integer.parseInt(cursor.getString(0)));
pet.setName(cursor.getString(1));
pet.setAge(cursor.getString(2));
petList.add(pet);
} while (cursor.moveToNext());
}
// Close cursor when finished using it
cursor.close();
return petList;
}

How to count row of a table from sqlite database android

I want to count rows of a table in android.I used 2 ways but not success & get a warning message
Launch timeout has expired, giving up wake lock!
Activity idle timeout for HistoryRecord{44e26a30 com.india.screen/.CategoryList}
I have tried-
String query="Select count(*) from Holyplace_Tbl";
Using rawQuery
public void countRows(String query) {
Cursor mcursor = assetDatabaseHelper.executeQuery(query);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
System.out.println("NUMBER IN DB: " + icount);
mcursor.close();
}
Using DatabaseUtils
public int countRows(String query)
{
int sometotal = (int) DatabaseUtils.longForQuery(sqliteDatabaseObj, query, null);
return sometotal;
}
AssetDatabaseOpenHelper.class
Try This
private static final String DB_TABLE_PLACES = "Places";
private SQLiteDatabase mDatabase;
private long fetchPlacesCount() {
String sql = "SELECT COUNT(*) FROM " + DB_TABLE_PLACES;
SQLiteStatement statement = mDatabase.compileStatement(sql);
long count = statement.simpleQueryForLong();
return count;
}
See More Here.
Simplest and Efficient way that i found from How to count number of records in sqlite
DatabaseUtils provides Static utility methods for dealing with
databases and Cursors.
int numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM table_name", null);
Or:
int numRows = DatabaseUtils.queryNumEntries(db, "table_name");
You can use a simple RawQuery like this:
private SQLiteDatabase mDatabase;
Cursor c = mDatabase.rawQuery("select COLUMN_NAME from TABLE_NAME",null);
int count = c.getCount();
The Cursor.getCount() method returns the number of rows in the cursor, whch in this case would be the number of items you are looking for.
long numRows = DatabaseUtils.queryNumEntries(db, table);
You can get row count as follows:
c = db.rawQuery("SELECT * FROM Your_tabename", null);
int i = c.getCount();

Categories

Resources