How to update a record in SQLite with Android? - android

How to update a record in SQLite with Android?
Hello.
I write because I am unfortunately stuck in my project and I hope you can help me.
How do I update a record in a database?
For example in a contact database. In this database of contacts, the following keys are used: name, phone, email and address; my problem is when I need to modify a record, what must I do to modify a record.
I hope you can help me. Thanks in advance.
This is the SQLite code to update the registry:
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
}
This same code I have found on many websites, but my problem is how to call the code from the MainActivity with Java.

1- create an instance from ur database in the main activity:
DBhelper db = new DBhelper(this);
2- call open:
db.open();
3- set the update method:
db.updateContact(name,phone);
4- close the database connection:
db.close();
5- open and close function in ur database helper class:
public DBhelper open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
6- also you gotta define those as global variables:
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
my advice to you is not to depend on written code you gotta learn to write it ur self specially database creation and usage it is really important so here is a good tutorial for you, you could benefit from it: http://www.tutorialspoint.com/android/android_sqlite_database.htm.
Good luck

Related

inserting data without getWritableDatabase()?

I'm practicing android, I was able to insert using db.insert() without the use of getWritableDatabase() why is that? I thought we need db = getWritableDatabase(); before we can insert to the database
private SQLiteDatabase db;
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
//some table creation
db.execSQL(TABLE);
fillQuestionsTable();
}
private void insertQuestion(Question question){
ContentValues cv = new ContentValues();
//some code
db.insert(QuestionsTable.TABLE_NAME, null, cv);
}
I thought it should be like this?
private void insertQuestion(Question question){
db = getWritableDatabase();
ContentValues cv = new ContentValues();
//some code
db.insert(QuestionsTable.TABLE_NAME, null, cv);
}
here's my implementation:
private void fillQuestionsTable(){
Question q1 = new Question("Programming, Easy: A is correct", "A", "B", "C",
1, Question.DIFFICULTY_EASY, Category.PROGRAMMING);
insertQuestion(q1);
}
your code works, because you are storing reference to db object in onCreate and then re-using this reference further. that should work in most of common cases, but getWritableDatabase() and getReadableDatabase() methods are there for a reason - you should use them in your insert/update/remove methods just like you posted. For safer, more reliable access in future app releases when there may/probably will be more code, more tables and more complicated lifecycle of app. and get rid of private SQLiteDatabase db; declaration on top of your SQLiteOpenHelper, use only locally fetched (with above methods) database object

SQLite file from assets not getting updated after inserting a record

I am trying to insert a record in my database but it's not updating my database.
My insert method:
public void insert(String name, String status, String seat, String id, String pnr) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_ID, id);
contentValues.put(DatabaseHelper.COL_NAME, name);
contentValues.put(DatabaseHelper.COL_PNR, pnr);
contentValues.put(DatabaseHelper.COL_STATUS, status);
contentValues.put(DatabaseHelper.COL_SEAT_NO, seat);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
Code when inserting:
dbManager = new DBManager(getContext());
dbManager.open();
dbManager.insert("Name","XYZ","B1 21", "2","2348384");
open method:
public DBManager open() throws SQLException {
databaseHelper = new DatabaseHelper(context) {};
database = databaseHelper.getWritableDatabase();
return this;
}
I am using SQLite Asset Helper in my DatabaseHelper and the database is stored in assests/databases
Thank you in advance!
Assets folder is meant for read-only purposes. You cannot alter the contents at run time - except build/development time.
In your case, I would suggest you to copy the database file from assets to your app's private folder (or your desired location) on SD/external storage and then use that database file to perform read/write operations.
In short, your assets' database is good for read operations only.
Note: same rules applies to Raw resources too and they serve a slightly different purpose.

android.database.sqlite.SQLiteException: no such table: OrderDetails (code 1) [duplicate]

