I'm familiar with Oracle SQL/PL, but not with SQLite, I have managed to construct my database, with an addition operation. I was however wondering how I could implement a WHERE condition for adding data later on to a specific row.
Here is my addition code:
public void putInformation(DatabaseOperations dop, String name, String pass, String email){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME,null, cv);
Log.d("Database Operations", "One Raw Inserted");
}
I think you are looking for an UPDATE query:
public void updateInformation(DatabaseOperations dop, String name, String pass, String email){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.update(TableData.TableInfo.TABLE_NAME, cv, TableData.TableInfo.USER_NAME+"=?",new String[]{name});
Log.d("Database Operations", k+" Rows Updated");
}
SQLiteDatabase.update docs
WHERE condition for adding data later on to a specific row. If I understand correctly then it will be update for sqlite database. For that you can refer below code.
public void updateInformation(DatabaseOperations dop, String name, String pass, String email){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long index = SQ.update(TableData.TableInfo.TABLE_NAME, cv, TableData.TableInfo.USER_NAME+"=?", new String[] {name});
}
You can't use WHERE condition on insert query. WHERE condition for adding data later on to a specific row. For this you can use UPDATE query.
LINKS:
http://www.tutorialspoint.com/sqlite/sqlite_update_query.htm
http://android-er.blogspot.in/2011/06/edit-row-in-sqlite-database-using.html
Related
Im trying to seed my sqlite database with testdata in onCreate method in my SqliteOpenHelper... However, it doesn't matter why I try it still won't work.. Im getting getDatabase called recursively.
This is the code of my SqliteOpenHelper class..
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(SQL_CREATE_CONTACT);
SeedData();
} catch (SQLException e) {
Log.d("ContactDbHelper", "Create Database failed" + e.getMessage());
}
}
private void SeedData() {
db = getWritableDatabase();
Contact contact = new Contact("Test1", "CEO/Founder", "http://test.se/system/data/6816/medium/test1.jpg", "blalblalblalblalblalbalbalallbalabalalbalb");
// Create ContentValues
ContentValues contentValues = new ContentValues();
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_NAME, contact.getName());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_PROFESSION, contact.getProfession());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_URL, contact.getUrl());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_DESCRIPTION, contact.getDescription());
// Insert values into Contact table rows
db.insert(
ContactContract.Contact.TABLE_NAME,
null,
contentValues
);
Contact contact2 = new Contact("Test2", "Employee", "http://test2.se/system/data/6816/medium/test2.jpg", "asdadsadadadadasdasdadsasds");
// Create ContentValues
ContentValues contentValues2 = new ContentValues();
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_NAME, contact.getName());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_PROFESSION, contact.getProfession());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_URL, contact.getUrl());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_DESCRIPTION, contact.getDescription());
// Insert values into Contact table rows
db.insert(
ContactContract.Contact.TABLE_NAME,
null,
contentValues2
);
}
Is there any other way to insert multiple rows with data, or any other approach to seed? I don't like plain sql-queries, I still wanna use SqliteDatabase db.insert()
I also tried creating custom Insert method and called it form SeedData method but got recursive error again:
// Create
public long Insert(Contact contact){
db = getWritableDatabase();
// Create ContentValues
ContentValues contentValues = new ContentValues();
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_NAME, contact.getName());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_PROFESSION, contact.getProfession());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_URL, contact.getUrl());
contentValues.put(ContactContract.Contact.COLUMN_NAME_CONTACT_DESCRIPTION, contact.getDescription());
// Insert values into Contact table rows
long contactId = db.insert(
ContactContract.Contact.TABLE_NAME,
null,
contentValues);
// Return generated id from database
return contactId;
}
Don't use db = getWritableDatabase();. This is causing the looping.
Pass SQLiteDatabase as an argument to SeedData(SQLiteDatabase db) in onCreate method
This method is supposed to update the friend in the database. But it is not. No error is shown, tried restarting to refresh the list etc still nothing. Log is showing me new values but they are not saved in the database.
public void updateFriend(Friend friend) {
Log.d("UpdateFriendMethod", friend.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, friend.getName());
values.put(KEY_BIRTHDAY, friend.getBirthday().getTimeInMillis());
db.update(TABLE_Friends,
values,
KEY_NAME + " = ?",
new String[] { String.valueOf(friend.getName()) });
db.close();
}
Here is the way how do I get items from db:
public List<Friend> getAllFriends() {
List<Friend> Friends = new LinkedList<Friend>();
String query = "SELECT * FROM " + TABLE_Friends;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Friend friend = new Friend();
friend.setName(cursor.getString(0));
Date date = new Date(cursor.getLong(1));
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
friend.setBirthday(cal);
Friends.add(friend);
} while (cursor.moveToNext());
}
Log.d("getAllFriends()", Friends.toString());
return Friends;
}
I bet, problem is somewhere in that SQL statement, I am not familiar with it yet, I am used to SQL language not this.
SOLVED, problem was in SQL statement as I later found out:
public void updateFriend(Friend friend) {
Log.d("UpdateFriendMethod", friend.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, friend.getName());
values.put(KEY_BIRTHDAY, friend.getBirthday().getTimeInMillis());
db.update(TABLE_Friends, values, KEY_NAME + "='" + friend.getName()
+ "'", null);
db.close();
}
Hi I want to update an entry in my DB , I am giving my codes for the updateEntry function below..I want to update the password field I have tried something but it is not working
public String updateEntry(String Password) {
// Create object of content values
ContentValues updatedValues = new ContentValues();
// Assign values for each item
// updatedValues.put("USERNAME", User_name);
updatedValues.put("PASSWORD", Password);
String where = "PASSWORD=?";
db.update("LOGINDETAILS", updatedValues, where,
new String[] { Password });
return Password;
}
and this is the code I have written to update the entry :
String Passwordnew =loginDataBaseAdapter.updateEntry(Confirm_password);
Passwordnew=Confirm_password;
where I want update the password in DB with the confirm_password. I need some good suggestions.
public int UpdateContact(int id,String username,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(USERNAME, username);
values.put(PASSWORD, password);
// updating Row
return db.update(LOGINDETAILS, values, KEY_ID + " = ?",
new String[] { id });
}
call this database function to your Activity
db.UpdateContact("1","dhaval","1234");
public int updateProfile(GetSet profile) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, profile.getUniqueID());
values.put(NAME, profile.getName());
values.put(EMAIL, profile.getEmail());
values.put(DOB, profile.getDob());
values.put(PHONE, profile.getPhone());
values.put(PLACE, profile.getPlace());
// db.close();
// updating row
return db.update(TABLE_NAME, values, ID + " = ?",
new String[] { profile.getUniqueID() });
}
In the corresponding activity:
RemoteDatabase remote = new RemoteDatabase(this);
GetSet profile;
profile = new GetSet(setname, seteid, setphone, setplace,
setdob);
profile.setUniqueID(sdumid);
remote.updateProfile(profile);
remote.close();
Your Logic needs correction, Don't use Password for where clause, use field that is the primary key for your database, maybe username or an auto-increment id.
Then you can update using following code:
public boolean update(int id,String username,String password)
{
ContentValues cv = new ContentValues();
String where = id+"=?";
cv.put(USERNAME, username);
cv.put(PASSWORD, password);
return db.update(TABLE_NAME, cv, where,new int[] { id })>0;
}
Hello I'm using this code to insert data into my database. In another activity I use a Cursor and I can see the data of table1 or table2 individually. But if I use both I can only see the data of table 2.
When I use the cursors to get the data I see that one is empty. I think I'm not inserting the data correctly.
What am I doing wrong?
ContentValues cv=new ContentValues();
//TABLE 1
cv.put(idAttendance, 1);
cv.put(attendPlayer, "Tiago");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 2);
cv.put(attendPlayer, "Joao");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 3);
cv.put(attendPlayer, "Pedro");
db.insert(AttendanceTable, idAttendance, cv);
//TABLE2
cv.put(idTrainInd, 1);
cv.put(TIindicator, "Remate Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
cv.put(idTrainInd, 2);
cv.put(TIindicator, "Remate SEM Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
Still can't save data.
My Class is something like this:
public class DatabaseHelper extends SQLiteOpenHelper {
private ... // database and tables
public DatabaseHelper(Context context) {
super(context, dbName, null,33);
}
SQLiteDatabase db = null;
#Override
public void onCreate(SQLiteDatabase db) {
//here i create all tables
db.execSQL("CREATE TABLE ... )
db=this.getWritableDatabase();
//THEN I USE THE CODE OF MY FIRST QUESTION
ContentValues cv=new ContentValues();
//TABLE 1
cv.put(idAttendance, 1);
cv.put(attendPlayer, "Tiago");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 2);
cv.put(attendPlayer, "Joao");
db.insert(AttendanceTable, idAttendance, cv);
cv.put(idAttendance, 3);
cv.put(attendPlayer, "Pedro");
db.insert(AttendanceTable, idAttendance, cv);
//TABLE2
//TABLE2
cv.put(idTrainInd, 1);
cv.put(TIindicator, "Remate Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
cv.put(idTrainInd, 2);
cv.put(TIindicator, "Remate SEM Sucesso");
db.insert(TrainingIndicatorTable, idTrainInd, cv);
//THEN I USE THIS TO RETURN GET THE DATA BUT TABLE TWO IS STILL EMPTY
/**Get all players from local database*/
public Cursor getPlayers() {
// db = this.getReadableDatabase();
Cursor c=db.rawQuery("SELECT player FROM Attendancetabl", null);
//c.close();
return c;
}
/**Get all players from local database*/
public Cursor getIndicadors() {
// db = this.getReadableDatabase();
Cursor c=db.rawQuery("SELECT indicator FROM TrainingIndicador", null);
//c.close();
return c;
}
It's the same problem of the first question.
Try to use support code:
private void insertData(SQLiteDatabase base, String table, String columnHack, ContentValues values) {
base.beginTransaction();
base.insertWithOnConflict(table, columnHack, values, SQLiteDatabase.CONFLICT_REPLACE);
base.setTransactionSuccessful();
base.endTransaction();
}
Then just call instead your db.insert this one code:
insertData(db, TrainingIndicatorTable, idTrainInd, cv);
Piece of code to Content Values insert will be like below.
private ContentValues initialValues;
initialValues = new ContentValues();
initialValues.put("User_ID", User_ID);
initialValues.put("FirstName", FirstName);
initialValues.put("LastName", LastName);
initialValues.put("UserID", UserID));
initialValues.put("Password",Password1);
initialValues.put("Email", Email);
mydb.insertTitle(initialValues,"CheckLogin");
// this will be you databse class or method to insert the values. hope this helps you.
I have a little problem with inserting data in sqlite in Android. I wrote a method which do that with ContentValues,but it's not working properly. Here is the method :
DatabaseHelper.class
public boolean executeQuery(String tableName,String keys,Object value){
return execQuery(tableName,keys,value);
}
private static boolean execQuery(String tableName,String key,Object value){
sqliteDb = instance.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(key, value.toString());
sqliteDb.insert(tableName, null, values);
return true;
}
And I'm using this like that :
dbHelper.executeQuery("users", "seed", seed); // string
dbHelper.executeQuery("users", "id", id); // int
dbHelper.executeQuery("users", "name", name); // string
dbHelper.executeQuery("users", "lang", lang); // string
And the problem is that I this method insert all values as single row in database,but I want all data to be a part of one row.
What I have to do to get the things to work correctly?
I'm not really good with sqlite,so please excuse me if my question is a little silly...
Thanks in advance!
private static boolean execQuery(String tableName,String seed,String id,String name, String lang){
sqliteDb = instance.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("seed", seed);
values.put("id", id);
values.put("name", name);
values.put("lang", lang);
sqliteDb.insert(tableName, null, values);
return true;
}
dbHelper.executeQuery("users",seed,id, name,lang); // string
EDITED
private void execQuery(String tableName,ContentValues val)
{
sqliteDb = instance.getWritableDatabase();
sqliteDb.insert(tableName, null, val);
return true;
}
call
ContentValues values = new ContentValues();
values.put("seed", seed);
values.put("id", id);
values.put("name", name);
values.put("lang", lang);
dbHelper.executeQuery("users",values); // string
You should use the same ContentValues object to add all your desired columns. Like this:
Content values= new ContentValues();
values.add("seed",seed);
values.add("id",id);
values.add("name",name);
values.add("lang",lang);
sqliteDb.insert(tableName,null,values);
you have to pass string key array and Object array
dbHelper.executeQuery("users", /*Array of seed,id,name,lang*/, /*Object Array of their value*/);
and use
values.put(key[i], value[i].toString()); for all i=0 to n