Android SQLite query is always empty - android

So right now I'm using this solution in my app Ship an application with a database
In my main activity, I just want to test to make sure that the database is working, so all I'm doing it a simply query to get some names, all I did was add 3 lines(commented where I added them):
DatabaseHelper myDbHelper;
SQLiteDatabase myDb = null;
myDbHelper = new DatabaseHelper(this);
/*
* Database must be initialized before it can be used. This will ensure
* that the database exists and is the current version.
*/
myDbHelper.initializeDataBase();
Cursor c;
String s = null;
try {
// A reference to the database can be obtained after initialization.
myDb = myDbHelper.getWritableDatabase();
//the next 3 lines are all I added
c = myDb.rawQuery("select name from breads", null);
s = c.getString(1);
c.close();
/*
* Place code to use database here.
*/
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
myDbHelper.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
myDb.close();
}
}
However, s just remains empty. If I do the exact same query select name from breads in the console, I will get data. Does anyone have any ideas?

myDb = myDbHelper.getWritableDatabase();
//the next 3 lines are all I added
c = myDb.rawQuery("select name from breads", null);
c.moveToFirst(); // ADD THIS
s = c.getString(1);
c.close();

Related

SQLite Database query function not replacing the ? with selection args

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 "?".

Application crashes while reading an empty table in android

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.

SQLite select all tables DESC

I have found the solution to get all tables in SQLite here.
How to list the tables in an SQLite database file that was opened with ATTACH?
However, when I change:
SELECT name FROM sqlite_master WHERE type='table';
into:
SELECT name FROM sqlite_master WHERE type='table' ORDER BY name DESC;
the output is completely weird.
The first query gives me:
tbl201306 --> only 1 table so far, for June 2013.
The second query gives me:
android_metadata --> the name is not changed, but it returns this name.
I want to have these tables in descending order because in the future, the newest table would be on the top then.
My complete code:
public ArrayList<String> getDBTables() {
ArrayList<String> toReturn = new ArrayList<String>();
try {
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name DESC", null);
c.moveToFirst();
while (c.moveToNext()) {
toReturn.add(c.getString(c.getColumnIndex("name")));
}
c.close();
}
catch(SQLiteException e) {
e.printStackTrace();
}
return toReturn;
}
Your code skips over the first returned record.
You can either
keep the call to moveToFirst(), and change the loop into a do { ... } while (); loop, or
just remove the call to moveToFirst().
This is the ultimate solution I used:
public ArrayList<String> getDBTables() {
ArrayList<String> toReturn = new ArrayList<String>();
try {
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'tbl%' ORDER BY name DESC", null);
while(c.moveToNext()) {
toReturn.add(c.getString(c.getColumnIndex("name")));
}
c.close();
}
catch(SQLiteException e) {
e.printStackTrace();
}
return toReturn;
}

How to connect to an existing database defined in a .sql file?

If we already have a database file in .sql format, how can we load this in our android app & use its data?
I also had this same problem and I did what jaydeep said. But I m not able to proceed..Please help me. I added 1 method in this to retrieve 1 record which is as follows:
public Cursor getTitle(String g,String k) throws SQLException {
Cursor c = myDataBase.rawQuery(
"select * from titles where food LIKE '%"+g+"%' and area LIKE '%"+k+"%' ",
null);
if (c != null) {
c.moveToFirst();
}
return c;
}
where titles is id name of table in database n food area n rest are fields. and in main file i did as follows:
{
Datahelper myDbHelper = new Datahelper(this);
final String tem="Chinese";
final String tem2="Bur Dubai";
final ListView list = (ListView)findViewById(R.id.list);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Cursor c = myDbHelper.getTitle(tem,tem2);
if (c.moveToFirst()) DisplayTitle(c);
else Toast.makeText(this, "No title found",
Toast.LENGTH_LONG).show();
}
public void DisplayTitle(Cursor c) {
final TextView ter=(TextView)findViewById(R.id.ter);
c.moveToPosition(0);
while (c.isAfterLast() == false) {
ter.append(c.getString(3)+"\n");
c.moveToNext();
}
c.close();
}
Please help me.
ListView code:
if (c.moveToFirst())
{
final String [] restarr=c.getColumnNames();
String[] fields = new String[] {db.KEY_REST};
list.setAdapter(new ArrayAdapter<String>(this, R.layout.main, restarr));
SimpleCursorAdapter rest = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,fields, new int[] {android.R.id.text1});
list.setAdapter(rest);
}
You need SQLite version of the database. I bet your current database you want to ship to the application, has schema written with pure SQL syntax which quite different from SQLite.
If my assumption is true, then you need to extract the schema and convert it to SQLite. This takes some minor changes in the syntax but logic stays the same.
Here is nice tutorial how you can ship your external local database in your android application:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
Mind the version and extension of the database file.

Problem with fetching data from SQLite in Android

I was following this tutroial about using your own SQLite database. I did these steps as described in the tutorial:
Preparing my database
Copying the same EXACT DataBaseHelper class to my project package. You can see the class code there
Then, I just added one method to the DataBaseHelper class which is fetchData. It is simply fetching a whole table with the given name:
public Cursor fetchData(String table) {
String[] selectionArgs = new String[] {"*"};
return myDataBase.query(table, null, null, selectionArgs, null, null, null);
}
After that, in one of my activity classes I did this:
DataBaseHelper myDbHelper;
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
TextView txt = (TextView) findViewById(R.id.txt);
try {
//I will use my method to fetch a table named: myTable
Cursor c = myDbHelper.fetchData("myTable");
if((Object)c.getCount() != null)
txt.setText(c.getCount());
else
txt.setText("null");
} catch(Exception e) {
txt.setText("error");
}
However, I keep getting 'error' in the TextView. Is there a problem in my way?
My problem is nothing related to SQLite. It was silly mistake :-\
The error is in the second line here:
if((Object)c.getCount() != null)
txt.setText(c.getCount());
It must be like this:
txt.setText(""+c.getCount());
the setText() method accepts a ChaSequence and the getCount() method returns Integer which are not in compatible type. you can work around that tha easy way, by adding empty string :)
Thanks Guys.
public Cursor fetchData(String table) {
return myDataBase.query(table, null, null, null, null, null, null);
}
Seems you got wrong idea about the selectionArgs parameter. In documentation, it says:
You may include ?s in selection, which
will be replaced by the values from
selectionArgs, in order that they
appear in the selection. The values
will be bound as Strings.
Your trying to cast an int as an Object, then comparing the cast value to null. I would say that you code is likely to break right there.

Categories

Resources