CursorIndexOutOfBoundsException during my query [SQLite] - java

I want to search my database for a row where KEY_TOR == place.getTor()
Here I call the method:
DB_Place tor = db_tore.getDBPlace(place.getTor());
This is the method:
public DB_Place getDBPlace(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
new String[]{name}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
DB_Place place = new DB_Place(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return place;
}
Looks good to me, except that I am getting this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.x.x/com.example.ahok.x.UI_MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
What am I missing here? Is it possible that it has something to do with a few of the columns being null?

Looks like you don't have any data inserted in your database. Moreover, you've some logical error in your code.
I would like to edit your function like this.
public DB_Place getDBPlace(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
new String[]{name}, null, null, null, null);
DB_Place place = null;
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
place = new DB_Place(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return place;
}
Update
So if you think its an error of your query, then run simple query like this.
Cursor cursor = db.rawQuery("Select * from " + TABLE_DB_TORE_Eintrag + " where " + KEY_TOR + " = '" + name + "'", null);

Related

How to fetch all contacts using cursor and store it in strings to store them in firebase realtime database

fetch all contacts using cursor and store it in strings to store them in firebase realtime database
ArrayList<String> contactData=new ArrayList();
ContentResolver cr = getContentResolver();
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
try{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
Firebase mRefchild = mRef.child(name);
mRefchild.setValue(phoneNumber);
}
phones.close();
to get all Constact List
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
To save list or store list to firebase
Firebase ref = new Firebase("<my-firebase-app>/names"):
List nameList = new ArrayList<Type>(Arrays.asList(names));
// Now set value with new nameList
ref.setValue(nameList)

get Home Location from a contact in Contacts List Android?

i use the following code for get all Contacts:
public void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contact_Details dt = new Contact_Details(name, number, UIDD);
dataArray.add(dt);
}
pCur.close();
}
}
}
cur.close();
}
now i want to get the home location from Contacts. what can i do now. home location is shown in the following image.
use this code to retrieve address from contact
Cursor pCur2 = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur2.moveToNext())
{
String address = pCur2.getString(pCur2.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
Log.d("tag", "Address: "+address);
}
pCur2.close();
this retrieve both phone and address
public void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext())
{
String number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("tag", "PhoneNumber: "+number);
}
pCur.close();
//get address of the phone
Cursor pCur2 = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur2.moveToNext())
{
String address = pCur2.getString(pCur2.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
Log.d("tag", "Address: "+address);
}
pCur2.close();
}
}
}
cur.close();
}

Cannot Fetch a Data From Database

