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());
}
}
Related
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();
}
Im using the following code to add values to db.
public void addComplianceAcceptability(ComplianceAcceptability complianceAcceptability) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, complianceAcceptability.getId());
contentValues.put(KEY_COUNTRY_ID, complianceAcceptability.getCountryId());
contentValues.put(KEY_DOMAIN_ID, complianceAcceptability.getDomainId());
contentValues.put(KEY_UNIT_ID, complianceAcceptability.getUnitId());
contentValues.put(KEY_COMPLIANCE_ID, complianceAcceptability.getComplianceId());
contentValues.put(KEY_COMPLIANCE_NAME, complianceAcceptability.getCompliancenName());
contentValues.put(KEY_COMPLIANCE_FREQUENCY, complianceAcceptability.getComplianceFrequency());
contentValues.put(KEY_COMPLIANCE_APPLICABLE, complianceAcceptability.getComplianceApplicable());
contentValues.put(KEY_COMPLIANCE_OPTED, complianceAcceptability.getComplianceOpted());
sqLiteDatabase.insert(TABLE_COMPLIANCE_ACCEPTABILITY, null, contentValues);
sqLiteDatabase.close();
}
Imm trying to access the values using the following code,
public List<ComplianceAcceptability> getAllAcceptability() {
List<ComplianceAcceptability> complianceAcceptabilityList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_COMPLIANCE_ACCEPTABILITY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
ComplianceAcceptability complianceAcceptability = new ComplianceAcceptability();
complianceAcceptability.setId(Integer.parseInt(cursor.getString(0)));
complianceAcceptability.setCountryId(cursor.getString(1));
complianceAcceptability.setDomainId(cursor.getString(2));
complianceAcceptability.setUnitId(cursor.getString(3));
complianceAcceptability.setComplianceId(cursor.getString(4));
complianceAcceptability.setCompliancenName(cursor.getString(5));
complianceAcceptability.setComplianceFrequency(cursor.getString(6));
complianceAcceptability.setComplianceApplicable(cursor.getString(7));
complianceAcceptability.setComplianceOpted(cursor.getString(8));
} while (cursor.moveToNext());
}
return complianceAcceptabilityList;
}
The problem is that it returns an empty array. But when I try to print the contentValues within addComplianceStatus, it of course prints the array of all values.
You never add anything to complianceAcceptabilityList. You just assign it once, then do nothing to it before returning it. Maybe you want to add complianceAcceptability into it at each iteration through the cursor?
Here you are not adding the complianceAcceptability object to the complianceAcceptabilityList, your modified code:
if (cursor.moveToFirst()) {
do {
ComplianceAcceptability complianceAcceptability = new ComplianceAcceptability();
complianceAcceptability.setId(Integer.parseInt(cursor.getString(0)));
complianceAcceptability.setCountryId(cursor.getString(1));
complianceAcceptability.setDomainId(cursor.getString(2));
complianceAcceptability.setUnitId(cursor.getString(3));
complianceAcceptability.setComplianceId(cursor.getString(4));
complianceAcceptability.setCompliancenName(cursor.getString(5));
complianceAcceptability.setComplianceFrequency(cursor.getString(6));
complianceAcceptability.setComplianceApplicable(cursor.getString(7));
complianceAcceptability.setComplianceOpted(cursor.getString(8));
complianceAcceptabilityList.add(complianceAcceptability);
} while (cursor.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.
How do you check to see if a Record (ContentValues) already exists in the Database?
public void insertData(String ActId,String Dstcode,String Mandicode,String Traderlicno,String licenseId,String licensename,String Gatepassno,String FarmerId,String Farmername,String FarmerFatherName,String CommodityGrpCode,String CommodityCode,String VartyCode,String Cwght,String UntCode,String FnlPrice,String lgndate,String Ip,String dte,String IEMIN0,String ModelNo,String BoardName,String BrandName,String SIMNo)
{
ContentValues cv = new ContentValues();
cv.put(DatabaseHandler.AUCTIONINFO_ActId, ActId);
cv.put(DatabaseHandler.AUCTIONINFO_Dstcode, Dstcode);
cv.put(DatabaseHandler.AUCTIONINFO_Mandicode, Mandicode);
cv.put(DatabaseHandler.AUCTIONINFO_Traderlicno, Traderlicno);
cv.put(DatabaseHandler.AUCTIONINFO_licenseId, licenseId);
cv.put(DatabaseHandler.AUCTIONINFO_licensename, licensename);
cv.put(DatabaseHandler.AUCTIONINFO_Gatepassno, Gatepassno);
cv.put(DatabaseHandler.AUCTIONINFO_FarmerId, FarmerId);
cv.put(DatabaseHandler.AUCTIONINFO_Farmername, Farmername);
cv.put(DatabaseHandler.AUCTIONINFO_FarmerFatherName, FarmerFatherName);
cv.put(DatabaseHandler.AUCTIONINFO_CommodityGrpCode, CommodityGrpCode);
cv.put(DatabaseHandler.AUCTIONINFO_CommodityCode, CommodityCode);
cv.put(DatabaseHandler.AUCTIONINFO_VartyCode, VartyCode);
cv.put(DatabaseHandler.AUCTIONINFO_Cwght, Cwght);
cv.put(DatabaseHandler.AUCTIONINFO_UntCode, UntCode);
cv.put(DatabaseHandler.AUCTIONINFO_FnlPrice, FnlPrice);
cv.put(DatabaseHandler.AUCTIONINFO_lgndate, lgndate);
cv.put(DatabaseHandler.AUCTIONINFO_Ip, Ip);
cv.put(DatabaseHandler.AUCTIONINFO_dte, dte);
cv.put(DatabaseHandler.AUCTIONINFO_IEMIN0, IEMIN0);
cv.put(DatabaseHandler.AUCTIONINFO_ModelNo, ModelNo);
cv.put(DatabaseHandler.AUCTIONINFO_BoardName, BoardName);
cv.put(DatabaseHandler.AUCTIONINFO_BrandName, BrandName);
cv.put(DatabaseHandler.AUCTIONINFO_SIMNo, SIMNo);
database.insert(DatabaseHandler.TABLE_AUCTIONINFO, null, cv);
}
Edit:
myDB= openOrCreateDatabase("DBName", MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS MyTable (your query goes here);");
Cursor cursor = myDB.rawQuery("select AUCTIONINFO_ActId from TABLE_AUCTIONINFO where AUCTIONINFO_licenseId = licenseId;", null);
if(cursor.getCount()!=0)
{
// now you can insert the record
}
else
{
}