Use a parameter to select data from SQlite database - java

I wanna use a String d as a parameter to select data from a sqlite database ..
- ID ------ DATE --------- VALUE
- 1 --------11/04/2020 ----2000
- 2 --------11/04/2020 ----4000
- 3 --------11/04/2020 ----1000
- 4 --------12/04/2020 ----700
- 5 --------13/04/2020 ----300
My getEntry() method looks like this :
public String getEntry(String d) {
// This value of storedEntry is returned if there is no data
String storedEntry = "Nothing!";
//here we use d to fetch data from table
String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+DATE+"="+ d;
SQLiteDatabase db = this.getReadableDatabase();
String table;
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()) {
do {
storedEntry = cursor.getString(2);
} while (cursor.moveToNext());
} else {
//Do nothing!
}
return storedEntry;
}
My onClick method looks like this :
showDataBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DataBaseHelper helper = new DataBaseHelper(HistoryActivity.this);
String v = helper.getEntry(dateEditText.getText().toString());
valueTextView.setText(v);
}
});
But, it returns an error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.darq2.myapplication, PID: 25073
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.darq2.myapplication.DataBaseHelper.getEntry(DataBaseHelper.java:61)
WHY ??

The easy but not safe way to do this is by enclosing the parameter d inside single quotes and then concatenate:
String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+DATE+"='"+ d + "'";
but as I said this is not safe.
Use ? placeholders for parameters:
String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+DATE+"=?";
and also change:
Cursor cursor = db.rawQuery(queryString, null);
to:
Cursor cursor = db.rawQuery(queryString, new String[] {d});
Also, you should change the format of your dates.
SQlite recognizes only the format YYYY-MM-DD as a valid date.

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
You are getting CursorIndexOutOfBoundsException.
An exception indicating that a cursor is out of bounds.
You should rectify your SELECT statement.
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE DATE =?", new String[]{d});
if (c.moveToFirst()){
do {
// Your work
}
while(c.moveToNext());
}
c.close();
db.close();

Related

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

error occur when try to SELECT in sqlite android

so i recently learn to write a code in android using sqlite and i try to select data from sqlite but this error occur
ive tried some suggestion from the internet and read my book but i didnt solve my problem
public Penyakit getPenyakit1(String namaGejal){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\"" + namaGejal + "\"";
Cursor cursor = db.rawQuery(query,null);
Penyakit penyakit = new Penyakit();
if(cursor.moveToFirst()){
cursor.moveToFirst();
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
penyakit.set_namaPen(cursor.getColumnName(1));
penyakit.set_idPenyakit(Integer.parseInt(cursor.getColumnName(2)));
penyakit.set_namGej(cursor.getColumnName(3));
penyakit.set_idGejala(Integer.parseInt(cursor.getColumnName(4)));
cursor.close();
} else {
penyakit=null;
}
return penyakit;
}
this is logcat
Process: com.example.lordbramasta.pakar, PID: 18914
java.lang.NumberFormatException: For input string: "idPen"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.lordbramasta.pakar.DBAdapter.getPenyakit1(DBAdapter.java:79)
i expected the value of idPen get selected , thank you
Your problem is this line:
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
cursor.getColumnName(0) returns idPen as this is the name of the only column returned by your query:
SELECT idPen FROM ....
and your code is trying to cast the string "idPen" to an integer.
So getColumnName() returns the name of the column at a specified index and not the value of the column.
You should do
penyakit.set_nomber(Integer.parseInt(cursor.getString(0)));
or if the data type of the column idPen is INTEGER then:
penyakit.set_nomber(cursor.getInt(0));
Also don't try to get any other columns because your query returns only 1.
Note: remove that cursor.moveToFirst(); inside the if block because it is already executed.
Probably you need to use a ' instead of ". So, change the query to the following:
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\'" + namaGejal + "\'";
I'm suggesting you to use SQLiteDatabase.query() instead rawQuery like this:
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
"idPen"
};
// Filter results WHERE "namapen" = 'namaGejal'
String selection = "namapen" + " = ?";
String[] selectionArgs = { namaGejal };
// How you want the results sorted in the resulting Cursor
String sortOrder = null; // null for default order
Cursor cursor = db.query(
TABLE_CONTACTS, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
// do something with the cursor
Please take a look Read information from a database
If you want to get all columns data from your TABLE_CONTACTS use SELECT * FROM

How can I implement a String variable instead of 'Landschaft'?

I have created a SpinnerActivity, which looks like following:
http://img4.fotos-hochladen.net/uploads/bildschirmfotovse8j4po1t.png
Now for example if I select 'Landschaft' (in English: landscape) I want to search in the DatabaseHandler.java for a location which is in the category 'Landschaft' (landscape)
Therefore I have written the following method in DatabaseHandler.java:
In this method, I have just written Kategorie = Landscape.
However I want, that the selected SpinnerArray (Landschaft, Brücken...etc.) in my Spinner would be inserted in my DatabaseHandler instead of "Landschaft", how can I do that?
public List<Position> getAllPositionsWithCategory() {
List<Position> positionList = new ArrayList<Position>();
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = 'Landschaft'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Position position = new Position();
position.setID(Integer.parseInt(cursor.getString(0)));
position.setName(cursor.getString(1));
position.setKategorie(cursor.getString(2));
position.setLaenge(cursor.getFloat(3));
position.setBreite(cursor.getFloat(4));
// Adding position to list
positionList.add(position);
} while (cursor.moveToNext());
}
}
Simply replace the the fixed String with ? in your query, and pass the value to be inserted in the second argument of db.rawQuery().
The following might work for your case:
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = ?";
// ...
Cursor cursor = db.rawQuery(selectQuery, new String[] { "Landschaft" });
You can now replace your String "Landschaft" with a variable of your choice.
See also: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String,%20java.lang.String[])

