First of all, please bear with me, I have minimal experience with SQLite. I am writing an app in Java for the Android platform and I've run into an issue while attempted to query a SQLite database.
I have implemented a database and I am unsure of how to write a method which returns a cursor of only specific rows with a certain value in a certain column. Say there is a column titled "date", I would like to write a method which returns all the columns that do not have the value string "null" in the "date" column.
I know how to write a fetchAll() method and how to write a fetch() for specific rows given an ID, but I not multiple specific rows.
If anyone can help me it would be greatly appreciated.
These will return all the row where Date!=null
public Cursor fetch()
{
return db.query(DATABASE_TABLE,
null,
DATE + "!=''",
null,
null,
null,
null);
}
If you don't need all columns then use
public Cursor fetch()
{
return db.query(DATABASE_TABLE,new String[] {
DATE,
TIME
},
DATE + "!=''",
null,
null,
null,
null);
}
For fetching multiple row using curosor, Have a go with this, You could customize it for your need:
public List<String> getNotNullValues(String value) {
String[] resultCols = new String[] { "Give your result column name here" }; //u could specify multiple column name here
List<String> list = new ArrayList<String>();
int count = 0;
Cursor cr = getWord("DATE", "Your Table Name", "Value of the column",
resultCols,"!="); //Cr is the cursor for resulted query
if (null == cr) {
return null;
}
do {
list.add(cr.getString(0)); //Fill the list or whatever here while traversing with the cursor
} while (cr.moveToNext());
cr.close();
return list;
}
}
public Cursor getWord(String columnName, String tblName, String rowId,
String[] columns, String condition) {
String selection = columnName + condition ; //condtion for selecting a value : "= ?"
String[] selectionArgs = new String[] { rowId };
return query(selection, tblName, selectionArgs, columns);
}
here are the steps:
Form the query with condition, column name and required column name
Get the cursor to the resulting query
Move the cursor to the next record till cr.moveToNext() returns false
For further reference:
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!
Related
I am trying to return the names of distinct values in the 'category' column of an SQLite database. The cursor does not appear to be returning any results.
I'm building an Android app using a pre-existing database of bird species. The aim is to allow the user to explore the database through the app. The problem I'm having is in trying to return the distinct categories of bird species that exist in the database. The database appears to be opening successfully - no SQLite exception is being thrown, - but after using the query, the '.moveToNext' method does not appear to be returning any data.
public ArrayList<String> getCategory(String[] name){
String TABLE_BIRDS = "main";
String[] COLUMN = name;
ArrayList<String>categories = new ArrayList<>();
if (name[0]!=null)
{
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
x = db.query(true, TABLE_BIRDS, new String[] { COLUMN[0] } , null, null, COLUMN[0], null, null, null );
if (x.moveToNext()) {
Log.i(LOG_TAG, x.getString(x.getColumnIndex("category")));
}
else {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
//Simple cursor loop
if (x.moveToNext()){
String category = new String();
category = x.getString(x.getColumnIndex(category));
categories.add(category);
Log.i("cursor loop", category);
}
return categories;
In the above code, the log messages are showing that: getCategory is receiving the expected string "category" before the query, but right after the query, the if/else loop is reporting that "The cursor is not returning any data".
What I expected is that the query would return six Strings, the cursor loop would add them to the ArrayList 'categories', and this ArrayList would be returned.
Please any help would be appreciated.
Here is a simpler version of your method:
public ArrayList<String> getCategory(String[] name) {
String TABLE_BIRDS = "main";
ArrayList<String> categories = new ArrayList<>();
if (name[0] != null) {
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
while (x.moveToNext()) {
String category = x.getString(0);
categories.add(category);
Log.i("cursor loop", category);
}
if (x.getCount() == 0) {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
x.close();
return categories;
}
I guess name[0] contains the string 'category' which is the column that you want to query.
Since you pass true as the 1st argument in the method query() this means that you will get distinct values, so no need for the group by argument.
You don't need the variable COLUMN since you have what you need in the variable name.Also you don't need getColumnIndex() since the cursor returns only 1 column.
Edit
Instead of:
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
try rawQuery():
Cursor x = db.rawQuery("SELECT DISTINCT " + name[0] + " FROM " + TABLE_BIRDS, null);
Assuming the cursor is not null, you should
iterate over the results with a while/for loop.
e.g :while(x.moveToNext()) {
//your logic
}
It is always useful when debugging this kind of issues to install an SQLite DB browser then check the cursor's query against your DB to see if you have any data.
I am creating an application. I need the email of the existing user, which is already saved in the first table, and save it into the second table. Which queries or functions do I need to achieve this? Any suggestions?
First, you need to fetch the user's email by passing on the valid row id:
public Cursor getRecord(long id) throws SQLException {
Cursor cursor = this.database.query(true, databaseTable, new String[] {columnId, columnName, columnEmail}, columnId + "=" + id, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Please note, you may have different columns so change the String[] array with your designated columns. Now, we can create another function to save that email in another table like so:
public long insertExistingUser(String name, String email) {
ContentValues contentValues = new ContentValues();
contentValues.put(columnName, name);
contentValues.put(columnEmail, email);
return this.database.insert(otherDatabaseTable, null, contentValues);
}
This will insert the other user's information into the other table. In order for this to work in your application:
DatabaseAdapter db = new DatabaseAdapter(this);
db.open();
Cursor cursor = db.getRecord(current_user_id);
if (db.insertExistingUser(cursor.getString(1), cursor.getString(2)) > 0)
Toast.makeText(this, "Old user's info was inserted!", Toast.LENGTH_SHORT).show();
db.close();
The cursor.getString(1) requires a number that indicates what column it is. Usually, 0 is the id column which you use to get the user's email.
I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:
METHODS FOR ANDROID SQLITE DATABASE QUERY:
public void updateUser(String newProfession, String newCountry, String sx, String ag) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
Cursor cursor = db.rawQuery(query, null);
cursor.close();
db.close();
}
public int countAll() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
db.close();
return cnt;
}
CALLING THE METHODS
public void updateUsersClicked(View view) {
int allData = db.countAll();
for (int i = 0; i < allData; i++) {
db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
System.out.println("T H I S I S T H E R E S U L T: " + i);
}
}
Use execSQL() and not rawQuery() for updates.
rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.
Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.
You don't need to do the for loop
a single QSL "Update" query is enough if you want to update All the female with age 30.
If you are new to SQL you can view a simple example here:
Simple SQL Update example
If you want to do something else - please edit your question
I'm, trying to add a credit score from multiple records of an SQLite table.
Each record has a column called credit score, I want to add them all together but I'm having trouble.
Here is the code:
String[] projection2 = { BorrowMeTable.COLUMN_CREDIT_SCORE };
Cursor databaseCursor2 = getContentResolver().query(uri, projection2,
null, null, null);
int number = 0;
if (databaseCursor2 != null) {
databaseCursor2.moveToFirst();
while (databaseCursor2.moveToNext()) {
number = number + databaseCursor2.getInt(
databaseCursor2.getColumnIndexOrThrow(
BorrowMeTable.COLUMN_CREDIT_SCORE));
}
}
Log.d("SCORE", Integer.toString(number));
The problem is the while statement, when it is in place it doesn't pull any data. When I remove it, it pulls the correct data but only from one record.
Use the sum funstion in SQLite
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(COLUMN_CREDIT_SCORE) FROM BorrowMeTable", null);
You can URI match this in your ContentProvider as a different URI
Then simply get the scalar value:
if(cursor.moveToFirst()) {
return cursor.getInt(0);
Use do->while to start from first record
do{
number = number + databaseCursor2.getInt(
databaseCursor2.getColumnIndexOrThrow(
BorrowMeTable.COLUMN_CREDIT_SCORE));
}while (databaseCursor2.moveToNext());
I have a database table with multiple columns
I use custom List<> and populate it from database
What i want to do is filter what will go into the list from database depending on user input
for example if i had a table like this:
name|phone|date|address
User can specify any filter(by name, by phone, by date... or all of it) and only items that matches all criteria will go into the list
Is there a way to do this?
Method that returns all items from database
public List<MoviesDatabaseEntry> getAllMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
MoviesDatabaseEntry list = new MoviesDatabaseEntry();
list.set_id(Integer.parseInt(cursor.getString(0)));
list.set_title(cursor.getString(1));
list.set_runtime(cursor.getString(2));
list.set_rating(cursor.getDouble(3));
list.set_genres(cursor.getString(4));
list.set_type(cursor.getString(5));
list.set_lang(cursor.getString(6));
list.set_poster(cursor.getString(7));
list.set_url(cursor.getString(8));
list.set_director(cursor.getString(9));
list.set_actors(cursor.getString(10));
list.set_plot(cursor.getString(11));
list.set_year(cursor.getInt(12));
list.set_country(cursor.getString(13));
list.set_date(cursor.getInt(14));
// Adding to list
lists.add(list);
} while (cursor.moveToNext());
}
// return list
db.close();
cursor.close();
return lists;
}
You can filter the entries you get in the SQL query you are building in this line:
String selectQuery = "SELECT * FROM " + table;
To filter the dataset your retrieve, you would add a WHERE clause to it. When you would, for example, only want those entries where the rating is over 3, you would change this to:
String selectQuery = "SELECT * FROM " + table + " WHERE rating > 3";
SQL is a very powerful language which offers a lot of possibilities. It's an essential skill when you work with relational databases. When you want to learn it, I can recommend you the interactive tutorial website http://sqlzoo.net/
You have to change your database query for getting specific data from the query.
You have one function that returns all rows from database like so: getAllMovies(String table)
Here you are using:
String selectQuery = "SELECT * FROM " + table;
Make a new function like this:
public List<MoviesDatabaseEntry> getSelectedMovies(String table)
{
List<MoviesDatabaseEntry> lists = new ArrayList<MoviesDatabaseEntry>();
Cursor cursor = db.query(true, TABLE_NAME, new String[] { <your row names> },
**check condition(as string)**, null,
null, null, null, null);
...
}
Now just call this function when required with your specific query string
Make as many functions as you want!