Hi guys i have a huge problem that in cannot reoslve... it's simple, y have a ListView and when y click in a one item of the ListView I get the "Rubro" of that item and it's fine...the problem is that I have a method that I do a query of comapre this Rubro and get a Long att form the table but, the query dont work!! but i know that the query is good because I prove it whit the DB Brwoser for SQLite!! so here is the code where i call the method:
public void onClick(DialogInterface dialog, int id) {
TextView selectR = (TextView) view.findViewById(R.id.Rubro);
TextView selectV = (TextView) view.findViewById(R.id.Valor);
Long ac = db.Buscar_Rubro(selectR.getText().toString()); //THIS IS THE METHOD!
EditText r = (EditText) dialogV.findViewById(R.id.Mod);
Long Sum = Long.parseLong(r.getText().toString());
db.ModRubros(Long.parseLong(selectV.getText().toString()),ac,Sum);
Cursor cT = db.ListarRubros();//RefreshRubros(cT, from, to);
}
And here is the Method:
public long Buscar_Rubro(String Rubro){
SQLiteDatabase DB = database.getReadableDatabase();
String Query ="SELECT " + Database.ValorActrual + " FROM "+ Database.Taba_Rubros + " WHERE " + Database.Rubro + " LIKE '"+ Rubro +"'" ;
Cursor c = DB.rawQuery(Query,null);
Long ac = c.getLong(1);
return ac;
}
Please help me! I lost all the day to correct this!
PD: This is the error that i get but it's obvios becuae the query dont work!
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
You should do like
String Query ="SELECT " + Database.ValorActrual + " FROM "+ Database.Taba_Rubros + " WHERE " + Database.Rubro + " LIKE '"+ Rubro +"'" ;
Cursor c = DB.rawQuery(Query,null);
if (c != null && c.moveToFirst()) {
Long ac = c.getLong(0);
}
Related
I'm new to android, and I don't know why I am getting CursorIndexOutOfBoundsException: Index 0 requested with a size of 0. I'm trying to display it on another class using listview. Here are my codes:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String aa = a.getString(a.getColumnIndex("name"));
Cursor b = MainActivity.sqldb
.rawQuery("Select phone from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
String bb = b.getString(b.getColumnIndex("phone"));
Intent next = new Intent (this, ThirdActivity.class);
startActivity(next);
}
I know that there's something really wrong here. And I wonder what it is.
Create Table:
sqldb = this.openOrCreateDatabase(dbpb, MODE_PRIVATE, null);
sqldb.execSQL("CREATE TABLE IF NOT EXISTS "
+ tblpb
+ " (_pid INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, phone INTEGER);");
Insert Table:
sqldb.execSQL("Insert into " + tblpb
+ " (name, phone) Values ('" + x + "' , '"
+ y + "' );");
Try doing this:
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
String aa = null;
String bb = null;
// do not alter the position, DB starts the same position as ItemClick for
// adapter view
// position = position + 1;
Cursor a = MainActivity.sqldb
.rawQuery("Select name from " + MainActivity.tblpb
+ " where _pid = " + position + ";", null);
if(a != null){
// Force cursor to position 0
if(a.moveToFirst()){
// make sure the column actually exists
aa = a.getString(a.getColumnIndexOrThrow("name"));
Log.d("Cursor A - Name", "name column val: "+ aa);
}else{
Log.d("Cursor A", "cursor A failed to move to first");
}
}else{
Log.d("Cursor A null", "cannot access cursor A");
}
Cursor b = MainActivity.sqldb.rawQuery("Select phone from " + MainActivity.tblpb + " where _pid = " + position + ";", null);
if(b != null){
// Force cursor to position 0
if(b.moveToFirst()){
// make sure the column actually exists
bb = b.getString(b.getColumnIndexOrThrow("phone"));
Log.d("Cursor B - Phone", "phone column val: "+ bb);
}else{
Log.d("Cursor B", "cursor B failed to move to first");
}
}else{
Log.d("Cursor B null", "cannot access cursor B");
}
Intent next = new Intent (this, ThirdActivity.class);
next.putExtra("NAME", aa);
next.putExtra("PHONE", bb);
startActivity(next);
}
Then in your second Activity do:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.content_file);
Bundle extras = getIntent().getExtras();
if(extras != null){
String aa = extras.getString("NAME");
String bb = extras.getString("PHONE");
// Since you cannot tell if these are null check them
if(aa != null){
// ... Use on your TextView
}
// Since you cannot tell if these are null check them
if(bb != null){
// ... Use on your TextView
}
}
}
The error indicates that you are trying to access the first element (index 0) of an empty list (size 0) meaning your queries are returning no results. Make sure your queries are correct.
EDIT:
It's also a good idea to call cursor.moveToFirst() and check its result before doing any operations on the data from a query.
http://developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29
I'm trying to load a database column with a cursor result for my quiz app. The reason for this is that i want to populate a list view with the questions in a each category so i set up this:
public void putValues(){
for (int i = 0; i < 18; i++) {
Cursor contentCursor = null;
contentCursor = mDB
.rawQuery("select count(*) from questions_en where used = 0 and category" + " = " + i, null);
if(contentCursor.getCount() >0 )
contentCursor.moveToFirst();
if (contentCursor.isAfterLast()) {
contentCursor.close();
mDB.close();
return;
}
int contentCursorInt = contentCursor.getInt(0);
Cursor upateCursor = null;
upateCursor = mDB.rawQuery("update categories_en set questions_count" + " = " + contentCursorInt + " where " + "_id" + " = " + i, null);
upateCursor.moveToNext();
upateCursor.close();
contentCursor.close();
}
}
so that when the user clicks an answer (on the question screen) used becomes 1(or any non-zero value) the query result changes. The above code works fine the very first time. Because i haven't set up the question screen, i added this query:
public void test(){
Cursor cus = mDB.rawQuery("update questions_en set used = 1 where category = 2 and _id = 146", null);
cus.close();
}
to my DB Adapter and then called this method from my MainActivty
#Override
public void onClick(View v) {
TestAdapter mTest = new TestAdapter(MainActivity.this);
mTest.createDatabase();
mTest.open();
mTest.test();
Log.d(DBHelper.TAG, " Worked ");
mTest.close();
}
});
But when i click on this and go to my ListActivity I expected the value of category 2 to have changed since the query had just been carried out again. But it doesn't reduce. I pulled out my DB from DDMS(file explorer) and i found out that the query to _id = 146 actually didn't change used to 1. Any help on what may be the cause?
Solve the problem with the help of this.
I just changed this:
public void test(){
Cursor cus = mDB.rawQuery("update questions_en set used = 1 where category = 2 and _id = 146", null);
cus.close();
}
to this
public void test(){
int id = 3;
ContentValues data = new ContentValues();
data.put(DBHelper.KEY_USED, "1");
mDB.update(DBHelper.KEY_QUESTIONS_TABLE, data, DBHelper.KEY_ID + " = " + id , null);
}
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();
name = namebox.getText().toString();
db.open();
Cursor c1 = db.executequery("SELECT _id FROM " + DATABASE_TABLE_CUSTOMER + " where name='" +name+"'" );
_id = c1.getInt(c1.getColumnIndex("name"));
Cursor c2 = db.executequery("SELECT amount FROM " + DATABASE_TABLE_CUSTOMER
+
" where _id=" + _id);
Double amount = c2.getDouble(c2.getColumnIndex("amount"));
Cursor c3 = db.executequery("SELECT arrear FROM " + DATABASE_TABLE_CUSTOMER + " where CUSTOMER_ID =" + _id);
arrear = c3.getDouble(c3.getColumnIndex("arrear"));
db.close();
This is giving me a bad request for field error. The method executequery on my adapter looks like this:
public Cursor executequery(String query) throws SQLException
{
Cursor mCursor = db.rawQuery(query, null);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
Can anyone please tell me what Im doing wrong. Im new at this.
You are being inconsistent when dealing with Cursor1. getColumnIndex("name") cannot succeed because IDs, not names are being SELECTed. It should read getColumnIndex("_id").
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Fetch data in database table insert it if not exist else return the row id
I try to fetch if data exist in database table, if yes I should get the row id else I insert it in the table this my code
public int finddate(String date){
int id=0;
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " +
AndroidOpenDbHelper.TABLE_DATE + " where " +
AndroidOpenDbHelper.COLUMN_NAME_DATE + " = " + date,
null);
startManagingCursor(cursor);
if (cursor != null) {
if( cursor.moveToFirst() ) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
} else {
id=0;
}
sqliteDatabase.close();
return id;
}
when i try with an existing item I get the result of this method =0 and the item is inserted in the table,
how can I do this?
The date is not being correctly escaped. The safest and cleanest way to resolve it is to pass the date value as a parameter, rather than embedding it in the query.
You can also tidy up the cursor management quite a bit. You don't need to check for a null cursor, as an exception will be thrown if the query fails. Also, you don't need to set id = 0 as you've already done that at the start. This is much simpler:
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " +
AndroidOpenDbHelper.TABLE_DATE + " where " +
AndroidOpenDbHelper.COLUMN_NAME_DATE + " = ?",
new String[] { date } );
if ( cursor.moveToFirst() ) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
cursor.close();
sqliteDatabase.close();
Your query should look like this:
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " + AndroidOpenDbHelper.TABLE_DATE + " where "+ AndroidOpenDbHelper.COLUMN_NAME_DATE+ " =\'"+date+"\'", null);
startManagingCursor(cursor);
cursor.moveTofirst();
if (cursor.getCount() > 0) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
} else {
id=0;
}