I wrote this function which takes in a post id and finds the last name for that post id.When I run this I get error :
database.cursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
What is wrong?
public Person_Obj GetPerson_Obj(int post_id)
{
Person_Obj obj = new Person_Obj();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_Persons + " WHERE "
+ Post_Id + " = " + post_id;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
obj.set_last_name(cursor.getString(cursor.getColumnIndex("LastName")));
return obj;
}
Try this,
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.rawQuery("query", null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
// write your code
} while (cursor.moveToNext());
}
database.close();
Related
I'm getting a null pointer exception on the following line of code
attendanceList = dbHelper.getAttendance(surName, name);
both surName and name are not null, have size() > 0 and attendanceList is of type ArrayList and here is the getAttendance function:
public ArrayList<Attendance> getAttendance(String surName, String name)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Attendance> attendanceList = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + ATTENDANCE_TABLE + " WHERE " + COLUMN_SURNAME + " =? AND "
+ COLUMN_NAME + " =?", new String[] {surName, name});
if(cursor .moveToFirst())
{
while(!cursor.isAfterLast())
{
Attendance attendance = new Attendance();
attendance.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE)));
attendance.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
attendance.setSurName(cursor.getString(cursor.getColumnIndex(COLUMN_SURNAME)));
attendance.setState(cursor.getString(cursor.getColumnIndex(COLUMN_STATE)));
attendance.setTerm(cursor.getInt(cursor.getColumnIndex(COLUMN_TERM)));
attendance.setSubject(cursor.getString(cursor.getColumnIndex(COLUMN_SUBJECT_NAME)));
attendanceList.add(attendance);
cursor.moveToNext();
}
cursor.close();
db.close();
return attendanceList;
}
else
{
cursor.close();
db.close();
return null;
}
}
There is no syntax error in the above function, and I know it shouldn't return null because I see the content of the ATTENDANCE_TABLE using DB Browser for SQLite. Can someone point what is wrong with my code? I feel like I wrote 1 + 1 = 2 and getting an error..
Try this... SQLiteDbHelper is my DataBase Class where my table is defined. Table_Name is string in which my table name is stored
cursor = db.rawQuery("SELECT * FROM "+SQLiteDBHelper.TABLE_NAME+" WHERE "+SQLiteDBHelper.COLUMN_SURNAME+"=? AND "+SQLiteDBHelper.COLUMN_NAME+"=?",new String[] {surName,name});
if (cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
//Retrieving User SurName and Name
String s_name = cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_SURNAME));
String _name= cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_NAME));
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
I am pretty sure that it not surName or name that causes NullpointerException, but dbHelper is.
So please check if you are initialising your dbHelper after this line
attendanceList = dbHelper.getAttendance(surName, name);
If so, then move it above and your crash will be fixed.
Hope it helps.
I'm attempting to query my SQLite database but I'm getting the error "Cursor Index Out Of Bounds Exception: Index 0 requested, with a size of 0". When I run the same query in SQLite Man, I get the result I'm looking for.
public int getHighScore () {
String query = "SELECT score FROM " + SCORE_TABLE + ";";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
int score = cursor.getInt(0);
cursor.close();
return score;
}
Please check if cursor is not null then you want to fetch record from cursor.Use this line to fetch record:
cursor.getInt(cursor.getColumnIndex("score")))
use this code :
public int getHighScore () {
int score=0;
String query = "SELECT score FROM " + SCORE_TABLE + ";";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
score = cursor.getInt(cursor.getColumnIndex("score")));
}
cursor.close();
return score;
}
Im trying to get the data of an entire column into a string array. My database contains two columns Id and Names. I want to read all the entries of the names column and put it into a array. Please help.
EDIT #1:
Im using the following code but i can get only one name with this code.
String query = "Select * FROM " + TABLE_APPS + " WHERE " + COLUMN_NAME + " = \"" + productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
cursor.moveToFirst();
name = cursor.getString(1);
cursor.close();
} else {
name = null;
}
db.close();
int total=0;
Cursor csr=sdb.query("tablename", null, null,null,null,null,null);
csr.moveToFirst();
while(!csr.isAfterLast())
{
total++;
csr.moveToNext();
}
String strarray[] = new String[total];
Cursor csrs=sdb.query("tablename", null, null,null,null,null,null);
csrs.moveToFirst();
int aray=0;
while(!csrs.isAfterLast())
{
strarray[aray]=csrs.getString(1);
aray++;
csrs.moveToNext();
}
I created a table with three columns id, name and discipline.
I want to find the student name given the discipline.
Following is my method:
String findstudent(String disc){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String find = "SELECT * FROM "+ TABLE_STUDENTS + " WHERE "+KEY_DISCIPLINE +" = " +disc ;
Cursor cursor = sqLiteDatabase.rawQuery(find,null);
cursor.moveToFirst();
String found =cursor.getString(1);
return found;
}
When I use it, the application stops working.
I am not sure. But, you can try this way
Cursor.moveToFirst();
do{
//get the data
String found =cursor.getString(cursor.getColumnIndexOrThrow("COLUMN NAME"));
}while(Cursor.moveNext);
Try the following code:
String find = "SELECT *<enter code here>
FROM "+ TABLE_STUDENTS + "
WHERE "+KEY_DISCIPLINE +" = '" + disc + "'" ;
Try this:
String findstudent(String disc){
Cursor cursor;
cursor = this.db.query(TABLE_STUDENTS,null, KEY_DISCIPLINE +" = "+ disc, null, null, null, null,null );
cursor.moveToFirst();
String found =cursor.getString(0);
return found;
}
Hope it Helps!!
public Cursor findstudent(String disc){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String[] find = new String[]{ col1,col2,col3};//all fields in db in need
String order=col1;
Cursor c=db.query(TABLE_STUDENTS, find, KEY_DISCIPLINE +" = " +disc, null, null, null, order);
c.moveToFirst();
db.close();
return c;
}
In the activity include this:
DataBaseHandler db = new DataBaseHandler(this);
try {
Cursor c = db.displayName(your_disc);
startManagingCursor(c);
if (!c.moveToFirst()) {
System.out.println("!Move " + posnumber);
} else {
String idname = c.getString(c
.getColumnIndex(DataBaseHandler.KEY_NAME));
System.out.println("null:");
System.out.println("Move " + idname);
return true;
}
c.close();
stopManagingCursor(c);
} catch (Exception ex) {
}
Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.
try {
String categoryex = "NAME";
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
MyData = dbHelper.getWritableDatabase();
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("Category"));
String age = c.getString(c.getColumnIndex("Text_Data"));
results.add( firstName + " Directions: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (MyData != null)
MyData.execSQL("DELETE FROM " + tableName);
MyData.close();
}
try... (you left out a double-quote before where.
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
I think you should use rawQuery in this form:
rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});
I think it's more secure this way.
Your quotes are buggered:
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);
You also should read up on SQL injection attacks.
it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.
public ArrayList<Invitees> getGroupMembers(String group_name) {
ArrayList<Invitees> contacts = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};
String selection = COLUMN_GROUP_NAME + "=?";
String[] selectionArgs = {group_name};
Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
Invitees invitees = new Invitees();
invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));
invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));
contacts.add(invitees);
} while (cursor.moveToNext());
}
return contacts;
}