This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 4 years ago.
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
Here is my code for sqlite in android studio
public class Database extends SQLiteAssetHelper{
private static final String DB_NAME="Jerson.db";
private static final int DB_VER=1;
public Database(Context context)
{
super(context, DB_NAME,null,DB_VER);
}
public List<Orders> getCarts()
{
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect={"MenuId","Name","Quantity","Price"};
String sqlTable="OrderDetails";
qb.setTables(sqlTable);
Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);
final List<Orders> result = new ArrayList<>();
if (c.moveToFirst())
{
do {
result.add(new Orders(c.getString(c.getColumnIndex("MenuId")),
c.getString(c.getColumnIndex("Name")),
c.getString(c.getColumnIndex("Quantity")),
c.getInt(c.getColumnIndex("Price"))
));
}while (c.moveToNext());
}
return result;
}
public void addToCart(Order order)
{
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO OrderDetails(MenuId,Name,Quantity,Price)VALUES('%s','%s','%s','%s');",
order.getMenuId(),
order.getName(),
order.getQuantity(),
order.getPrice());
db.execSQL(query);
}
public void cleanCart()
{
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM OrderDetails");
db.execSQL(query);
}
}
I am sure I have a table in sqlite I dont know why its returning me no such table
here is a snippet of code on where I use the database
btnCart.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
new Database(getBaseContext()).addToCart(new Order(
foodId,
currentFood.getName(),
numberButton.getNumber(),
currentFood.getPrice()
));
Toast.makeText(FoodDetail.this, "Added To Cart", Toast.LENGTH_SHORT).show();
}
});
The most common cause for table not found is that it hasn't been created when the database is created. This may be due to an SQL error in the tale create statement or issues encountered when copying a packaged database from the assets folder.
The latter can be a badly written copy process, hence why SQLiteAssetHelper is frequently recommended as it's tried and tested. However, even with SQliteAssetHelper a bad file can result in such an error, such a database saved before the table is created as some SQLite Tools can allow.
When using SQLiteAssethelper, as per this question. The fix should be to :-
Delete the App's Data or Uninstall the App (both will delete the existing database allow it be copied (SQLiteAssethelper checks to see if the Database exists, if so then it doesn't attempt to copy the asset)).
Check that Database is sound using an SQlite tool and save it.
Copy the saved file (best done outside of Android Studio) to the App's assets/database folder (creating the assets folder and databases folder if need be).
Rerun the App.

Unable to insert new record in SQLite using Emulators

I am trying to develop a small app where at the end of the flow which needs to insert one row of data in SQLite database.
Following is the code which i am trying for insert:
SQLiteDatabase db = this.getReadableDatabase();
ContentValues values = new ContentValues();
values.put("UserId",1);
values.put("A",scoreValues.get("I"));
values.put("B",scoreValues.get("J"));
values.put("C",scoreValues.get("K"));
db.insert("ScoreTbl",null,values);
db.close();
When the above code is run, i am getting an Error message,
W/FileUtils: Failed to
chmod(/data/user/0/com.abc.xyz/databases/mydatabase.db: :
android.system.ErrnoException: chmod failed: EPERM
Can somebody help me how to overcome this error?
change this..
SQLiteDatabase db = this.getReadableDatabase();
to
SQLiteDatabase db = this.getWritableDatabase();
getReadableDatabase() method Create and/or open a database.
getWritableDatabase() method Create and/or open a database that will be used for reading and writing.
check Docs
the db class extends SQLiteOpenHelper and also create table then after used below code to insert data.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
values.put("UserId",1);
values.put("A",scoreValues.get("I"));
values.put("B",scoreValues.get("J"));
values.put("C",scoreValues.get("K"));
db.insert("ScoreTbl",null,values);
db.close();

how to set the delete method in sqlite database correctly?

I have a database called "Users" and a table in that database called "contact". i want to delete a selected contact when I click a button. I want to know how to set the parameters correctly to the delete method. if somebody can gimme an answer with a little example i will be delighted .
my code goes like this
private void deleteContact(String name) {
SQLiteDatabase database=openOrCreateDatabase("Users",MODE_PRIVATE,null);
int res=database.delete("contact", "name =", name);
///
}
I call this method when I click that Button. my query is,
"delete from contact where name ='"+name+"';
If your datebase table name is Contact and name is unique identifier and name of column you are inserting names is COLUMN_NAME then
//Delete single item from Db
public void deleteContact(String name){
SQLiteDatabase db = this.getWritableDatabase();
db.delete("Contact", COLUMN_NAME + " = ?", new String[]{name});
db.close();
}
private void deleteContact(String name) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("contact","name=?" , new String[]{name});
db.close();
}

Categories

Resources