i have a get function in my database class to get a specific line from the DB.
public Line getLine(String date){
SQLiteDatabase sql = db.getWritableDatabase();
Cursor cursor;
Line line = new Line();
try{
cursor = sql.query(Db_name,null,DATE_COL+"=?",new String[] {date},null,null,null);
line = new Line(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3).equals("YES"));
}
catch (Exception e){
e.getCause();
}
finally {
if (sql.isOpen())
sql.close();
}
return line;
}`
however when i run it, the cursor is not getting the right query, when debbuging it looks like this:
SQLiteQuery: SELECT * FROM a28a9a2015 WHERE date_col=?
so it kept the ? and did not put the date string in there..
i've tried something like -
cursor = sql.query(Db_name,null,DATE_COL+"="+date,null,null,null,null);
OR
cursor = sql.query(Db_name,null,DATE_COL+"= '"+date+"',null,null,null,null);
with same result.
any pointers?
You need to move cursor to first position
cursor = sql.query(Db_name,null,DATE_COL+"=?",new String[] {date},null,null,null);
if (cursor.moveToFirst()) {
// TODO
}
Otherwise your cursor is in position -1 and cannot get any data. Symbol "?" is replacing inside request to sqlite so in cursor you'll see "?".
Related
I have an SQLite-Database with four columns
ID
Name
symptoms
Medicine
My Helper class code
public Cursor getMedicine(String symptom1)
{
SQLiteDatabase db=helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT medicine FROM diseases WHERE symptoms = ?;",new String[] {symptom1});
c.moveToFirst();
return c;
}
And here is code of my activity class :
String med = "";
Disp_med_DBHelper medicalHelp = new Disp_med_DBHelper(this);
medicalHelp.open();
medicalHelp.getMedicine(Value1);
med = medicalHelp.getMedicine(Value1).toString();
t1.setText(med);
medicalHelp.close();
Where t1 is my textbox, and Value1 is the string that we need to send to database helper to query the database.
When I check output on my textbox, I get the following output
android.database.sqlire.SQLiteCursor#4174986
What should I do to get it fixed?
Method toString() returns string representation of object Cursor. You have to use method getString(int column) from Cursor class.
Something like this:
med = medicalHelp.getMedicine(Value1).getString(0);
More info: https://developer.android.com/reference/android/database/Cursor.html
use this method instead:
public String getMedicine(String symptom1) {
SQLiteDatabase db = helper.getWritableDatabase();
Cursor c = db.rawQuery("SELECT medicine FROM diseases WHERE symptoms = ?;", new String[]{symptom1});
if (c.moveToFirst()) {
return c.getString(c.getColumnIndex("medicine"));
}
return null;
}
and then in your activity:
med = medicalHelp.getMedicine(Value1)
if(med!=null){
t1.setText(med);
}
Even when the cursor contains only a single value, it still behaves as a cursor that might have multiple columns and multiple rows. So you have to go to the first row (with moveToFirst(), which might fail), and read the value from the first column (with getString(0)).
However, for this simple situation, there is a helper function that allows you to avoid having to muck around with a cursor:
public Cursor getMedicine(String symptom1) {
SQLiteDatabase db = helper.getReadableDatabase();
return DatabaseUtils.stringForQuery(db,
"SELECT medicine FROM diseases WHERE symptoms = ?;",
new String[]{ symptom1 });
}
The issue is purely with the contents inside the tables. If the table is not empty (with one or more records), application works perfectly. I am deleting the contents of table and immediately after that reading the same table, it throws exception and app force closes.
I tried searching for it but couldn't conclude. The key point is : index out of bound exception which is thrown at movetofirst() method of cursor when i am going to read the table, i suppose... Please help.
public List<TableData> readForPaymentDetais()
{
List<TableData> paymentDetails = new ArrayList<TableData>();
try
{
String selectQuery = "select * from PaymentDetails";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if(cursor.getCount() !=0)
{
if(cursor.moveToFirst())
{
do
{
TableData data = new TableData();
data.setPaymentMade(Float.valueOf(cursor.getString(0).toString()));
data.setDateOfPayment(cursor.getString(1));
paymentDetails.add(data);
}
while(cursor.moveToNext());
}
}
return paymentDetails;
}
catch(Exception exc)
{
return null;
}
}
Before executing moveToFirst method of cursor please check whether cursor is empty. For that you can use code like:
if (mCursor.getCount() == 0) {
// cursor is empty
}
If cursor is not empty put your stuff in else part.
I want to fetch data from table "student" in SQLite android database
and here is the method that I use to retrieve the data
public Cursor getAllStudent(){
SQLiteDatabase db= helper.getWritableDatabase();
String[] columns={"_id",
"'reg_number'",
"'School_id'",
"'class_id'",
"'first_name'",
"'last_name'",
"'PPN'",
"'photo'",
"'CyncStatus'"};
Cursor cursor=null;
try {
cursor = db.query("student",columns,null, null,null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("select student failed: %d", e.toString());
}
return cursor;
}
and this is how I iterate through the result
Cursor c1 = studentHelperAdapter.getAllStudent();
c1.moveToFirst();
while (!c1.isAfterLast()){
String reg = c1.getString(1); // return column name not value
String name = c1.getString(4); //return name column not value
String reg = c1.getString(5); //return name column not value
c1.moveToNext();
}
c1.close();
and I have tried to add this line below to see cursor content and I realized that no data was fetched there are only column names
Log.d("AB cursor ",android.database.DatabaseUtils.dumpCursorToString(c1));
Anyway, there 2 similar questions but none of the solutions solved my problem
Get the field value with a Cursor
How to get field value instead of column name?
I look forward to see your answer here, thanks
I think your column names should just be strings.
"reg_number" not "'reg_number'"
also make sure that you are using correct types. Is the value stored in column "reg_number" really a String?
Now I want to access an entire column from database and then compare it with some text that I have stored...but I am getting no idea on how to do that..So can someone please help me with this...
Entire column? You mean all the values for a given column accross all records?
You should iterate the ResultSet obtained and start comparing the values (for example - if you iterate using "rs" object of ResultSet, you should compare:
String valueFromDB = rs.getString("myColumn");
String someTextStored = .... //the text being stored
if (valueFromDB != null) {
if (someTextStored.equals(valueFromDB) {
//Comparison succeeded - implement some logic here for handling success
}
}
And the above code should be inside a loop code that iterates over the ResultSet and
uses the "next" method to obtain the next record.
Hope this helps you
public ArrayList<String> getValues(){
Cursor cursor = null;
SQLiteDatabase db = getReadableDatabase();
Log.v("done","getting rows ");
cursor = db.rawQuery("SELECT YourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
list_values.add(cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
return list_values;
}
Now you are having all the values of a particular column you can compare it from this array list.
My SQLite query returning only one record, However, the table has multiple rows
cursor=mydb.rawQuery("Select category from items;", null);
I have even tried GROUP BY but still wont work.
I am new to SQLite, would appreciate any help. Thanks.
First of all your string query must not be terminated so instead of passing it as:
"Select category from items;"
you should try passing it as:
"Select category from items"
as mentioned on this page.
Also, are you looping over the cursor? Here is an example of how to get data out of a cursor with a while loop:
ArrayList<String> results = new ArrayList<String>()
while (cursor.moveNext()) {
results.add(cursor.getString(0)); // 0 is the first column
}
First, search:
Cursor cs = myDataBase.rawQuery("Your query", null);
if (cs.moveToFirst()) {
String a = cs.getString(cs.getColumnIndex("your_column_name"));
cs.close();
return a;
}
cs.close();
return "";
Get the information from cursor:
if (cs.moveToFirst()) {
ArrayList<String> results = new ArrayList<String>()
do {
results.add(cs.getString(cs.getColumnIndex("your_column_name")));
} while (cs.moveNext());
}
Without if, I took error in my project. But this worked for me. By the way, your query doesn't look good. If you give some information about your database, we can help much more.
Use this to select all items from the table:
Cursor cursor = db.rawQuery("SELECT * FROM Tablename ,
null);
this can help you
public ArrayList<mydata> getallContents() {
ArrayList<mydata> lst = new ArrayList<mydata>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + GAMETABLE, null);
if (c.moveToFirst()) {
do {
lst.add(new mydata(c.getString(1),
c.getString(3),c.getString(4),c.getString(5),c.getString(6)));
} while (c.moveToNext());
}
db.close();
return lst;
}
you don't need raw query method. i think that the android way is better in this case:
db.query(items, category, null, null, null, null, null);
than use the cursor how already is written in the other comment.