Android Sqlite select Query if value is zero or 0 - java

I am trying to program a get a query that will show data from COURSE table if the values are :
course_id=0
or
semester_id=0
or
level_id=0
or
level_code=Select level
or
grade=Grade
So any rows that have any of the values above should be showed :
public List<Courses> getListCourseError() {
Courses courses = null;
List<Courses> coursesList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
courses = new Courses(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3), cursor.getInt(4), cursor.getString(5), cursor.getInt(6), cursor.getString(7), cursor.getInt(8), cursor.getInt(9));
coursesList.add(courses);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return coursesList;
}
Thanks

I believe that you issue is that string values have to be enclosed in quotes. You are also not including course_id is 0.
So instead of "SELECT * FROM COURSES WHERE semester_id=0 OR level_id=0 OR level_code=Select level OR grade=Grade"
use :-
"SELECT * FROM COURSES WHERE course_id=0 OR semester_id=0 OR level_id=0 OR level_code='Select level' OR grade='Grade'"
However the above is a candidate for SQL injection so really you should be utilising the selection args (2nd parameter), which will properly enclose strings on your behalf. So the more correct solution would be to utilise :-
String[] selectionargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.rawQuery("SELECT * FROM COURSES WHERE course_id=? semester_id=? OR level_id=? OR level_code=? OR grade=?", selectionargs);
However, it is recommended to only use the rawQuery method when need and that the conveniece query method be used. This would be :-
String whereclause = "course_id=? OR semester_id=? OR level_id=? OR level_code=? or grade=?";
String[] whereargs = new String[]{"0","0","0","Select level", "Grade"};
Cursor cursor = mDatabase.query(
"COURSES",
null, //<<<< all columns (else String[] of columns)
whereclause, //<<<< WHERE clause without the WHERE keyword
whereargs, //<<<< arguments to replace ?'s
null, //<<<< GROUP BY clause
null, //<<<< HAVING clause
null //<<<< ORDER BY clause
);
Notes
- null results in the respective parameter to be ignored/defaulted (table name cannot be null). e.g. columns (2nd parameter) as null defaults to ALL columns i.e. *.
there are a number of different query method signatures. See SQLiteDatabase
The code above is in-principle code and has not been tested so there may be some errors.

Related

How can I search all columns of a table in Android Studio using SQL database

I have an Android app with a SQL database that has 4 columns. I would like to search all 4 columns in the database however I can only get 1 to be searched.
I'm not quite sure on how to get it to search all 4 columns.
All 4 Columns are displayed but I can only search one. I can not seem to get it to search all 4 columns.
the code I'm using to get it to search one column is
#SuppressLint("Range")
public List<Data> getDataByVARIETY (String VARIETY) {
variety = VARIETY;
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"VARIETY", "COMMODITY", "PLU", "BOTANICAL"};
String tableName = "data";
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
List<Data> result = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Data data = new Data();
data.setCOMMODITY(cursor.getString(cursor.getColumnIndex("COMMODITY")));
data.setVARIETY(cursor.getString(cursor.getColumnIndex("VARIETY")));
data.setPLU(cursor.getString(cursor.getColumnIndex("PLU")));
data.setBOTANICAL(cursor.getString(cursor.getColumnIndex("BOTANICAL")));
result.add(data);
} while (cursor.moveToNext());
}
return result;
}
so all i had to do was
change this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
to this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
String conditions = "COMMODITY LIKE ? OR PLU LIKE ? OR VARIETY LIKE ?";
String par;
par = "%"+COMMODITY+"%";
Cursor cursor = db.query(tableName, sqlSelect, conditions, new String[]{par, par, par}, null, null, null);

Android SQLite take the first element from database column

I am working on a project and created a database with SQLite. In my database I have just two columns, column names are r_id and m_id. I want to take the first element of the r_id and assign it in to a string. The elements of the r_id column is like 1, 2, 3.. in this situation my String has to be 1.
My code; creating a db query:
There is no problem I can add data correcly.
my_table = "CREATE TABLE "my_table"("r_id" Text, "m_id" Text);";
db.execSQL(my_table );
Code to take the first element of the column;
public String getSetting() {
String result = "";
String[] columns = {"r_id"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(true, "r_id", columns, "row", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
databaseHelper.close();
return result;
}
The error I am getting:
android.database.sqlite.SQLiteException: no such column: row (code 1 SQLITE_ERROR): , while compiling: SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
The 4th argument of query() is the WHERE clause of the query (without the keyword WHERE) and for it you pass "row".
Also, the 2nd argument is the table's name for which you pass "r_id", but the error message does not contain ...FROM r_id... (although it should), so I guess that the code you posted is not your actual code.
So your query (translated in SQL) is:
SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
which is invalid.
But you don't need a WHERE clause if you want just the min value of the column r_id.
You can do it with a query like:
SELECT MIN(r_id) AS r_id FROM my_table
without DISTINCT and a WHERE clause.
Or:
SELECT r_id FROM my_table ORDER BY r_id LIMIT 1;
So your java code should be:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT MIN(r_id) AS r_id FROM my_table", null);
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
I used rawQuery() here instead of query().
Or:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(false, "my_table", new String[] {"r_id"}, null, null, null, null, "r_id", "1");
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}

Update integer values in SQLite database (java)

I am pretty new to SQLite databases, so please forgive me...
I have a database with integer values. When updating a row in the database using the code below, there is somehting I don't understand. whereArgs is of type String[], though the values you are looking for are integers, so I would expect that one should pass in a int[].
SQ.update(table, values, whereClause, whereArgs)
Where do I go wrong?
Example code (hypothetical):
public void changeOneIntoTwo(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getWritableDatabase();
String selection = "ValuesColumn = ?";
String[] args = {"1"};
ContentValues cv = new ContentValues();
cv.put("ValuesColumn", 2);
SQ.update("MyTable", cv, selection, args);
}
selection is the condition that you put in where clause of Sql query and args is what replaced by "?" of selection .
for example : lets assume you need your sql query select * from Mytable where ValuesColumn ='1' and Name = 'MVB'. so in this case
String selection = "ValuesColumn = ? AND Name = ?";
String[] args = {"1","MVB"};

How to create filter

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!

Android - Fetching only rows with a value in a column in java

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!!

Categories