Querying a specific column in an Android Database - android

I have an Android app that has a database. My database has a table say Person Table, which has 4 columns , Firstname, lastname, DOB and Age. How do I go about retrieving just the DOB information for all the rows in the table.
Your help would be most appreciated.

When querying, just specify the columns that you're after:
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] cols = {"dob"};
Cursor result = db.query("person", cols, null, null, null, null, null);

List<String> DobList = new ArrayList<String>();
Cursor cursor = db.rawQuery(String.format("select DOB from %s", TABLE_NAME);
if (cursor.movetoFirst) {
do {
DobList.add(cursor.getString(cursor.getColumnIndex("DOB")));
} while (cursor.moveToNext());
}
cursor.close();

Related

How to write a sqlite query to get specific data?

I want to get the first name, middle name and last name of a student whose userid is used for login. I have written this particular piece of code but it stops my application.
I have used both the ways like database.query() and .rawquery() also.
Cursor studentData(String userId) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
// Cursor cursor = db.rawQuery("select First_Name, Middle_Name, Last_Name from Student_Table where User_ID =?", new String[]{userId});
String data = cursor.getString(cursor.getColumnIndex("First_Name"));
db.close();
return cursor;
}
I should get whole name in the string.
You have a number of issues.
Attempting to use String data = cursor.getString(cursor.getColumnIndex("First_Name"));,
will result in an error because you have not moved the cursor beyond BEFORE THE FIRST ROW and the attempt to access the row -1 will result in an exception (the likely issue you have encountered).
you can use various move??? methods e.g. moveToFirst, moveToNext (the 2 most common), moveToLast, moveToPosition.
Most of the Cursor move??? methods return true if the move could be made, else false.
You CANNOT close the database and then access the Cursor (this would happen if the issue above was resolved)
The Cursor buffers rows and then ONLY when required.
That is The Cursor is when returned from the query method (or rawQuery) at a position of BEFORE THE FIRST ROW (-1), it's only when an attempt is made to move through the Cursor that the CursorWindow (the buffer) is filled (getCount() included) and the actual data obtained. So the database MUST be open.
If you want a single String, the full name, then you could use :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("First_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Middle_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Last_Name"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
Or alternately :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name"||" "||"Middle_Name"||" "||"Last_Name" AS fullname}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("fullname"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
the underlying query being SELECT First_Name||" "||Middle_Name||" "||LastName AS fullname FROM student_table; so you concatenate the names as part of the query which returns just one dynamically created column named fullname.

Android : cursor is empty even return one value

I want to check the records are available or not in my Sqlite table. I tried but the cursor is always return 1 value even if the SQlite databse table is empty, no any record in table. Why return one? How to solve this issue?
dbhelper = new MyDbHelper(this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
String count = "select count(*) from ActivityObjectList";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
{
Log.e("Record does not found","");
//leav
}
else
{
Log.e("Record is exists !!","");
//populate table
}
Use mcursor.getCount() to check number of rows.

Android delete Record SQLite

In my activity I have a spinner with data taken from SQLite db by this query:
private List<String> ottieniAnni(){
List<String> result = new LinkedList<String>();
SQLiteDatabase db = new BHelper(this).getReadableDatabase();
String sql = "SELECT DISTINCT strftime('%Y',"+GTable.DATE+") FROM "+GTable.TABLE_NAME;
Cursor c = db.rawQuery(sql, null);
while (c.moveToNext()){
result.add(c.getString(0));
}
db.close();
return result;
}
Now through button, I want to delete all records in the year chosen by the user. I used the method db.delete (), but so will delete all the records.
Should I set a parameter but do not know how to do it:
SQLiteDatabase db= mHelper.getWritableDatabase();
db.delete(GiornateTable.TABLE_NAME, null, null );
db.close();
Try like
SQLiteDatabase db= mHelper.getWritableDatabase();
int rowcount = db.delete(GiornateTable.TABLE_NAME,
"GIVE YOUR COLUMN NAME" + "=?",
new String[] { "GIVE YOUR VALUE" });
Log.d("No of record deleted",String.valueOf(rowcount));
you can use the same syntax as you do with the select, only for deleting

Android: SQLite database query not returning any records

I created and populated a SQLite database with the Firefox SQLite Manager. I copied the .sqlite file into the assets folder of my Android project.
My aim is to use this records to populate a spinner. When I query the database, the cursor displays the columns but no records.
My DatabaseHandler class extends SQLiteOpenHelper and contains methods for onCreate, onUpgrade and getAllOffices.
public List<String> getAllOffices(){
List<String> offices = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT OfficeId as _id, OfficeName FROM " + TABLE_OFFICE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
offices.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning offices
return offices;
}
Any ideas on why the records are not returned would be appreciated.
Try this:
public List<String> getAllOffices(){
List<String> offices = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT OfficeId as _id, OfficeName FROM " + TABLE_OFFICE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
offices.add(cursor.getString(cursor.getColumnIndex("_id")));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning offices
return offices;
}
Basically it will just ensure that you are using the correct column index. Otherwise if you are using eclipse then try the cellobject plugin to browse the database and make sure your table is populated as expected:
http://marketplace.eclipse.org/content/cellobject-sqlite-xml-browser#.UWOU5RaBD3g
Please try this and may be useful for you.
public List<String> getAllOffices(){
List<String> offices = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_OFFICE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.println("CURSOR SIZE:"+cursor.getCount())
// looping through all rows and adding to list
if(cursor.getCount()!=0){
if (cursor.moveToFirst()) {
do {
System.out.println(cursor.getString(c.getColumnIndex("as per your db column name"));
} while (cursor.moveToNext());
}
}
// closing connection
cursor.close();
db.close();
// returning offices
return offices;
}
First of all you have to just see console output if you are getting right then add into your office bean

select one cell from sql database

I'm trying a simple SQL Command wihtin my Android-App, to get the age of a selected Person:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name =? " + MainActivity.selectedPerson.getText().toString(), null);
int age = cursor.getInt(3); // column with ages
cursor.close();
db.close();
return age;
}
But when I run my app, it crashes when I call the function getAge(). I get the following Error:
SQLiteException: no such column: Max: , while compiling: SELECT * FROM persons WHERE name = Max
I don't get it. There is the name "Max" in the table. What am I doing wrong? Thanks in advance.
Edit 2:
With this one:
Cursor cursor = db.rawQuery("SELECT name FROM persons WHERE name = '" + MainActivity.selectedPerson.getText().toString() + "'", null);
I get a different error:
08-27 19:43:47.573: E/AndroidRuntime(6161): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
what does this mean?
You should consider using the selectionArgs parameter of rawQuery() to prevent SQL Injection Attacks:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
Also you only need one column so rather than wasting resources by selecting them all with *, you should just select the one column:
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
Hope that helps!
All together it should look like:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
int age;
// Check if you have a valid result and move to the first row to read it
if(cursor.moveToFirst())
age = cursor.getInt(0);
// Prevent a crash if there is no data for this name
else
age = 0;
cursor.close();
db.close();
return age;
}
Chan ge the 3rd line of your program:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name =? " + MainActivity.selectedPerson.getText().toString(), null);
to this:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString()} );
Try this:
public int getAge(){
int age;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = '" + MainActivity.selectedPerson.getText().toString()+"'",null);
if(cursor.moveToFirst())
{
age = cursor.getInt(3); // column with ages
}
cursor.close();
db.close();
return age;
}
You missed the single quotes (' ') in your sql command. That's why MAX was taken as a column and not as a value.

Categories

Resources