inserting value into database sqlite not working - android

Hi i have issue with database SQLITE android
please check my code for reference
when i am going to insert values it returns -1 that i come to know from debug
which is not inserting values so tell me what is wrong
i am inserting value from list view.
public void add_device(String data,
ArrayList<HashMap<String, String>> jsonlist) {
try {
SQLiteDatabase db = this.getReadableDatabase();
// database = this.getWritableDatabase();
for (HashMap<String, String> map : jsonlist) {
ContentValues values = new ContentValues();
values.put(SAVE_COLUMN_NAME, data);
values.put(SAVE_COLUMN_KEY, map.get(SAVE_COLUMN_KEY));
values.put(SAVE_COLUMN_VALUE, map.get(SAVE_COLUMN_VALUE));
#SuppressWarnings("unused")
Long int1 = db.insert(SAVE_TABLE_NAME, null, values);
Log.i("insserted value ", int1 + "");
}
}
/*
* for(HashMap<String, String> map : mylist){ ContentValues cv = new
* ContentValues(); cv.put(FILE_NAME, map.get(FILE_NAME)); cv.put(DESC,
* map.get(DESC)); cv.put(UPLOADED_BY, map.get(DATE_UPLOADED));
* cv.put(ACTION, map.get(FILE_NAME)); cv.put(ID, map.get(ID));
* cv.put(FILE_URI, map.get(FILE_URI)); db.insert("tablename", null,
* cv); }
*/
catch (Exception e) {
// TODO: handle exception
}
}
thanks in advance

I am guessing that the "-1" value is coming from your Log.i(...) message, so the -1 is the return value of the db.insert(...) call. The -1 indicates an error occurred.
Instead of using insert, user insertOrThrow(...) and look at the exception for clues as to why there is a problem.

-1 is returned when you are inserting the records.
This can be due to violation of table properties (like conflict between type of data you are inserting and the type of column in table ,is "key" and "Value" column in table are of string type) also there can be several other reasons for this like you may be missing any table column value in insert operation or value of 'SAVE_COLUMN_NAME','SAVE_COLUMN_KEY','SAVE_COLUMN_VALUE' doesn't matches with respective column names in table .
[while running app open separate command prompt and write adb logcat ) and show the result here (specifically when you try to insert the record) so that we have more information related to issue]
[EDIT]
OK so i think i have found the problem
SQLiteDatabase db = this.getReadableDatabase();
and you are inserting statement
Long int1 = db.insert(SAVE_TABLE_NAME, null, values);
INSERT SHOULD BE DONE USING WRITABLE DATABASE NOT READABLE DATABASE.
Here SQLiteDatabase db is a Readable Database it should be a Writable database
change
SQLiteDatabase db = this.getReadableDatabase();
to
SQLiteDatabase db = this.getWritableDatabase();

I have made changes like
public void add_device(String data,ArrayList<HashMap<String, String>> jsonlist) {
try {
database = this.getWritableDatabase();
for (HashMap<String, String> map : jsonlist) {
ContentValues values = new ContentValues();
values.put(SAVE_COLUMN_NAME, data);
values.put(SAVE_COLUMN_KEY, map.get(SAVE_COLUMN_KEY));
values.put(SAVE_COLUMN_VALUE, map.get(SAVE_COLUMN_VALUE));
Long int1 = database.insertOrThrow(SAVE_TABLE_NAME, null,
values);
Log.i("insserted value ", int1 + "");
}
}
/*
* for(HashMap<String, String> map : mylist){ ContentValues cv = new
* ContentValues(); cv.put(FILE_NAME, map.get(FILE_NAME)); cv.put(DESC,
* map.get(DESC)); cv.put(UPLOADED_BY, map.get(DATE_UPLOADED));
* cv.put(ACTION, map.get(FILE_NAME)); cv.put(ID, map.get(ID));
* cv.put(FILE_URI, map.get(FILE_URI)); db.insert("tablename", null,
* cv); }
*/
catch (Exception e) {
}
}

Related

How to Insert and update in sqlite android

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

Why returning values from sqlite returns an empty array

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

Queries in SQLite

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

How to keep the database updated when the user enters new values in android studio?

I'm dealing with a simple app, which basically stores various dates. But when I enter a new date, I have to close the app and open it again. The same thing counts for changing the date values. I can only see the changes by closing the app and reopening it.
Here are the two main functions in my DB class;
public void addBirthday(Person person){ //Add a data to database
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(column_name, person.getName());
cv.put(column_sname, person.getSname());
cv.put(column_day, person.getDay());
cv.put(column_month, person.getMonth());
cv.put(column_year, person.getYear());
db.insert(TABLE_NAME, null, cv);
db.close();
}
public int updateBirthday(Person person) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues cv = new ContentValues();
cv.put(column_name, person.getName());
cv.put(column_sname, person.getSname());
cv.put(column_day, person.getDay());
cv.put(column_month, person.getMonth());
cv.put(column_year, person.getYear());
// 3. updating row
int i = db.update(TABLE_NAME, //table
cv, // column/value
column_id +" = ?", // selections
new String[] { String.valueOf(person.getId()) }); //selection args
// 4. close
db.close();
return i;
}
You will need to refresh the view (probably a ListView) where you display this data.
Get rid of the notifyDataSetChanged() and call requery() on your Cursor

Saving and retrieving accented characters to mysql database

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.

Categories

Resources