First of all i'm new to Android Development.
I'm having some issues with fetching data from database. Whenever i try to fetch a data, the cursor is being empty.
Here is my code:
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> List = new ArrayList<Word>();
if(cursor != null){
cursor.moveToFirst();
while (cursor.moveToNext()){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return List;
}
The size of the cursor is always 1 but the size of the "List" variable is always 0.
I didn't understand the problem, thanks for helping me.
You are shifting the cursor position twice. Just remove the line cursor.moveToFirst(); The moveToNext method is sufficient as it moves to the first position on the first iteration.
you can use this code:
1-If you need first row:
if(cursor != null){
cursor.moveToFirst();
if(cursor.isAfterLast() == false){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
2- if you need several rows :
if(cursor != null){
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
List.add(new Word(cursor.getString(cursor.getPosition())));
cursor.moveToNext();
}
}
I checked everything but your recommendations didn't worked. Just to be sure: I want to fetch all rows.
Try like this
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> list = new ArrayList<Word>();
if(cursor != null){
while (cursor.moveToNext()){
list.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return list;
}
I just realised that the program does not go into the while loop in the code that i given above. I think there is a problem with database.
I used that query to create database:
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME_TURKISH + " TEXT, " +
COLUMN_NAME_ENGLISH + " TEXT, " +
COLUMN_NAME_GERMAN + " TEXT, " +
COLUMN_NAME_FRENCH + " TEXT, " +
COLUMN_NAME_ARABIC + " TEXT, " +
COLUMN_NAME_RUSSIAN + " TEXT, " +
COLUMN_NAME_SPANISH + " TEXT, " +
COLUMN_NAME_ITALIAN + " TEXT)";
I feel like a idiot because i forgot to type the database name at the constructor method like that:
Old
super(context, null, null, 1);
Now
super(context, "database", null, 1);
Thanks for your help!

Cursor index out of bounds exception that is passing null check

I checked a bunch of questions here and I cannot find correct answer. I have problem with retrieving data from my database. I get android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0 exception. My code for creating database:
String KREIRAJ_TABELU = "CREATE TABLE " + IME_TABELE + "("
+ ID + " INTEGER PRIMARY KEY," + PITANJE + " TEXT,"
+ PRVI_NETACAN + " TEXT," + DRUGI_NETACAN + " TEXT," + TRECI_NETACAN + " TEXT," + TACAN_ODGOVOR + " TEXT" + ")";
db.execSQL(KREIRAJ_TABELU);
String dodajPitanjaIOdgovore = "INSERT INTO pitanja (ID,PITANJE,PRVI_NETACAN,DRUGI_NETACAN,TRECI_NETACAN,TACAN_ODGOVOR)\n" +
"VALUES (0,\"Ovo je prvo pitanje:\",\"Netacan odgovor\",\"Netacan odgovor\",\"Netacan odgovor\",\"Tacan odgovor\");\n" +
"\n" + ...
db.execSQL(dodajPitanjaIOdgovore);
And for retriving data I use this piece of code:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(IME_TABELE, new String[]{ID,
PITANJE, PRVI_NETACAN, DRUGI_NETACAN, TRECI_NETACAN, TACAN_ODGOVOR}, ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if(cursor.getCount() > 0)
{
cursor.moveToFirst();
}
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return podaci;
Edit: I also tried this:
if (cursor.moveToFirst()) {
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
else{
podaciOPitanjima podaci;
}
podaciOPitanjima podaci = new podaciOPitanjima(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
return podaci;
Change
if (cursor.getCount() > 0) {
cursor.moveToFirst();
}
//do operations here
To
if (cursor.moveToFirst()) {
//do operations here
}
Explanation - the problem is this line:
podaci = new poda...ima(Integer.parseInt(cursor.getString(0)), ...);
When you use cursor.getString the cursor is not actually at a row (because there is no row), so you cannot get a cell/column which is what this command is asking for.
The full solution:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(IME_TABELE, new String[]{ID, PITANJE, PRVI_NETACAN, DRUGI_NETACAN, TRECI_NETACAN, TACAN_ODGOVOR}, ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
podaciOPitanjima podaci = null;
if (cursor.moveToFirst()) {
//Note: using getColumnIndex avoids errors if the columns are ever returned in a changed order
podaci = new podaciOPitanjima(
cursor.getInteger( cursor.getColumnIndex(ID) ),
cursor.getString( cursor.getColumnIndex(PITANJE) ),
cursor.getString( cursor.getColumnIndex(PRVI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(DRUGI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(TRECI_NETACAN) ),
cursor.getString( cursor.getColumnIndex(TACAN_ODGOVOR) ));
}
return podaci;
Now remember wherever you are calling this method, that you might get null back and that you need to check for that.

How do I within SQLite, return a row based on 3 values rather than just one? (Already done code for 1)

Within SQLite, I can search a table for a particular row which contains 1 values for instance a player name but I want to return a row based on 3 values for instance Player name, Team name and favorite color etc.
How do I alter below code to do this?
Code for searching based upon one value is below:
public BackupDatastore getentry(String value, String columnName) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_Name,
new String[] { KEY_ID,
KEY_Team_Name,
KEY_Ref_Name,
KEY_Date,
KEY_Player_1,
KEY_Player_2,
KEY_Player_3,
KEY_Player_4,
KEY_Player_5,
KEY_Player_6,
KEY_Player_7 ,
KEY_Player_8},
columnName + "=?",
new String[] { value }, null, null, null, null);
if (cursor != null)
{
boolean move = cursor.moveToFirst();
//false value means the query returned 0 results
if(!move)
{
return BackupDatastore.kEmptyData;
}
}
BackupDatastore entry = new BackupDatastore(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11));
// return entry
return entry;
}
You need to change what you're passing as the 3rd and 4th parameters - the column names and values passed to the WHERE clause.
For example, to filter across 3 columns you'd do:
Cursor cursor = db.query(TABLE_Name,
new String[] { KEY_ID,
KEY_Team_Name,
KEY_Ref_Name,
KEY_Date,
KEY_Player_1,
KEY_Player_2,
KEY_Player_3,
KEY_Player_4,
KEY_Player_5,
KEY_Player_6,
KEY_Player_7 ,
KEY_Player_8},
column1Name + "=? AND " +
column2Name + "=? AND " +
column3Name + "=? ",
new String[] { value1, value2, value3 }, null, null, null, null);
This will build an expression similar to SELECT Player1, Player2, ... FROM TeamName WHERE FirstName = 'X' AND LastName = 'Y' AND TeamName = 'Z'
You could build this dynamically using variable length args, or passing in string arrays, rather than simply a method defined to take 3 columns & 3 values as parameters, for example:
public BackupDatastore getentry(String[] values, String[] columns) {
if (values.length != columns.length) {
throw new IllegalArgumentException("Number of columns does not match number of values provided.");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < columns.length; i++) {
sb.append(columns[i]);
sb.append("=?");
if (i != columns.length - 1) {
sb.append(" AND ");
}
}
String whereColumns = sb.toString();
Cursor cursor = db.query(TABLE_Name,
new String[] { KEY_ID,
KEY_Team_Name,
KEY_Ref_Name,
KEY_Date,
KEY_Player_1,
KEY_Player_2,
KEY_Player_3,
KEY_Player_4,
KEY_Player_5,
KEY_Player_6,
KEY_Player_7 ,
KEY_Player_8},
whereColumns,
values, null, null, null, null);
...

Categories