Android error, cannot bind argument because index is out of range - android

I have given a statement in DBAdapter class as follows
String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
+ "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
+ "WHERE T.Trans_Date ='"+ date +"' AND T.Trans_Type='debit' ORDER BY T.Entry_Time asc";
return db.rawQuery(sql, new String[]{KEY_ACCNO,KEY_ACCCUSTNAME,KEY_TRANSAMOUNT});
My activity calling is given below
public void onClick(View v) {
try {
db.open();
Cursor c = db.gettranscation();
if (c.moveToFirst()) {
do {
DisplayDetails(c);
} while (c.moveToNext());
}
db.close();
} catch (Exception e) {
// TODO: handle exception
Log.e("Retrive Error ", " "+e.getMessage());
}
}
private void DisplayDetails(Cursor c) {
Log.e("",
"KEY_ACCID Id : " + c.getString(0) + "\n" + "KEY_TRANSDATE :"
+ c.getString(1) + "\n" + "KEY_TRANSTYPE : " + c.getString(2));
}
});
But I am getting this error :
Cannot bind argument at index 3 because the index is out of range. The
statement has 0 parameters.
What is the error in my code ??

try this....
String sql = "SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt
FROM TransactionTable T
LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID
WHERE T.Trans_Date =? AND T.Trans_Type=?
ORDER BY T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{"18-08-2014", "debit"});

You're not putting well "SelectionArgs". To put it well in the query you have to add the character "?" where you want this argument.
The official documentation Here
Example:
String sql = "SELECT * FROM USER WHERE id = ?";
db.rawQuery(sql, new String[]{idUser});
EDIT
You aren't using never SelectionArgs because you are binding params directly.
Try this.
return db.rawQuery(sql,null);

Related

how to get sum of values of cursor retrieved values in Android

i have retrieved some values from DB using the query which is given below.
public Cursor getcredittranscation(String date)
{
String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
+ "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
+ "WHERE T.Trans_Date =? AND T.Trans_Type=? ORDER BY T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{date, "credit"});
return cursor;
}
And in main activity i want to show these results as a report. Activity code is as given below.
try{
db.open();
Cursor c = db.getdebittranscation(temp);
if (c.moveToFirst()) {
do {
DisplayDebitDetails(c);
debittotal(c);
} while (c.moveToNext());
}
db.close();
}catch (Exception e) {
// TODO: handle exception
Log.e("Retrive Debit Error ", " "+e.getMessage());
}
private void DisplayDebitDetails(Cursor c) {
String tempdebit = debitView.getText().toString() + " ";
tempdebit= " \t"+tempdebit+ "\n\t" +c.getString(0) + "\t\t\t"
+ c.getString(1) + "\t\t\t" + c.getString(2);
debitView.setText(tempdebit);
Log.e("debit", "Acc No :"+c.getString(0) +"Name :"+c.getString(1)+ "Trans Amnt :"+c.getString(2));
}
}
private void debittotal(Cursor c){
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
Retrieving and viewing all values is ok... But i need the sum of all values in String(2) . which is given in method debittotal(Cursor c). what is the error in that part ?? I am not getting total
you can use getCount() method
int number_of_records = cursor.getCount();
try this and make sure that debitTotalView.getText().toString() is not blank or null
initially that field value must be 0 otherwise it will give you NumberFormatException for invalid int value
replace
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
with
int tmp = Integer.parseInt(debiTotalView.getText().toString().trim());
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp+"");

Sqlite form of query

i have an issue with both functions
// Insert a new contact in database
public void insertInSignature(String TITLE_SI) {
try {
// Open Android Database
Boolean b = checkIsDataAlreadyInDBorNot("DELIVERY_SLIP",
"TITLE_SI", TITLE_SI);
if(b==false)
{
// cursor is empty
ContentValues initialValues = new ContentValues();
initialValues.put("TITLE_SI", TITLE_SI);
db.insertWithOnConflict("DELIVERY_SLIP", null, initialValues,
SQLiteDatabase.CONFLICT_IGNORE);
}
} catch (SQLException sqle) {
Log.e(TAG, "insertUser Error");
Log.e(TAG, "Exception : " + sqle);
} finally {
// Close Android Database
databaseHelper.close();
}
}
public boolean checkIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
db = databaseHelper.getWritableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + "="
+ "`"+ fieldValue+"`";
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
return false;
}
return true;
}
I have this function , I'm inserting signature when it's not on the database.. But the function boolean return an SQLexception i don't know why i found informations about the form , but not for my problem.
Here my log.
http://hpics.li/0ae4ba2
I just want to know if the row exist on my database
here my table.
http://hpics.li/1fd3d9a
Thanks by advance if you need for informations ask me
In SQL, strings are delimited with single quotes ', not backticks `.
To avoid such formatting problems, and SQL injections, you should use parameters instead:
String query = "SELECT * FROM " + TableName + " WHERE " + dbfield + "= ?";
Cursor cursor = db.rawQuery(query, new String[] { fieldValue });
Instead of doing a query every time you want to insert, why not make the TITLE_SI column UNIQUE with ON CONFLICT IGNORE or ONC CONFLICT REPLACE? Then you don't need to check, you simply insert and let the uniqueness constraint manage this for you.

getting values from column in database

