Android database not updating - android

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();
}

Related

Pass id int into query

I have a query where I pass by parameters the groupID, but the query does not recognize the number(group id).All the values are reaching the query( I debugged). This is my query, can you see if the structure is ok?
public Cursor updateGrupo(String nomegrupo,int idgroup){
SQLiteDatabase db = this.getReadableDatabase();
//Does not put the ID in the "idgroup"
Cursor c = db.rawQuery("UPDATE '"+tableGrupo+"' SET '"+nomeGrupo+"' = '"+nomegrupo+"' WHERE '"+idGrupo+"' = '"+idgroup+"'", new String[]{});
return c;
}
You should use SQLiteDatabase as writable mode getWritableDatabase().
You should use below method for updating data:
update(String table, ContentValues values, String whereClause, String[] whereArgs)
Try this:
public void updateGrupo(String nomegrupo,int idgroup) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(nomeGrupo, nomegrupo);
db.update(tableGrupo, values, idGrupo + " = ? " , new String[]{String.valueOf(idgroup)});
}

turning SQLite outcome to integer - Android

I'm working on a project and in need to use new ID's added to my database as numbers,
How do I turn this:
String query = "SELECT * FROM " + playlistsDBName + " WHERE ID = LAST_INSERT_ROWID";
To an integer (or some other number type) that I can use in my Android code?
you should change this your method from:
public void addNewPlaylist(String DBName, String playlistName) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("PlaylistName", playlistName);
db.insert(DBName, null, values);
db.close();
}
to
public int addNewPlaylist(String DBName, String playlistName) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("PlaylistName", playlistName);
final int id = db.insert(DBName, null, values);
db.close();
return (int)id;
}

How to put and get the current date by using simple database

I'm a beginner and don't know how to insert and get the current date by using database.
For an insert into the database, I use a button for adding the information. Here is the full code:
public void Badd_Click(View view) {
db.execSQL("INSERT INTO Demo (event, venue, amount, textView) VALUES ('" + tEvent.getText().toString() + "'," + "'" + tLocation.getText().toString() + "'," + "'" + tAmount.getText().toString() +"' )");
Toast.makeText(this, "Create record successfully...", Toast.LENGTH_SHORT).show();
}
Then, for showing the information inserted into the database, I also use a button:
public void Btnshow_Click(View view){
String str = "";
Cursor c = db.rawQuery("SELECT * FROM "+DATABASE_TABLE,null);
c.moveToFirst();
for(int i = 0; i<c.getCount();i++){
str+="ID: "+c.getString(0)+"\n";
str+="Name : "+c.getString(1)+"\n";
str+="Location : "+c.getString(2)+"\n";
str+="Amount : "+c.getString(3)+"\n\n";
c.moveToNext();
}
I have searched for many solutions, but I am unable to do it successfully.
Please help :(
You can use below two methods to save and retrieve date from database in the format you want.
public static String getDbDateString(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
return sdf.format(date);
}
public static Date getDateFromDb(String dateText) {
SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyyMMdd");
try {
return dbDateFormat.parse(dateText);
} catch ( ParseException e ) {
e.printStackTrace();
return null;
}
}
You can get current date with below code:
Date date = new Date(System.currentTimeMillis());
To add to database:
public void addDate() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("key", "value");
// Inserting Row
db.insert(table_name, null, values);
db.close(); // Closing database connection
}
To read from database:
public Date getDate(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_name,
new String[]{column_id,
column_date_value},
column_id + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
assert cursor != null;
return new Date(cursor.getString(index_column_date));
}

Update Individual field in DB

I am Creating DB with three fields name,id,mark. I created table and inserted values using
StudentDb.addStudentDetail(new StudentDetails(id,Name,0));
I used Update method Like:
public int updateStudentDetail(StudentDetails student) {
SQLiteDatabase db = this.getWritableDatabase();`enter code here`
ContentValues values = new ContentValues();
values.put("id", student.getID());
values.put("name", student.getName());
values.put("mark", student.getMark());
int i = db.update(TABLE_STUDENT, values, KEY_ID + " = ?",
new String[] { String.valueOf(student.getId()) });
db.close();
return i;
}
I call this method Like:
StudentDb.updateStudentDetail(student);
I don't know how to pass a value update method?
its very simple. Lets say you want to update the marks of a student. Implement this in your DatabaseHelper class:
public int udpateStudentMarks(final int studentID,final int marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("mark", marks);
int i = db.update(TABLE_STUDENT, values, KEY_ID + " = ?",
new String[] { String.valueOf(studentID) });
db.close();
return i;
}
now you can use it like this:
db.updateStudentMarks(studID,newMarks);
Hope it helps.

how to apply filters in inserting data to sqlite in android

I have created an application to insert data to sq-lite . i want if i enter same data again it should give e toast massage and then it only update that data not re-insert.
what should i do.....
now data is been re-inserted
method code of SQLiteOpenHelper.....
public void insertdata(String name,String ph,String area){
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
sd=this.getWritableDatabase();
sd.insert("location", null, cv);
sd.close();
method use in Activity class......
public void onClick(View v) {
// TODO Auto-generated method stub
help=new MyHelper(getApplicationContext());
help.getWritableDatabase();
String myname=name.getText().toString();
String call=phone.getText().toString();
String myarea=area.getText().toString().trim();
help.insertdata(myname, call, myarea);
Toast.makeText(getApplicationContext(), "data saved ", Toast.LENGTH_SHORT).show();
}
});
The data is being reinserted because you're methods never check to see if it already exists in the databse. You need to add a query for some unique combination - probably name and phone number. If that query returns a result you can prompt the user to enter the data.
String query = "SELECT * FROM " + TABLE_NAME + " WHERE name = " + name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor != null && cursor.moveToFirst()){ //if cursor has entry then don't reinsert
//prompt user with dialog
} else {
//insert data
}
Also you cannot use a Toast for this. What you want is a Dialog. If the data exists you can display a custom Dialog to the user that you could use to allow them to (1) enter new data (2) edit existing data (3) choose to reinsert the data they are posting. A Toast will just display a message to them like - "reinserting data". It does not sound like that is the functionalty you want to achieve.
To update the database you can just use an update statment depending on what fields you want to change.
String query = "UPDATE " + TABLE_NAME + " SET";
if(!name.isEmpty(){
query += " name = " + name;
}
if(!phone.isEmpty(){
query += " phone = " + phone;
}
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(CREATE_CONTACTS_TABLE)
I put the if statments in to check for which fields are being changed and add them to the query accordingly. In the alternative you could use something like this
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()) });
}
While I havnet modified it to fit your example you can see the basic approach. Hhere you can use conditionals to check if values are being supplied, if they are you add them to the ContentVlues list which will update them in the DB.
You can try something like this:
ContentValues values=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
if (db == null) {
db = getWritableDatabase();
}
if (isNameExists(name)) { //check if name exits
id = db.update(TABLE_NAME, values, name + " = ?",
new String[] {name});
} else {
id = db.insert(TABLE_NAME, null, values);
}
public boolean isNameExists(String name) {
Cursor cursor = null;
boolean result = false;
try {
String[] args = { "" + name };
StringBuffer sbQuery = new StringBuffer("SELECT * from ").append(
TABLE_NAME).append(" where name=?");
cursor = getReadableDatabase().rawQuery(sbQuery.toString(), args);
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
} catch (Exception e) {
Log.e("AppoitnmentDBhelper", e.toString());
}
return result;

Categories

Resources