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.
Related
I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.
Is there a good method or query to check if the UserId == ThreadId?
My current code:
public void deleteThread() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_THREAD, null, null);
db.close();
Log.d(TAG, "Deleted all Thread info from sqlite");
}
You need to pass correct value to the well-documented delete method to narrow down the scope of deletion to a subset of all entries in the DB table.
public void deleteThreadById(String threadId) {
SQLiteDatabase db = this.getWritableDatabase();
String whereClause = "threadId = " + threadId;
db.delete(TABLE_THREAD, whereClause, null);
db.close();
}
Deleting all threads of a given user via their userId would be similar but probably doesn't make sense in a forum software.
This is how SQL works in general and it's a bit scary you started development without familiarising yourself with the very basics.
Something like this;
public void deleteThread(String threadName) {
SQLiteDatabase db = this.getWritableDatabase();
try {
db.delete(MYDATABASE_TABLE, "name = ?", new String[]{threadName});
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
Something long these lines, querying database to find the specific row that has column which matches the parameter.
For example to delete a row which the name column is "Hello World";
deleteThread("Hello World");
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 "?".
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.
This is my code:
public int getIdMotChuDe(String tenChuDe) {
int IDChuDe = 0;
try
{
Cursor c = null;
c = database.rawQuery(
"SELECT ChuDeID FROM DanhSachChuDe WHERE TenChuDe = ?"
, new String[] {tenChuDe});
c.moveToFirst();
IDChuDe = c.getInt(c.getColumnIndex("ChuDeID"));
c.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return IDChuDe;
}
I'm trying to get ChuDeID from DanhSachChuDe table with condition in WHERE clause. But i don't know why this function always return 0.
Help me please. Thanks! Sorry because my english.
This could be because an Exception is being thrown. The code you are using is not correctly checking the state of your Cursor - it attempts to moveToFirst() before any checking too see if the object is not null.
Your code also assumes a result is always returned. This is bad practise, and should be avoided. A much safer and more common solution is the following:
if (cursor != null) {
// If the cursor has results, move the cursor to first row
if (cursor.moveToFirst()) {
do {
// YOUR METHODS HERE
// then move to next row
} while (cursor.moveToNext());
}
}
I'm trying to write a function that will delete every row in a given table but I'm getting a null pointer exception. Could somebody point me in the right direction? Here is the code...
public void deleteall(){
SQLiteDatabase db = tweets.getWritableDatabase();
String delete = "TRUNCATE FROM tweets";
db.rawQuery(delete, null);
}
Check if tweets is null.
I think it's more simpler to use this call, than using rawQuery.
Your rawQuery must be parsed, but using the delete method it uses already a parametrized query.
db.delete('tweets',null,null);
just to delete all rows, you can use following method.
void deleteAll()
{
SQLiteDatabase db= this.getWritableDatabase();
db.delete(table_name, null, null);
}
dataBaseHelper = new DataBaseHelper(getApplicationContext(), DataBaseHelper.DataBaseName, null, 1);
sqLiteDatabase = dataBaseHelper.getWritableDatabase();
if (sqLiteDatabase != null) {
sqLiteDatabase.delete(DataBaseHelper.TableName, null, null);
Toast.makeText(MainActivity.this, "Refresh", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
break;
}
I was getting a null pointer exception, and then I realised that my method was not calling db.open() first. Added that (and db.close()) and it worked.
SQLite does not have any TRUNCATE statement, so you must do:
public void deleteall(){
SQLiteDatabase db = tweets.getWritableDatabase();
String delete = "DELETE FROM tweets";
db.rawQuery(delete, null);
}
The right answer is this:
db.delete('tweets',"1",null);
From Android official documentation: SQLiteDatabase