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
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");
my app should delete a specific row in the sql database by this method
public void delete(int id){
open();
sqLiteDatabase.delete("item","id = "+id,null);
close();
}
and it should also delete all rows if the user want that by this method
public void deleteAll(){
cursor=sqLiteDatabase.rawQuery("select * from item",null);
cursor.moveToFirst();
i=1;
while (!cursor.isAfterLast()) {
sqLiteDatabase.delete("item","id = "+i,null);
i++;
System.out.println(i);
cursor.moveToNext();
}
}
when the user use deleteAll() alone it is work but when he use it after using delete() it delete all rows before the deleted one using delete()
is the problem in deleteAll() method ? and how to fix it?
Your delete() function only deletes rows with the given id. If you want to delete all rows, then just do
sqLiteDatabase.delete("item", null ,null);
There is no reason to write your own loop especially since you never use the Cursor anyway.
Additionally, you should never use string concatenation for the "where" clause in a SQL statement. Instead use "id = ?" and provide a String[] with the values:
db.delete("image","id= ?", new String[] {id});
Here is an example of how to delete a particular column with an id:
SQLiteDatabase db= this.getWritableDatabase();
db.delete("image","id= ?", new String[] {id});
Toast.makeText(context,"Delete successfully",Toast.LENGTH_LONG).show();
Hope this will work for you
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.
So I have a database, SQLiteDatabase db I am writing a couple private methods in my manager class that will be called by a public method:
public void updateData (MakeabilityModel newData){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
reWriteSVTable(db, list);
db.setTransactionSuccessful();
} catch (Exception e){
//TODO through rollback message?
e.printStackTrace();
} finally {
db.endTransaction();
}
}
//Private Methods
private void clearTable(SQLiteDatabase db, String table){
db.delete(table, null, null);
}
private void reWriteSVTable(SQLiteDatabase db, List<MakeabilityLens> lenses){
clearTable(db, singleVision);
ContentValues cv;
for(int i=0; i<lenses.size(); i++){
cv = new ContentValues();
cv.put(colScreenID, hsID);
cv.put(colIconID, id);
cv.put(colRank, hsTotal);
db.insert(isLookUp, colID, cv);
}
}
My question is this.. i want to be able to throw sql exceptions back to the public method so that if there is an exception, it will kill the transaction and rollback ALL data..
it appears that using delete() and insert() methods are cleaner than execSQL() but don't throw sqlExceptions. execSQL() on the other hand does? do i need to uses execSQL and how do I insure that should it throws an exception in any of the private methods that it will catch it and roll it back in the private method
first of all execSQL() throws an exception if the sql string is not valid. that is the exception is on the sql string syntax NOT the sql operation. that is, it will not throw an exception if the sql statement is valid but the operation failed (because of a constraint for example).
So ..
basically the only difference between execSQL() and delete() is that delete() returns the number of rows affected (in your case, the number of deleted rows), but execSQL() doesn't.
Note:
for delete() to return the number of rows affected, you have to pass any value other than null in the where clause parameter. In your case, pass "1".
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.