I'm new to Android programming and working on a first, small App.
I implemented an SQLite Database with 3 Columns (KEY_ID,KEY_DATUM,KEY_ANZAHL), where the Date Column is a String in the Format YYYY-MM-DD.
Where I struggle is getting Data out with a Query.
Can someone help me set up a Query, which checks if there is already a certain Date in my Database, and the either Add a new Entry in the DB or update an existing one? I also read about the strftime() function, but I have no idea where in my Code to use it...
I tried it with this, but it doesn't do anything
void addBiereintrag(Biereintrag biereintrag) {
// Get writable Access
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// With this query im trying to find out if the Date given by biereintrag is already in the Database
Cursor cursor = db.query(TABLE_BIER, new String[]{KEY_DATUM}, KEY_DATUM + "=?",
new String[]{biereintrag.getDatum()}, null, null,
null, null);
cursor.moveToFirst();
// if cursor == null, there is no entry for the Date, and the i put a new Entry
if (cursor == null) {
Log.d("test", "cursor ist null");
values.put(KEY_DATUM, biereintrag.getDatum()); // Datum aus get.Datum() holen
values.put(KEY_ANZAHL, biereintrag.getAnzahl()); // Anzahl zum Datum holen
// close DB connection
db.close();
} else {
values.put(KEY_DATUM, biereintrag.getDatum()); // Datum aus get.Datum() holen
// If there is already a Entry, then Add the value of biereintrag.getAnzahl() to the Value written in the cursor
values.put(KEY_ANZAHL, biereintrag.getAnzahl() + cursor.getInt(cursor.getColumnIndex("KEY_ANZAHL")));
// close DB connection
db.close();
}
cursor.close();
}
You need to upadte/insert values into your database after values.put() to make changes into database as:
// if cursor == null, there is no entry for the Date, and the i put a new Entry
if (cursor == null) {
Log.d("test", "cursor ist null");
values.put(KEY_DATUM, biereintrag.getDatum()); // Datum aus get.Datum() holen
values.put(KEY_ANZAHL, biereintrag.getAnzahl()); // Anzahl zum Datum holen
// insert values into database
database.insert(TABLE_BIER, null, values);
// close DB connection
db.close();
} else {
// If there is already a Entry, then Add the value of biereintrag.getAnzahl() to the Value written in the cursor
values.put(KEY_ANZAHL, biereintrag.getAnzahl() + cursor.getInt(cursor.getColumnIndex("KEY_ANZAHL")));
//update database with new value
database.update(TABLE_BIER, values, KEY_DATUM + " = ?",
new String[]{ biereintrag.getDatum()});
// close DB connection
db.close();
}
Related
I'm fetching data from server and storing it in local db i.e sqlite. It is inserting duplicate values in sqlite.
So my condition is :
Check with sqlite db is empty,insert the record
Check the id column of sqlite already present, if yes update it or else insert.
I've done so for :-
SQLiteDatabase db = dbhelp.getWritableDatabase();
ContentValues values = new ContentValues();
String sqlq = "Select clid from client_detail";
Cursor cccs = db.rawQuery(sqlq, null);
if (cccs.getCount()== 0) {
values.put("clid", queryValues.get("clid"));
values.put("_id", queryValues.get("_id"));
values.put("client_id", queryValues.get("client_id"));
values.put("client_name", queryValues.get("client_name"));
values.put("client_mobile", queryValues.get("client_mobile"));
values.put("client_phone", queryValues.get("client_phone"));
values.put("client_email", queryValues.get("client_email"));
values.put("client_address", queryValues.get("client_address"));
db.insert("client_detail", null, values);
}else{
if (cccs.moveToFirst()) {
do{
Log.d("Client ID",""+cccs.getString(0));
clid.add(cccs.getString(0));
String temp = cccs.getString(0);
Log.d("Clid",temp);
if(temp.equals(queryValues.get("clid"))) //checking each id present in db
{
values.put("clid", queryValues.get("clid"));
values.put("lawyer_id", queryValues.get("_id"));
values.put("client_id", queryValues.get("client_id"));
values.put("client_name", queryValues.get("client_name"));
values.put("client_mobile", queryValues.get("client_mobile"));
values.put("client_phone", queryValues.get("client_phone"));
values.put("client_email", queryValues.get("client_email"));
values.put("client_address", queryValues.get("client_address"));
db.update("client_detail", values, null, null);
}
else{
values.put("clid", queryValues.get("clid"));
values.put("lawyer_id", queryValues.get("_id"));
values.put("client_id", queryValues.get("client_id"));
values.put("client_name", queryValues.get("client_name"));
values.put("client_mobile", queryValues.get("client_mobile"));
values.put("client_phone", queryValues.get("client_phone"));
values.put("client_email", queryValues.get("client_email"));
values.put("client_address", queryValues.get("client_address"));
db.insert("client_detail", null, values);
}
}while(cccs.moveToNext());
}
}
I have the following insert statement in my app which work.
Before the insert I want to first check the database if the value name does not exist in the name column.
If it does not exists I want to continue with the insert, else display an error message.
How do I incorporate it into my existing statement below?
public void insert(HashMap<String, String> queryValues){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
Cursor c = database.query("SELECT * FROM user_details where" + "name=?", new String[] {values.put("name") });
if (c.getCount() > 0) {
// don't do it
return;
}
else {
values.put("name", queryValues.get("name"));
values.put("age", queryValues.get("age"));
database.insert("user", null, values);
}
database.close();
}
The correct way to do this is to add a unique constraint on the name field, and then use insertWithOnConflict() with a last argument of CONFLICT_FAIL. That's actually the default behavior. Your insert will fail if it would otherwise cause a constraint violation (insert() will return -1).
If you don't want to do that, there's no magic. Query your DB for a row with the given name field. If you are returned >0 rows, don't perform the insert.
Cursor c = db.query(..., "name=?", new String[] {theName}, ...);
if (c.getCount > 0) {
// don't do it
return;
}
I'm having some trouble saving a string with an accent to my database and retrieving it.
This is my function that saves a new location to the database. It gets 'myId' and 'location' and inserts them. The println there shows the item as I expect, with the accent. The example I'm using is Mazzarrà.
public long createLocationRecord(String location, int myId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_OWMID, myId);
values.put(KEY_NAME, location);
System.out.println("newItem in DB = "+location);
long callSQL = db.insertWithOnConflict(TABLE_LOCATION, null, values, SQLiteDatabase.CONFLICT_IGNORE);
if(callSQL==-1)
db.update(TABLE_LOCATION, values, KEY_OWMID + '=' + owmId, null);
return callSQL;
}
This is my function to retrieve all location items. The println here prints out Mezzarra, without the accented à. Am I missing something? Do I need to make a change to my database? It's just a regular Android SQLite DB that I'm opening via SQLiteBrowser.
public ArrayList<String> getLocationList() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * "
+ "FROM " + TABLE_LOCATION
+ " ORDER BY _id ASC";
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
if (c.moveToFirst()) {
do {
System.out.println("newItem GETTING FROM DB = "+c.getString(c.getColumnIndex(KEY_NAME)));
list.add(c.getString(c.getColumnIndex(KEY_NAME)));
} while (c.moveToNext());
}
c.close();
return list;
}
Thanks for any help anyone can provide.
before Insert the data to Db, Check whether all values are Exist or not..if its exist means no need to insert ...if not exist means insert the values in db.....
sql_db = helper.getWritableDatabase();
Cursor cursor = sql_db.rawQuery(query, null);
cursor = sql_db.rawQuery(query, new String[] { res_namestr[i] , res_eventidstr[i] , get_res_starttime[i], get_res_endtime[i], get_res_location[i] });
int noOfRecords= cursor.getCount();
Log.d("No-of-Records :",""+noOfRecords);
if (noOfRecords> 0)
{
// Toast.makeText(context, "Table Already Exit", Toast.LENGTH_LONG).show();
}
else
{
// record not exist
ContentValues values = new ContentValues();
values.put(DBHelper.E_NAME, res_namestr[i]);
values.put(DBHelper.E_EVENT_ID, res_eventidstr[j]);
values.put(DBHelper.E_STARTTIME, get_res_starttime[int_date]);
values.put(DBHelper.E_ENDTIME, get_res_endtime[int_time]);
values.put(DBHelper.E_LOCATION, get_res_location[int_loc]);
sql_db.insert(DBHelper.TABLE, null, values);
}
}
you can use insertWithOnConflict() method. If record does not exist, it will insert he record and return the id of that and if exist, it will return the id of existing record.
I saved Data in my SQL databank.
Now I want to compare this saved data, with a string
Something like this:
String example = "house";
Now I want to check, if "house" is already in the databank, with a if clause
something like this
if ( example == [SQL Data] ) {
}
else {
}
Now, how can I accomplish this ?
Do something like
String sql = "SELECT * FROM your_table WHERE your_column = '" + example + "'";
Cursor data = database.rawQuery(sql, null);
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
stolen from here
Writing my reply to Sharath's comment as an answer, as the code will be messed up in a comment:
Not saying your reply is wrong, but it's really inefficient to select everything from the table and iterate over it outside the database and it shouldn't be suggested as an answer to the question, because it's a bad habbit to do like that in general.
The way I usually do it, if I want to see if some record is present in the database, I do like this. Not gonna argue about using do-while over a normal while-loop, because that's about different preferences ;)
String query = "SELECT * FROM table_name WHERE column_name=" + the_example_string_to_find;
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
// Do whatever you like with the result.
cursor.moveToNext();
}
}
// Getting Specific Record by name.
// in DB handler class make this function call it by sending search criteria.
Records getRecord(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_Auth_Name, KEY_B_PRICE}, KEY_ID + "=?",
new String[]{name}, null, null, null,null);
if (cursor.getCount() > 0)
cursor.moveToFirst();
Records Records = new Records(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return book
return Records;
}
you need to first fetch all the data from the database and next check the data with what you obtained from the database.
Have a look at the link sample database example
suppose you got a cursor object from the database
cursor = db.rawQuery("SELECT yourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
if(cursor.getString(0).equals(example))
//do something which you want and break
break;
} while (cursor.moveToNext());
}