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.
Related
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
I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !
I am creating app in which i register user and store user's information in database,so i have created database and storing value in databse but i don't know how to fetch data from database and show in textview?Using below query to fetch data but it has error.What is correct way?
public void insertEntry(String fname, String lname, String gen,String weight)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", gen);
values.put("weight",weight);
}
public Cursor fetchData()
{
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
return mDB.rawQuery("SELECT * FROM Register WHERE firstname=? lastname =?" , null);
}
Using this to set fetched value on textview in different activity
Cursor name = sqliteDataBase.fetchData();
tv_name.setText((CharSequence) name);
Try this,
try {
SQLiteDatabase mDB = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM Register WHERE firstname= "+first+" lastname =" + last + ";";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
String firstName = cursor.getString(cursor.getColumnIndex("firstname")));
}
}
} catch(Exception e) {
e.printSTackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
public String fecthResults()
{
String name = null;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
name = cursor.getString(cursor.getColumnIndex("firstname")
} while (cursor.moveToNext());
cursor.close();
}
sqLiteDatabase.close();
return name;
Get the name and then set it directly to a texView
A Cursor is an interface that provides random read-write access to the result set returned by the query. It contains multiple rows of data and this data can be easily processed by help of For loop.
Lets take an example to understand the process. Suppose, you need to access data from a column name "col_1" and show the data in TextView. The For loop for the process will be as follows.
for (cursor.moveToNext()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Now, if we need only one value (from only one record or tuple) then, we can opt out the For loop and change the code as shown below.
if (cursor.moveToFirst()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Always remember to close the cursor after using it.
To close the cursor, use the following line of code.
cursor.close();
For more information, please visit the following links:
https://developer.android.com/reference/android/database/Cursor.html
https://developer.android.com/training/basics/data-storage/databases.html#ReadDbRow
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.
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....