I'm trying to build my first Android application, but I'm experiencing a problem: I write following code for insert record in database, but I don't know how to delete a row, so can anybody help me???
Code for insert record:
public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
Spannable spn=txtAge.getText();
String name=txtName.getText().toString();
int age=Integer.valueOf(spn.toString());
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
Student emp=new Student(name,age,deptID);
dbHelper.AddEmployee(emp);
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();
Alerts.ShowEmpAddedAlert(this);
txtEmps.setText("Number of students "+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}
DELETE FROM tableName WHERE fieldName = value
This is delete query. Execute it with execSql
Edit: use execSql instead of rawQuery
You can simply do this using SQLiteDatabase.execSQL() and don't try rawQuery It's meant for querying.
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM tableName where fieldName=Value");
db.close();
Check out the detailed answer here
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");
Does anyone know if it is possible to sum a column using Sugar ORM? I've tried to find any documentation, and there is a raw query method, however, the raw query method does not have any returning values.
Example: "select sum(price) from atable"
Class.executeQuery() is void.
Sugar ORM does not seem very usable until this kind of features (along with JOIN etc) are present.
I finally do it with the following code:
long sumValue = -1L;
Database db = ((Application)SugarApp.getSugarContext()).obtainDatabase();
SQLiteDatabase sqLiteDatabase = db.getDB();
SQLiteStatement sqLiteStatement = sqLiteDatabase.compileStatement(
"SELECT SUM(column_name) FROM table_name");
try {
sumValue = sqLiteStatement.simpleQueryForLong();
} catch (Exception var16) {
var16.printStackTrace();
} finally {
sqLiteStatement.close();
}
Also need to change the Application class to can access to the DataBase property because has protected access (don't forget to modify the manifest properly).
public class Application extends SugarApp {
public Database obtainDatabase(){
return getDatabase();
}
}
Hope it helps.
You can perform raw queries by accessing sugar database object by reflection:
int sumValue = -1;
Field f = null;
try {
f = SugarContext.getSugarContext().getClass().getDeclaredField("sugarDb");
f.setAccessible(true);
SugarDb db = (SugarDb) f.get(SugarContext.getSugarContext());
Cursor cursor = db.getDB().
rawQuery("Select Sum(COLUMN_NAME) as s from TABLE_NAME" , null);
if (cursor.moveToFirst())
sumValue = cursor.getInt(cursor.getColumnIndex("s"));
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
It does not seem possible at present time. I ended up using greenDAO instead, a much faster (not depending on reflection) solution which gives access to the SQLiteDatabase-object, enabling all kind of custom possibilities.
The answer might be too late, but it will help new comers, its pretty easy to query custom queries to the database in order to SUM or use any query you could obtain access to the Database by the following code:
SugarDb sugarDb = new SugarDb(context);
then its pretty straight forward to query the database for example you could do
SQLiteDatabase database = sugarDb.getDB();
SQLiteStatement query = database.compileStatement("SELECT SUM(AMOUNT) FROM EXPENSES_MODEL");
try {
total = query.simpleQueryForLong();
} catch (Exception e) {
e.printStackTrace();
} finally {
query.close();
}
notice the underscore in table name? its how Sugar ORM names our tables so please be careful when calling the table.
notice how the column name is capitalised? its because Sugar ORM capitalise each column.
There's this method which i've created to know if a contact exists in my Sqlite database.
public Cursor doesContactExist(String name)
{
return db.rawQuery("select * from contacts where name = ?; ", new String[] {name});
}
But whenever it is called from another activity it crashes only at this point....
if(db.doesContactExist(name)==null){ <== crashes here
try {
db.open();
db.insertContact(name,cNumber);//name and number are Strings
listItems.add(name); //a List View array
db.close();
adapter.notifyDataSetChanged(); //adapter for ListView
}
catch (Exception e) {
//some code }
}
According to me the rawQuery is having some troulble, especially the sql String in it.
Any help please?
you try to make a select before your database is open:
if(db.doesContactExist(name)==null){ <== it is closed here
try {
db.open(); <== open the db here
change it to:
db.open();
if(db.doesContactExist(name)==null){
try {
I think it might help you..
db.open();
if(db.doesContactExist(name)==null)
{
try
{
// Your Code Here..
}
}
and in Database Class
public Cursor doesContactExist(String name)
{
return db.rawQuery("SELECT * FROM contacts WHERE name=?", new String[ {name.toString()});
}
use db.open() method before using any database function because it will open your connection with database.. and at last don't forget to close database like db.close() and if you are using Cursor anywhere in code please close this also. it not generates any error but it gives you warnings. :)
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'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