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

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

Related

ArrayList outOfBoundsException database error

Hey as I was running tests on my application I began to delete database values from my database. Once I did I began getting this error
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
It is for this line of code.
PasswordResults passwordResults = password.get(0); which I am confused on as .get(0) would always get the selected row on my recyclerView prior to me deleting some data in the database.
Here is my code for my PasswordManager where I am getting the error at.
I am passing a checker integer and a String that has the selectedID of the row the user clicked. I have tried using PasswordResults passwordResults = password.get(Integer.parseInt(id)) thinking that would work but it does not.
// method to load correct screen based on user input.
public void loadScreen(int c, String id){
// checking if it is a previous entry.
if(c == 1) {
// Since there already is a password set button to "Show Password"
password_btn.setText("Show");
// getting selected passwords data.
password = db.getSelectedPassword(id);
// GETTING ERROR HERE
PasswordResults passwordResults = password.get(0);
idSelected = id;
entryName_et.setText(passwordResults.entryName);
website_et.setText(passwordResults.website);
username_et.setText(passwordResults.username);
realPassword = passwordResults.password;
// dont show real password yet.
if(showPW == 1)
password_et.setText(realPassword);
else
password_et.setText("***********");
desc_et.setText(passwordResults.description);
// make delete button visible since user could want to delete entry.
delete_btn.setVisibility(View.VISIBLE);
} else {
// since user is creating a new entry dont show delete button.
delete_btn.setVisibility(View.GONE);
}
}
Here is my code for my Database class which handles the retrieval of information in my database.
public void addPassword(String n, String w, String u, String p, String d) {
// get database.
SQLiteDatabase db = getWritableDatabase();
try {
// add scores.
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, n);
values.put(COLUMN_WEBSITE, w);
values.put(COLUMN_USERNAME, u);
values.put(COLUMN_PASSWORD, p);
values.put(COLUMN_DESC, d);
// insert will handle null values. closing.
db.insert(TABLE_NAME, "", values);
db.close();
} catch (Exception e) {
e.getLocalizedMessage();
}
}
public void removePassword(String id){
// get database.
SQLiteDatabase db = getWritableDatabase();
// delete database then close or print error.
try {
db.delete(TABLE_NAME, "_id="+id, null);
db.close();
} catch(Exception e) {
e.getLocalizedMessage();
}
}
public void updatePassword(String id, String n, String w, String u, String p, String d) {
// get database.
SQLiteDatabase db = getWritableDatabase();
//update database then close or print error.
try {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, id);
values.put(COLUMN_NAME, n);
values.put(COLUMN_WEBSITE, w);
values.put(COLUMN_USERNAME, u);
values.put(COLUMN_PASSWORD, p);
values.put(COLUMN_DESC, d);
db.update(TABLE_NAME, values, "_id="+id, null);
db.close();
} catch (Exception e) {
e.getLocalizedMessage();
}
}
public ArrayList<PasswordResults> getPasswords() {
// get database, password array, and select statement.
passwords = new ArrayList<>();
String refQuery = "Select "+COLUMN_NAME+", "+COLUMN_WEBSITE+", "+COLUMN_USERNAME+", "+COLUMN_PASSWORD+", "+COLUMN_DESC+" FROM "+TABLE_NAME;
SQLiteDatabase db = getWritableDatabase();
// link to database
Cursor cursor = db.rawQuery(refQuery, null);
if(cursor.moveToFirst()) {
do {
PasswordResults passwordResults = new PasswordResults();
passwordResults.entryName = cursor.getString(0);
passwordResults.website = cursor.getString(1);
passwordResults.username = cursor.getString(2);
passwordResults.password = cursor.getString(3);
passwordResults.description = cursor.getString(4);
passwords.add(passwordResults);
} while(cursor.moveToNext());
}
db.close();
return passwords;
}
public ArrayList<PasswordResults> getSelectedPassword(String id) {
// get database, password array, and select statement.
passwords = new ArrayList<>();
String refQuery = "Select "+COLUMN_NAME+", "+COLUMN_WEBSITE+", "+COLUMN_USERNAME+", "+COLUMN_PASSWORD+", "+COLUMN_DESC+" FROM "+TABLE_NAME+" WHERE "+COLUMN_ID+" = "+id;
SQLiteDatabase db = getWritableDatabase();
// link to database
Cursor cursor = db.rawQuery(refQuery, null);
if(cursor.moveToFirst()) {
do {
PasswordResults passwordResults = new PasswordResults();
passwordResults.id = Integer.parseInt(id);
passwordResults.entryName = cursor.getString(0);
passwordResults.website = cursor.getString(1);
passwordResults.username = cursor.getString(2);
passwordResults.password = cursor.getString(3);
passwordResults.description = cursor.getString(4);
passwords.add(passwordResults);
} while(cursor.moveToNext());
}
db.close();
return passwords;
}
And here is my code for PasswordResults class.
public class PasswordResults {
public int id;
public String entryName;
public String website;
public String username;
public String password;
public String description;
}
Could be an easy fix like half the things I put on here but thanks for your help in advance.
If your id is a String, you have to change +id inside your query to + '"' + id + '"', so it will be treat as a String.
String refQuery = "Select "+COLUMN_NAME+", "+COLUMN_WEBSITE+", "+COLUMN_USERNAME+", "+COLUMN_PASSWORD+", "+COLUMN_DESC+" FROM "+TABLE_NAME+" WHERE "+COLUMN_ID+" = "+ '"' + id + '"';
Odds on no rows are being selected by the getSelectedPassword. The do...while construct won't be entered (i.e. cursor.moveToFirst() returns false) and thus the result an empty ArrayList being returned that has no elements and thus index 0 is out of bounds.
Check the ArrayList's size and only attempt to get the password if the size is greater than 0. Perhaps Toast or something to indicate the error.
Obviously you then need to ascertain why the id being passed is not found, which will be the root cause.

How to do addition on a specific column?

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

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 iterate and retrieve over all data stored in sqlite database

I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.

Android SQLite: Spinner + select sql methods

I have a Spinner which is showing SQLite data. For that I am using this select method:
public List<String> getAllProductsName(int id)
{
String buildSQL = "SELECT nome FROM " + DatabaseHelper.Produtos.TABELA + " WHERE id =" + id;
List<String> nomes = new ArrayList<String>();
SQLiteDatabase db = this.getDatabase();
Cursor cursor = database.rawQuery(buildSQL, null);
if (cursor.moveToFirst()) {
do {
nomes.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return nomes;
}
The thing is, I am getting only the names but I need the ID as well. I know i could use "SELECT nome, _id FROM ", but how would I return that? Could i possibly return 2 lists (one with IDS and the other one with the Names) in the same method?
Or maybe I should create a new method that show the Names only (when i give the ID as a parameter)? Please help! thanks in advance! :)
How about something like this ... using and returning HashMap that contains ID as keys and nome as values
public HashMap<Integer,String> getAllProductsName(int id)
{
String buildSQL = "SELECT nome,_id FROM " + DatabaseHelper.Produtos.TABELA + " WHERE id =" + id;
HashMap<Integer,String> idAndNomes = new HashMap<Integer,String>();
SQLiteDatabase db = this.getDatabase();
Cursor cursor = database.rawQuery(buildSQL, null);
if (cursor.moveToFirst()) {
do {
idAndNomes.put(cursor.getInt(1), cursor.getString(0)));
} while (cursor.moveToNext());
}
return idAndNomes;
}
Then you can use:
idAndNomes.keySet() - Returns a set of the keys contained in this map. In our case ID.
idAndNomes.values() - Returns a collection of the values contained in this map. In our case nomes.

Categories

Resources