I am getting values from the column "threadid" in the database.Problem is that it gets the value from the previous record/row. and when I try to get the first record my app crashes,, How to tackle this problem and whats the issue?
long id;
long threadid = datasource.getthreadid(id);
Toast.makeText(getActivity(), String.valueOf(threadid), Toast.LENGTH_SHORT).show();
public long getthreadid(long id)
{
String ide=String.valueOf(id);
String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID
+ " FROM " + MySQLiteHelper.TABLE_NAME
+ " WHERE " + MySQLiteHelper.COLUMN_ID + "=" + ide;
Cursor cursor = database.rawQuery(queryz, null);
cursor.moveToFirst();
// cursor.moveToPosition(Integer.parseInt(String.valueOf(id)));
long threadid= cursor.getLong(cursor.getColumnIndex("threadid"));
cursor.close();
return threadid;
}
If you are only expecting one row. Then it might be useful to do something like this.
long threadid;
if (cursor.moveToFirst())
{
threadid = cursor.getLong(cursor.getColumnIndex("threadid"));
}
else
{
// ah oh, we do not have this id!
// do something here if you need to
}
Also, if you are going to use strings, I recommend you bind the parameters. I know you had a long beforehand, but for strings you can do this.
String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID
+ " FROM " + MySQLiteHelper.TABLE_NAME
+ " WHERE " + MySQLiteHelper.COLUMN_ID + " = ?";
Cursor cursor = database.rawQuery(queryz, new String[]{ide});
To get all the records, you first need to move to the first one, then you iterate through the rest.
if (cursor.moveToFirst()) {
do {
// get row values
} while (cursor.moveToNext());
}
cursor.close();

retrieve all data from all columns from an inner join result

How do I retrieve the data on all columns from an INNER JOIN result? I use this query:
SELECT course.course_title,
course.course_body,
course. course_image,
instructor.instructor_title,
instructor.instructor_body,
instructor.instructor_photo
FROM course
INNER JOIN instructor
ON course.course_instructor1=instructor.instructor_nid
WHERE course_id=4
and this is the equivalent variable COURSE_OUTLINE that i'll be using to execute
String COURSE_OUTLINE =
"SELECT " + Qualified.COURSE_TITLE + ", "
+ Qualified.COURSE_BODY + ", "
+ Qualified.COURSE_IMAGE + ", "
+ Qualified.INSTRUCTOR_TITLE + ", "
+ Qualified.INSTRUCTOR_BODY + ", "
+ Qualified.INSTRUCTOR_IMAGE + ", " +
"FROM " + Tables.COURSE_JOIN_INSTRUCTOR +
"WHERE " + CourseColumns.COURSE_ID +
"=?";
In my code,
Cursor cur = mSqliteDb.rawQuery(SubQuery.COURSE_OUTLINE, new String[] {position});
This gives 1 record. I know how to retrieve data from a specific column but I'm not sure how to retrieve it from all columns.
this is the code I use to retrieve data from a specific column
public String getCourseImage(int position) {
String image = "";
String pos = Integer.toString(position);
Cursor cur = mSqliteDb.rawQuery(SelectQuery.ALL_COURSES, new String[] {pos});
if (cur != null) {
if (cur.moveToFirst()) {
do {
image = cur.getString(cur.getColumnIndex(CourseColumns.COURSE_IMAGE));
} while (cur.moveToNext());
}
cur.close();
}
return image;
}
My intention is mapping each data in a column to a View
getColumnNames gives you an array with all columns... if that's what you're asking. It's kind of hard to tell.

How to match or compare a date string with the date stored in sqlite in android?

Actually I am working on this for the last 3 or 4 weeks but have not able to resolve it.
I am working on Sqlite Database in android in which I have used a date picker control in my activity Once a user sets a date then i'll stored the date into the string and then sends it to the database it is working fine but when i tried to retrieve the date on the basis of date set on date picker control then it doesn't give me the desired output it show the only a line which is opening a database on my catlog.
Database Class
//Table Definition with Columns
private static final String CREATE_MYCOMPANY =
"create table company " + " (" + "_id" + " integer primary key autoincrement, "
+ "company_date" +" date);";
//Insert Method
public long create(String str) {
ContentValues args = new ContentValues();
args.put(KEY_COMPANY_DATE, str);
return mDb.insert(MYCOMPANY, null,args);
}
//Method For Fetching the row on the basis of Date.//
public Cursor fetchdate(String datr) throws SQLException, ParseException {
Cursor mCursor =
mDb.query(true, MYCOMPANY, new String[] {KEY_COMPANY_ID,
KEY_COMPANY_DATE}, KEY_COMPANY_DATE /*+" BETWEEN date('2012-6-10') AND date('2012-6-14')"*/
+ " = " + datr, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Activity Class Code
//Date picker
DatePicker dt = (DatePicker)findViewById(R.id.datePicker1);
//Converting the Date into the string format
String day = String.valueOf(dt.getYear())+"-" +String.valueOf(dt.getMonth() + 1)
+"-"+String.valueOf(dt.getDayOfMonth());
//Method for displaying the rows of table on date basis
public void DisplayAllCmpData(){
employeeTable.open();
try{
Cursor c = employeeTable.fetchdate("2012-6-13");
if (c.moveToFirst())
{
do {
System.out.println("bool2");
DisplayCmpTitle(c);
} while (c.moveToNext());
}
}catch(Exception e){
System.out.println(e);
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
employeeTable.close();
}
//Function For Displaying the all record.//
public void DisplayCmpTitle(Cursor c)
{
System.out.println("bool");
Toast.makeText(this,
"ID: " + c.getString(0) + "\n" +
"DATE: " + c.getString(1)
, Toast.LENGTH_LONG).show();
}
Thanks for any help in advance!!!!!!
mDb.query(true, MYCOMPANY, new String[] {KEY_COMPANY_ID,
KEY_COMPANY_DATE}, KEY_COMPANY_DATE /*+" BETWEEN date('2012-6-10') AND date('2012-6-14')"*/
+ " = '" + datr+"'", null,
null, null, null, null);

Categories

Resources