no such column: ٤۹۸ (code 1): - java

I translated my app using android studio translation editor, i get this error when running my application on android phone using Arabic as its language:
android.database.sqlite.SQLiteException: no such column: ٤۹۸ (code 1): , while compiling: SELECT * FROM photos WHERE store_id = ٤۹۸ ORDER BY photo_id ASC
The method in app_id > java > com > db > Queries is:
public ArrayList<Photo> getPhotosByStoreId(int storeId) {
ArrayList<Photo> list = new ArrayList<Photo>();
db = dbHelper.getReadableDatabase();
String sql = String.format("SELECT * FROM photos WHERE store_id = %d", storeId);
Cursor mCursor = db.rawQuery(sql, null);
mCursor.moveToFirst();
if (!mCursor.isAfterLast()) {
do {
Photo entry = formatPhoto(mCursor);
list.add(entry);
} while (mCursor.moveToNext());
}
mCursor.close();
dbHelper.close();
return list;
}

use the full set of method arguments for rawQuery to properly escape your values for use in a sql statement.
...
ArrayList<Photo> list = new ArrayList<Photo>();
db = dbHelper.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM photos WHERE store_id = ?",
new String[] { storeId });
mCursor.moveToFirst();
...

The problem is that you are using String.format(String, Object ...), which uses the default locale for formatting. Arabic uses different digits, causing your query to include characters that does not match what is found in your SQLite database.
To solve this, you could either avoid using String.format() and just do:
String sql = "SELECT * FROM photos WHERE store_id = " + storeId;
Or, if you for some reason still want string.format(), you could do:
Locale locale = Locale.Builder().setLanguage("en").setRegion("US").build();
String sql = String.format(locale, "SELECT * FROM photos WHERE store_id = %d", storeId);

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);

Cursor is empty but query is (supposedly) right

I've got very strange problem.
My snippet is looking like that
public Wynik getData(int pomiar, int godzina) {
Wynik wynik = null;
String query = "SELECT * FROM " + "insulina" + " WHERE godzina = " + godzina +
" AND cukier = " + pomiar;
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, null)) {
Log.i("tag", "cursor length:" + cursor.getCount());
if (cursor.getCount() > 0) {
String s = DatabaseUtils.dumpCursorToString(cursor);
Log.d("s", s);
cursor.moveToFirst();
wynik = new Wynik
(cursor.getInt(cursor.getColumnIndexOrThrow("godzina")),
cursor.getString(cursor.getColumnIndexOrThrow("insulina")),
cursor.getInt(cursor.getColumnIndexOrThrow("dawka")),
cursor.getString(cursor.getColumnIndexOrThrow("cialo")));
}
cursor.close();
return wynik;
(sorry for not English convention, but it was meant to be quick, routinely project)
Whole app idea is to help my friend with his grandmother's diabetes. He would insert an result of blood sugar level test (cukier) and time of test is checked automatically (godzina).
Based on those, app should return a whole result (wynik), with required dose of insulin (dawka), type of it (insulina) and part of body from which the blood should be taken (cialo).
Database looks like this:
So for example. The blood result is 10 (it's only thing which user is inserting) and it's 7 P.M (19, by 24-hours convention - the program is giving the closest hour of test, so it's 18). So, the query looks like
SELECT * FROM insulina WHERE godzina = 18 AND cukier = 10
And here's my problem. The app is recognizing cursor length as 0 (it should be 1) even if my other app related to database creation (DB Browser for SQLite) is giving out my result properly with the same query
Also Android Studio says that database is sucessfully opened.
I cannot find a fault here. And I'm really confused with this problem.
I think the query should be :
String query = "SELECT * FROM insulina WHERE godzina = ? AND cukier = ?";
SQLiteDatabase db = this.getReadableDatabase();
try (Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(godzina), String.valueOf(pomiar)})) {
//... rest of code
Also looks like you're using "try with resources" so the close isn't explicitly necessary.

search in SQLite android java not work

I am trying to fetch data from sqlite data base .I already have a table for employees and I want to fetch employee info by employee name.I already created a function in the database helper like this:
public List getEmpdat(String empname) {
final String TABLE_NAME = "Employee";
String selectQuery = "SELECT * FROM Employee where EmployeeName="+empname;
SQLiteDatabase db = this.getReadableDatabase();
List<String> li = new ArrayList<String>();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
// String name =null;
if (cursor.moveToFirst()) {
do {
String name=cursor.getString(2);
String notes=cursor.getString(3);
String strdate=cursor.getString(4);
if(strdate==null)
strdate = "0";
String gate=cursor.getString(6);
if(gate==null)
gate = "0";
String enddate=cursor.getString(5);
if(enddate==null)
enddate = "0";
li.add(name);
li.add(notes);
li.add(strdate);
li.add(enddate);
li.add(gate);
// get the data into array, or class variable
} while (cursor.moveToNext());
}
cursor.close();
return li;
}
and then call it in the search activity like this :
db=new DataBaseHelper(this);
data = (GridView) findViewById(R.id.gridView);
List<String> li = new ArrayList<String>();
li = db.getEmpdat(editName.getText().toString());
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, li);
dataAdapter.setDropDownViewResource(R.layout.activity_search);
dataAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, li);
data.setAdapter(dataAdapter);
but there is a problem taking place from the logcat the problem is
" java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.university.newapp/com.example.university.newapp.SearchActivity}: android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: SELECT * FROM Employee where EmployeeName=
"
can any one provide help with this issue please
Try to change the line where exception occurred and check if it works.
String selectQuery = "SELECT * FROM Employee where EmployeeName='"+empname+"'";
You can use placeholder in querying, like that,
String query = String.format("SELECT * FROM Employee WHERE EmployeeName='%s'",empname);
You will see '%s',it serve as placeholder and your variable value will be insert to placeholder when querying.
So, '%s' can be use for String placeholder and if you want for Digit , you can use '%d'.I hope this will help for you.