Android SQLite: CursorIndexOutOfBoundsException when retrieving a row from a table?

I keep getting android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 exception when trying to get a single row from a Sqlite table using a ID value.
Why do you think this happens? What is wrong with my code?
public Product getProduct(DBOps dop, String productId) {
Product p = new Product();
String sqlQuery = "SELECT " + TableInfo.PID + " FROM "
+ TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'";
SQLiteDatabase SQ = dop.getReadableDatabase();
Cursor CR = SQ.rawQuery(sqlQuery, null);
try
{
if(CR.getCount() > 0)
{
while (!CR.isAfterLast()) {
p.PID = CR.getString(0);
p.NAME = CR.getString(1);
p.SIZE = CR.getString(2);
p.COLORS = CR.getString(3);
p.DESC = CR.getString(4);
p.PRICE= CR.getString(5);
p.OUTLETS = CR.getString(6);
p.FABRIC = CR.getString(7);
p.QUANTITY = CR.getString(8);
p.CATEGORY = CR.getString(9);
p.RATING = CR.getString(10);
CR.moveToNext();
}
}
else
{
CR.close();
}
}
catch(Exception ex)
{
Log.e("DBOps Error", "Look at DBOps Class's getProduct Method");
Log.e("DBOps Error", ex.toString());
}
return p;
}
android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 1
Because you are currently selecting only one column from table which is TableInfo.PID but trying to retrieve more then one column from cursor.
So change select query by specify all columns in select query or use * FROM get all columns:
String sqlQuery = "SELECT * FROM "
+ TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'";
Use Like This
if(cursor.getCount()>0)
{
if(cursor.moveToFirst())
{ do
{
//your code
}
while(cursor.moveToNext());
cursor.close();
}
}
Hope it will helps u
You need to call cursor.moveToFirst() before using the cursor. This moves it to row 0. Make sure to check the return value- if it returns false then it could not move to row 0 for some reason (generally it means 0 rows returned).

Android / Java: How to get last row value in sqlite?

Hello I am using a sqlite database in my android application, and I have question:
I am trying to get the last value text(thats the collumn) from the last row from the table TABLE_XYZ... but it does not work.. i am using the following code...what am I doing wrong?
another question is, how can I return two values instead of only one, when I want to get several values from the last row like column text and message?
private static final String KEY_MESSAGE = "message";
private static final String KEY_TEXT = "text";
...
String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.close();
return cursor.getString( cursor.getColumnIndex(KEY_TEXT) );
EDIT:
i hade some errors in my Query,, i fixed it, but still have errors:
String selectQuery= "SELECT * FROM " + TABLE_XYZ + " ORDER BY " + KEY_TEXT+ " DESC LIMIT 1";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String str = cursor.getString( cursor.getColumnIndex(KEY_TEXT );
cursor.close();
return str;
while debugging I can see that cursor does have the right values inside... but when i try to get the column value with this command "cursor.getString( cursor.getColumnIndex(KEY_TEXT );"... it does not work...
you are closing cursor before getting it's value
try this :
String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String str = "";
if(cursor.moveToFirst())
str = cursor.getString( cursor.getColumnIndex(KEY_TEXT) );
cursor.close();
return str;
From the android documentation: http://developer.android.com/reference/android/database/Cursor.html
abstract void close()
Closes the Cursor, releasing all of its resources and making it completely invalid.
You are closing the cursor before returningthe string.
Like #whatever5599451 said you should not close the cursor before you get value. Also try a query like this:
String selectQuery = "SELECT column FROM " + TABLE_XYZ +
" ORDER BY column DESC LIMIT 1";
You can specify the columns also specify to return only 1 row.
This will bring back only the column you are ordering by you can also specify more columns example:
String selectQuery = "SELECT column, column2, column3 FROM " + TABLE_XYZ +
" ORDER BY column DESC LIMIT 1";
* means select all columns
to get the last column, use the name of the column instead of " * " (* means all, all the fields)
#Steve: do this:
String selectQuery= "SELECT " + KEY_TEXT + " FROM " + TABLE_XYZ + " ORDER BY " + KEY_TEXT+ " DESC LIMIT 1";
then you get just one String with the last record containing just the right column

Categories