Anyone? please help me to figure this out. I'm getting an android.database.cursorindexoutofboundsexception error and I don't why. I'm sure that I name my columns correct but still I got it. What I am trying to do is just to get the companycode of the given company name.
Here my code my DatabaseAdapter
public Cursor getCompanyCode(String company)
{
Cursor c = dbSqlite.query(Constants.DATABASE_TABLE_COMPANY,
new String[] { Constants.DATABASE_COLUMN_ID,
Constants.COMPANY_CODE,Constants.COMPANY_NAME},
Constants.COMPANY_CODE+" = ?",
new String[]{company}, null, null, null);
if (c != null)
{
c.moveToFirst();
}
return c;
}
and here another code to get company code of the given company
Cursor companyCode = databaseAdapter.getCompanyCode(company);
code = companyCode.getString(companyCode.getColumnIndex(Constants.COMPANY_CODE));
and here is my logcat.
06-04 12:54:48.085: E/AndroidRuntime(27134): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.uni.customercare/com.uni.customercare.ViewSummaryActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Try this approach:
define this method in your database helper class which extends SQLiteOpenHelper. Use an instance of the class to call this method.
public HashMap<String, String> getCompanyDetails(){
HashMap<String,String> company= new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_COMPANY; //Change this query accordingly.
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
company.put(KEY_COMP_ID, cursor.getString(0));
company.put(KEY_COMP_CODE, cursor.getString(1));
company.put(KEY_COMP_NAME, cursor.getString(2));
}
cursor.close();
db.close();
return company;
}
Simple way to work with cursor companyCode..
companyCode.moveToFirst();
while( !companyCode.isAfterLast() ) {
//do something with companyCode..
//.....
companyCode.moveToNext();
}
companyCode.close()
Related
I am retrieving data according to dates but when running my app its shows nothing.
Here's my code :
SQL QUERY :
private Cursor getAllCurrentData()
{
String[] selectArg = new String[]{};
return db.query(Db_Contract.Db_Fieds.TABLE_NAME,
null ,
Db_Contract.Db_Fieds.DATE+ "= 2018-11-10",
selectArg,
null,
null,
Db_Contract.Db_Fieds.TIMESTAMP);
}
Displaying Data :
private void totalMoney()
{
Cursor cursor = getAllCurrentData();
double sum = 0.000d;
double getMoney;
while (cursor.moveToNext()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
}
total.setText("Total money spent: " +sum);
}
I am new to Android Programming. Where I am doing wrong ?. Please correct me
First make sure you are connected to database and cursor returned by db.query() is not empty/null. Then Iterate over cursor like
private void totalMoney()
{
openDatabase();
Cursor cursor = getAllCurrentData();
cursor.moveToFirst();
double getMoney = 0;
while (!cursor.isAfterLast()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
cursor.moveToNext();
}
total.setText("Total money spent: " + sum );
closeDatabase();
}
I have an app that uses a cursor to run an SQlite query.
public Cursor totaltrips(){
Cursor cursor = database.rawQuery("SELECT * AS TTotal FROM " + DatabaseHelper.TABLE_NAME, null);
return cursor;
}
The results are stored to an Arraylist with a maximum of 5 values. If there are no records in the database the app crashes. If I have one or more database entries it works fine. Does anyone know how I can stop it from crashing when there are no database entries?
// get column value
if (Distance.moveToNext())
result = String.valueOf(Distance.getDouble(Distance.getColumnIndex("myTotal")));
tnmView.setText(result);
List<String> distancearray = new ArrayList<String>();
Cursor cursor = dbManager.totaldistance();
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
ttrips = cursor.getCount();
Log.i("Graph", "TTRIPS = " + ttrips);
// Be sure here to have at least the 5 desired elements into the list
while(distancearray.size() < 5){
distancearray.add("0");
}
The app crashes with the error
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
On the line
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
Check if cursor actually has results, try something like this for example:
int numResults = cursor.getCount();
if (numResults > 0) {
do {
distancearray.add(cursor.getString(1));
} while ((cursor.moveToNext()));
}
Replace
do{
distancearray.add(cursor.getString(1));
}while ((cursor.moveToNext()));
with
if (cursor != null) {
while (cursor.moveToNext()) {
distancearray.add(cursor.getString(1));
}
cursor.close();
}
Check if cursor is null and has more than one value.Close cursor after uses.
if(cursor!=null&&cursor.getCount()>0){
cursor.moveToFirst();
while(cursor.hasNext()){
//do stuff here
}
cursor.close();
}
This is an headache I am trying it from a long but still no where this code giving me error
MainActivity.class
try{
handler = new DataHandler(this);
handler.open();
c = handler.getAllMainData();
c.moveToFirst();
while(!c.isAfterLast()){
CampaignId.add(c.getInt(0), null);
CampaignName.add(c.getString(1));
Message.add(c.getString(c.getColumnIndex("message")));
StartDate.add(c.getString(c.getColumnIndex("start_date")));
Repeat.add(c.getString(c.getColumnIndex("repeat")));
c.moveToNext();
}
handler.close();
}
catch(Exception e){
Log.d("Error",e.toString());
}
getAllMainData in DataHelper Class
public Cursor getAllMainData(){
String sql= "SELECT * FROM "+CampaignMain_TABLE;
return db.rawQuery(sql, null);
}
Error is
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
Select * From campaign_name will retrive more columns then i am selecting in the MainActivity // I guess that shouldnt be aproblem but just for becoming more descriptive
At which line exactly you are getting IndexOutOfBoundsException exception? Are you sure your cursor is not null/empty? I think it should be like this:
if (cursor.moveToFirst()) {
do {
// Read data from cursor
} while (cursor.moveToNext());
}
Here is the solution for you:
while (cursor.moveToNext()) {
// Read data
}
I'm not able to add read data from the following SQLite select query function. I have a table with 3 columns, namely driverID, driversName, driversNo.
It's supposed to return a simple string but alas.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
if (cursor != null){
cursor.moveToFirst();
Log.v("TEST", Integer.toString(cursor.getCount()));
Log.v("TEST", cursor.getColumnName(0));
Log.v("TEST", cursor.getColumnName(1));
Log.v("TEST", cursor.getString(0));
Log.v("TEST", cursor.getString(1));
}
String returnString = cursor.getString(0) + cursor.getString(1);
return returnString;
}
Below are the most recent results from LogCat. The last two logs don't show, for some strange reason.
08-04 20:27:35.271: V/TEST(25126): 1
08-04 20:27:35.271: V/TEST(25126): driversName
08-04 20:27:35.271: V/TEST(25126): driversNo
Any help will be greatly appreciated.
The rest of the code is based on this tut http://www.vogella.com/tutorials/AndroidSQLite/article.html
It would be easier if you provided your table structure, but in any case, some info that might help:
Cursor starts from position -1 when not null.
A good way to read the cursor would be
while (cursor.moveToNext()) {
...
}
Also,
String returnString = cursor.getString(1) + cursor.getString(2);
The above code will concatenate column index 1 and column index 2 (please note that indexes start from 0), from first row returned from your query.
Edit:
Then something as the following should work fine.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
List<String> list = new ArrayList<String>;
while (cursor.moveToNext()) {
list.add(cursor.getString(1) + cursor.getString(2));
}
return list;
}
In my application I am saving a bill number in SQLite database. Before I add a new bill number how to check if the bill number exists in the DB.
My main class code is,
String bill_no_excist_or_not = db.billno_exist_or_not(""+et_bill_number.getText().toString());
Log.v("Bill No", ""+bill_no_excist_or_not);
My DB Code,
String billno_exist_or_not(String bill_number){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_BILL_DETAILS, new String[] { KEY_BILL_NUMBER }, KEY_BILL_NUMBER + "=?"
+ new String[] { bill_number }, null, null, null, null);
//after this i don't know how to return the values
return bill_number;
}
I don't know how to check the values which is already available or not in DB. Can any one know please help me to solve this problem.
Here is the function that helps you to find whether the value is available in database or not.
Here please replace your query with my query..
public int isUserAvailable(int userId)
{
int number = 0;
Cursor c = null;
try
{
c = db.rawQuery("select user_id from user_table where user_id = ?", new String[] {String.valueOf(userId)});
if(c.getCount() != 0)
number = c.getCount();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if(c!=null) c.close();
}
return number;
}
Make your KEY_BILL_NUMBER column in your table UNIQUE and you can just insert using insertWithOnConflict with the flag SQLiteDatabase.CONFLICT_IGNORE