I am trying to update my SQLite database through this method in my SQLiteHelper class and I am getting the error:
android.database.sqlite.SQLiteException: unrecognized token: "55c7e253afcf48" (code 1): , while compiling: UPDATE login SET user_group=? WHERE uid=55c7e253afcf48.85187730
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
The uid is correct other than the extra ".85187730" at the end... I'm not sure what those numbers mean.
Here is my update method:
//updating sqlite database with the group name
public void updateUserGroup(String groupName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_GROUP, groupName);
HashMap<String, String> user = getUserDetails();
String userID = user.get("uid");
System.out.println("User id is: " + userID);
db.update(TABLE_LOGIN, values, SQLiteHandler.KEY_UID + "=" + "userID", null);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("user_group", cursor.getString(3));
user.put("uid", cursor.getString(4));
user.put("created_at", cursor.getString(5));
}
cursor.close();
//db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
Any help is appreciated.
You've missed quotation marks around your uid.
You should pass every string as below to avoid errors.
UPDATE login SET user_group=? WHERE uid="55c7e253afcf48.85187730"
and in your case query will be like
HashMap<String, String> user = getUserDetails();
String userID = user.get("uid");
db.update(TABLE_LOGIN, values, SQLiteHandler.KEY_UID + "=\"" + userID + "\"", null);
Related
I want to merge my two Hashmap methods. One method is for getting user ID and the other is for getting user String information. But I want to get all information from one hashmap method. Is it possible? If it is, how can I do this in my getuserdetails hashmap method?
Method 1:
public HashMap<String, Integer> getUid() {
HashMap<String, Integer> uid = new HashMap<String,Integer>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
Log.d("database", "before uid put");
if (cursor.getCount() > 0) {
uid.put("uid",cursor.getInt(0));
}
cursor.close();
// return user
return uid;
}
Method 2:
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("created_at", cursor.getString(3));
}
cursor.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
The cleanest approach here would be to create a User object with fields for id, name, email and created_at, something like this:
public class User {
private int id;
private String name;
private String email;
private Date createdAt; // Or use string here, whichever you want
// create or generate getters and setters for above fields
}
You can then get the data from the database using your query and create a user:
public User getUserDetails() {
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
User user = new User();
if (cursor.getCount() > 0) {
user.setId(cursor.getInt(0));
user.setName(cursor.getString(1));
user.setEmail(cursor.getString(2));
user.setCreatedAt(cursor.getString(3));
}
else {
cursor.close();
return null; // There wasn't a user to be found
}
cursor.close();
return user;
}
Now your method creates a User object, containing all required information.
Make a class with uid and name veriable And Create a hashmap method as a return type of this class. Hope this will work.
you can wrap together in a class like
public class Info {
public int uid;
public String name;
}
and have a HashMap<String, Info>
I add data into a database using this code,
/**
* Storing deck
* */
public void addDeck(String id, String name, String uid, String did) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DECK_ID, id); // ID
values.put(KEY_DECK_NAME, name); // Name
values.put(KEY_DECK_UID, uid); // Unique Id
values.put(KEY_DECK_DID, did); // Deck id
// Inserting Row
db.insert(TABLE_DECK, null, values);
db.close(); // Closing database connection
}
Now I want to be able to access each row, how can I do this?
This is my current code to access the rows in the database
// Getting deck data from database
public HashMap<String, String> getDeckDetails(){
HashMap<String,String> deck = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_DECK;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
deck.put("id", cursor.getString(1));
deck.put("name", cursor.getString(2));
deck.put("uid", cursor.getString(3));
deck.put("did", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return deck;
}
This code only returns the first row, how can I get it to return every row?
you have to use a loop:
Cursor cursor = db.rawQuery(selectQuery, null);
while( cursor.moveToNext() ){
deck.put("id", cursor.getString(1));
deck.put("name", cursor.getString(2));
deck.put("uid", cursor.getString(3));
deck.put("did", cursor.getString(4));
}
cursor.close();
also, instead of cursor.getString(3) I'd use:
int uidPos = cursor.getColumnIndex( "uid" );
if( -1 != uidPos ) cursor.getString( uidPos );
as it's safer
I am working on a project where 6 edittext fields are inserted into the the database when i click the save button and it will be viewed in a list... I can able to achieve those things but problem is that i could not able to insert multiple rows into the DB. The listview is showing only the first inserted values always eventhough if i insert again. Please help me for this solution.... My code for table creation and insertion is as follows for your reference
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE_QUERY = null;
// Used
CREATE_TABLE_QUERY = "CREATE TABLE IF NOT EXISTS userMaster(Bar CHAR(25),Product CHAR(15), Name TEXT,Mrp CHAR(15),Quantity CHAR(15), Tax CHAR(15));";
db.execSQL(CREATE_TABLE_QUERY);
L.i("userMaster Table created");
}
public void insertDetails(String bar, String mrp, String quantity,
String tax, String product, String name) {
SQLiteDatabase dbase = this.getReadableDatabase();
ContentValues cv = new ContentValues();
cv.put("bar", bar);
cv.put("product", product);
cv.put("name", name);
cv.put("mrp", mrp);
cv.put("quantity", quantity);
cv.put("tax", tax);
dbase.insert("userMaster", null, cv);
dbase.close();
} <br>
public void insertUserMaster(String bar, String mrp, String quantity,
String tax, String product, String name) {
SQLiteDatabase SqlDB = getWritableDatabase();
SqlDB.delete("userMaster", null, null);
String INSERT = "insert into userMaster (Bar,Product,Name,Mrp,Quantity,Tax) values (?,?,?,?,?,?)";
SQLiteStatement insertstatment = SqlDB.compileStatement(INSERT);
insertstatment.bindString(1, bar);
insertstatment.bindString(2, product);
insertstatment.bindString(3, name);
insertstatment.bindString(4, quantity);
insertstatment.bindString(5, mrp);
insertstatment.bindString(6, tax);
insertstatment.executeInsert();
SqlDB.close();
close();
} <br>
The array list representation is as follows
public ArrayList<HashMap<String, String>> getdata() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query("userMaster", null, null, null, null, null,
null, null);
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
if (cursor != null) {
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
do {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("bar", cursor.getString(0));
hm.put("product", cursor.getString(1));
hm.put("name", cursor.getString(2));
hm.put("mrp", cursor.getString(3));
hm.put("quantity", cursor.getString(4));
hm.put("tax", cursor.getString(5));
arraylist.add(hm);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return arraylist;
}
Use proper query to avoid those issue. Before inserting check whether you are deleting the existing table..
In method insertUserMaster you delete all data before insert.
Remove this line:
SqlDB.delete("userMaster", null, null);
I created database with few tables, got 1 table called friend. A friend has few expenses, some expenses might share with another friend. Now i am trying to delete a friend, what i am trying to do is when the friend share expenses with another friend, the expense of the friend that shared with another friend will then added to another friend and the expense will not deleted. Then, the expenses that are not shared with another friend is directly deleted and will not added to any friend since the friend has many expenses. Now the problem is when i trying to add the expense to another friend, its not working. And i am not getting any error.
Here is my code : i think the problem occur inside if(sharerList.size()>1)...., since the rest of the code works well.
public void deleteFriend(String id) {
Log.d(LOGCAT, "delete");
SQLiteDatabase database = this.getWritableDatabase();
ArrayList<HashMap<String, String>> wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM FriendsExpenses WHERE friendId='" + id + "'";
SQLiteDatabase databaseread = this.getReadableDatabase();
Cursor cursor = databaseread.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("expenseId", cursor.getString(0));
wordList.add(map);
} while (cursor.moveToNext());
}
for (int a=0; a<wordList.size();a++){
HashMap<String, String> ValexpenseId = wordList.get(a);
for (Entry<String, String> entry : ValexpenseId.entrySet()) {
String value = entry.getValue();
String selectQuery2 = "SELECT * FROM FriendsExpenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread2 = this.getReadableDatabase();
Cursor cursor2 = databaseread2.rawQuery(selectQuery2, null);
ArrayList<HashMap<String, String>> sharerList = new ArrayList<HashMap<String, String>>();
if (cursor2.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("friendId", cursor2.getString(0));
wordList.add(map);
} while (cursor2.moveToNext());
}
else{};
if (sharerList.size() > 1){
String selectQuery3 = "SELECT expenseTotal FROM expenses WHERE expenseId='" + value + "'";
SQLiteDatabase databaseread3 = this.getReadableDatabase();
Cursor cursor3 = databaseread3.rawQuery(selectQuery3, null);
String expenseTotal = null;
if (cursor3.moveToFirst()) {
do {
expenseTotal = cursor3.getString(cursor3.getColumnIndex("expenseTotal"));
} while (cursor3.moveToNext());
}
for (int b=0; b<sharerList.size();b++){
HashMap<String, String> ValfriendId = sharerList.get(b);
for (Entry<String, String> entry2 : ValfriendId.entrySet()) {
String value2 = entry2.getValue();
String currentSpend = currentSpending(value2);
double currentSpending = (Double.parseDouble(currentSpend));
double expTotal = (Double.parseDouble(expenseTotal));
double newSpending = currentSpending + ((expTotal/sharerList.size()) /sharerList.size()-1);
updateSpending(value2, newSpending);
}
}
}
else
{
String deleteQuery = "DELETE FROM expenses where expenseId='" + value + "'";
Log.d("query", deleteQuery);
database.execSQL(deleteQuery);
}
}
}
String deleteQuery = "DELETE FROM friends where friendId='" + id + "'";
String deleteQuery2 = "DELETE FROM FriendsExpenses where friendId='" + id + "'";
Log.d("query", deleteQuery2);
Log.d("query", deleteQuery);
database.execSQL(deleteQuery2);
database.execSQL(deleteQuery);
}
sharerList is empty because you never add any entries.
There are likely to be other copy/paste errors, such as getString(0) with SELECT *.
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;