How to get all table names in android sqlite database?

I have tried this code
Cursor c=db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'",null);
c.moveToFirst();
while(!c.isAfterLast()){
Toast.makeText(activityName.this, "Table Name=> "+c.getString(0),
Toast.LENGTH_LONG).show();
}
But it throws the error:
"android.database.sqlite.SQLiteException: no such table: sqlite_master(code 1):, while
compiling: SELECT name FROM sqlite_master WHERE type='table'"
How to fetch all the table names?
Checked, tested and functioning. Try this code:
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
Toast.makeText(activityName.this, "Table Name=> "+c.getString(0), Toast.LENGTH_LONG).show();
c.moveToNext();
}
}
I am assuming, at some point down the line, you will to grab a list of the table names to display in perhaps a ListView or something. Not just show a Toast.
Untested code. Just what came at the top of my mind. Do test before using it in a production app. ;-)
In that event, consider the following changes to the code posted above:
ArrayList<String> arrTblNames = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
arrTblNames.add( c.getString( c.getColumnIndex("name")) );
c.moveToNext();
}
}
Change your sql string to this one:
"SELECT name FROM sqlite_master WHERE type='table' AND name!='android_metadata' order by name"
To get table name with list of all column of that table
public void getDatabaseStructure(SQLiteDatabase db) {
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table'", null);
ArrayList<String[]> result = new ArrayList<String[]>();
int i = 0;
result.add(c.getColumnNames());
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
String[] temp = new String[c.getColumnCount()];
for (i = 0; i < temp.length; i++) {
temp[i] = c.getString(i);
System.out.println("TABLE - "+temp[i]);
Cursor c1 = db.rawQuery(
"SELECT * FROM "+temp[i], null);
c1.moveToFirst();
String[] COLUMNS = c1.getColumnNames();
for(int j=0;j<COLUMNS.length;j++){
c1.move(j);
System.out.println(" COLUMN - "+COLUMNS[j]);
}
}
result.add(temp);
}
}
Try adding the schema before the table
schema.sqlite_master
From SQL FAQ
If you are running the sqlite3 command-line access program you can type ".tables" to get a list of all tables. Or you can type ".schema" to see the complete database schema including all tables and indices. Either of these commands can be followed by a LIKE pattern that will restrict the tables that are displayed.
From within a C/C++ program (or a script using Tcl/Ruby/Perl/Python bindings) you can get access to table and index names by doing a SELECT on a special table named "SQLITE_MASTER". Every SQLite database has an SQLITE_MASTER table that defines the schema for the database. The SQLITE_MASTER table looks like this:
CREATE TABLE sqlite_master (
type TEXT,
name TEXT,
tbl_name TEXT,
rootpage INTEGER,
sql TEXT
);
Try this:
SELECT name FROM sqlite_master WHERE type = "table";
I tested Siddharth Lele answer with Kotlin and Room, and it works as well.
The same code but using Kotlin and Room is something like that:
val cursor = roomDatabaseInstance.query(SimpleSQLiteQuery("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('android_metadata', 'sqlite_sequence', 'room_master_table')"))
val tableNames = arrayListOf<String>()
if(cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
tableNames.add(cursor.getString(0))
cursor.moveToNext()
}
}

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!

Categories