Sorry if related question is asked before but I could not find a solution of it. Actually I am retrieving data from SQLite and doing addition on "count" column on every user input add the current plus previous input. Everything is working fine. I am trying to show that retrieved count from database in a Textview of a listview. When I do SUM(count) FROM TABLE_NAME, I can see the count but the problem is listview is showing only one item in list. It just changing the first item or overwriting. How can I solve this problem. Please help. Showing code snippets below :
This is public function from where I am retrieving data from SQLite.
public List<Product> getAllProduct() {
List<Product> products = new ArrayList<Product>();
Cursor cursor = database.rawQuery("SELECT SUM(count) From shirts ORDER BY id DESC ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int id = cursor.getInt(0);
String title = cursor.getString(1);
String price = cursor.getString(2);
String quantity = cursor.getString(3);
int count = cursor.getInt(4);
products.add(new Product(id, title, price, quantity, count));
cursor.moveToNext();
}
cursor.close();
return products;
}
you have to use two different query for that
1)Return list of all product
public List<Product> getAllProduct() {
List<Product> products = new ArrayList<Product>();
Cursor cursor = database.rawQuery("SELECT * From shirts ORDER BY id DESC ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int id = cursor.getInt(0);
String title = cursor.getString(1);
String price = cursor.getString(2);
String quantity = cursor.getString(3);
int count = cursor.getInt(4);
products.add(new Product(id, title, price, quantity, count));
cursor.moveToNext();
}
cursor.close();
return products;
}
2)Item count in cart
public int getTotalItem() {
int totalItem=0;
Cursor cursor = database.rawQuery("SELECT count(*) as totalItem From shirts ORDER BY id DESC ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int id = cursor.getInt(0);
cursor.moveToNext();
}
cursor.close();
return totalItem;
}
#OmInfowareDevelopers This is the answer I wanted to implement. You did not put cursor value in the int variable that's why it is always returning null. Well I really appreciate you time and leading to me an exact answer I wanted.
public int getTotalItem() {
int totalItem = 0;
Cursor cursor = database.rawQuery("SELECT SUM(count) From shirts ORDER BY id DESC ", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
totalItem = cursor.getInt(0);
cursor.moveToNext();
}
cursor.close();
return totalItem;
}
Related
I'm trying to fetch value from distance column where name matches the providing string. See the code below :
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
cursor.moveToFirst();
while(cursor.moveToNext()){
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}
I'm using an external Database file in assets folder of android and used pretty much same function to populate my spinner.
It is working fine with the spinner but returning the null value when using the above function.
This is my table :
Help me figure out the issue.
Thanks in advance.
//Once try this. It will definitely work.
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
if (cursor.moveToFirst())
{
distance = cursor.getString(0);
}
cursor.close();
return distance;
}
// See here for what's wrong in your code.
// cursor.moveToFirst() to move cursor to first index of cursor.
// cursor.moveToNext() to move cursor to next index.
// See what you did here.
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ", new String[] {station_name} );
cursor.moveToFirst(); // CURSOR INDEX = 0
while(cursor.moveToNext()){ // CURSOR INDEX = 1
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}
There was a problem with the iteration I was performing
The working code is below:
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data WHERE name =? ", new String[] {station_name} );
cursor.moveToFirst();
while(!cursor.isAfterLast()){
distance = cursor.getString(0);
cursor.moveToNext();
}
cursor.close();
return distance;
}
public String getDistance(String station_name){
String distance = null;
Cursor cursor = database.rawQuery("SELECT distance from station_data where name =? ",
new String[] {station_name} );
if(cursor.length() > 0){
cursor.moveToFirst();
distance = cursor.getString(0);
}
cursor.close();
return distance;
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
Main Activity
Code for fetching data from Sqlite & adding it inside Expandable list view.
public void getExpandableListData() {
// Group data//
Cursor cursor = databaseHelper.getGroupData();
cursor.moveToFirst();
do {
String categoryDescription = cursor.getString(cursor .getColumnIndex("categorydesc"));
int categoryId = cursor.getInt(cursor.getColumnIndex("CategoryId"));
listDataHeader.add(categoryDescription);
// Child data//
Cursor cursorChild = databaseHelper.getChildData(categoryId);
List<ChildInfo> childList = new ArrayList<ChildInfo>();
cursorChild.moveToFirst();
while (cursorChild.moveToNext()) {
String businessName = cursorChild.getString(cursorChild.getColumnIndex("BusinessName"));
phoneNumber = cursorChild.getString(cursorChild.getColumnIndex("ph_Phone"));
String landMark = cursorChild.getString(cursorChild.getColumnIndex("LandMark"));
ChildInfo childInfo = new ChildInfo(businessName, phoneNumber, landMark);
childList.add(childInfo);
}
childDataHashMap.put(categoryDescription, childList);
} while (cursor.moveToNext());
cursor.close();
}
DataBaseHelper class
public Cursor getGroupData() {
String query = "SELECT * FROM Category GROUP BY categorydesc";
return db.rawQuery(query, null);
}
public Cursor getChildData(int CategoryId) {
String query = "SELECT * from Category WHERE CategoryId = '" + CategoryId + "' LIMIT 3" ;
return db.rawQuery(query, null);
}
On load more tab click I have to fetch data from Sqlite db and set it to Expandable list view.Can anyone please suggest me how to avoid repetition of data fetching from Sqlite and maintain count of data fetched.
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..
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....