android sqlite check if inserted new value - android

I'm working with sqlite. I successfully created database and table. I also wrote code which can insert new values in my table. My code is working perfect, but now I want to show for example: toast message if inserted new value, else show error message in toast or something else.
This is a my insert to table source code:
public void InsertToPhysicalPersonTable(String FirstName, String LastName,
String FullName, String FatherName) {
try {
ContentValues newValues = new ContentValues();
newValues.put("FirstName", FirstName);
newValues.put("LastName", LastName);
newValues.put("FullName", FullName);
newValues.put("FatherName", FatherName);
db.insert(AddNewPhysicalPerson, null, newValues);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
}
}
I called my function like this:
loginDataBaseAdapter.InsertToPhysicalPersonTable("FirstName",
"LastName",
"FullName",
"FatherName"
);
If anyone knows the solution, please help me.
Thanks

insert() method returns the row ID of the newly inserted row, or -1 if an error occurred.
Change
db.insert(AddNewPhysicalPerson, null, newValues);
like this
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added, row id: " + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();

long result = db.insert(table name, null, contentvalues);
if(result==-1)
return false;
else
return true;
this is good solution for it..

here is another way:-
I don't know if I am too late for your project but have you thought of .lastrowid?
Here is an example of what I did last_rec=self.cursor.lastrowid so lastrec would have the number of the last row inserted.
Here is the info from sqlite.org
Hope it helps, you , or anyone else who wonders about this.
Kind regards and all the best :¬)
joe

Related

How to put validation to check whether it has data or not? android studio with sqlite

I'm wondering how to put validation to check if there is "database column1" then whatever I type and save. It will turn to 'Update' instead of creating a new "Column2".
Here is the code
sB_Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SettingModel txn = new SettingModel(); // initialize your model class first
txn.setH1(h1.getText().toString());
txn.setH2(h2.getText().toString());
txn.setH3(h3.getText().toString());
txn.setH4(h4.getText().toString());
txn.setPerson_Charge(Person_Charge.getText().toString());
txn.setUnit_Code(unit_Code.getText().toString());
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("header1", txn.getH1()); // get the entered name here.
cv.put("header2", txn.getH2());
cv.put("header3", txn.getH3());
cv.put("header4", txn.getH4());
cv.put("unitcode", txn.getUnit_Code());
cv.put("personInCharge", txn.getPerson_Charge());
db.insert("Information", null, cv);
db.close();
Toast.makeText(Setting_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It needs 'if statement' , But I don't know how to put validation to check... Please Help. Thanks in advance
You could use the following.
public void onClick(View v) {
SettingModel txn = new SettingModel(); // initialize your model class first
txn.setH1(h1.getText().toString());
txn.setH2(h2.getText().toString());
txn.setH3(h3.getText().toString());
txn.setH4(h4.getText().toString());
txn.setPerson_Charge(Person_Charge.getText().toString());
txn.setUnit_Code(unit_Code.getText().toString());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor csr = db.query("Information",null,null,null,null,null,null);
int rowcount = csr.getCount();
csr.close();
ContentValues cv = new ContentValues();
cv.put("header1", txn.getH1()); // get the entered name here.
cv.put("header2", txn.getH2());
cv.put("header3", txn.getH3());
cv.put("header4", txn.getH4());
cv.put("unitcode", txn.getUnit_Code());
cv.put("personInCharge", txn.getPerson_Charge());
if (rowcount == 0) {
db.insert("Information", null, cv);
Toast.makeText(Setting_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} else {
db.update("Information",cv,null,null);
Toast.makeText(Setting_Page.this, "Updated successfully", Toast.LENGTH_SHORT).show();
}
db.close();
}
Note the above is in-principle code and hasn't been tested so may contain errors.
An alternative method (perhaps some would say the correct method) would be to create a UNIQUE (index) constraint on a column or columns and then use the insertWithonConflict with CONFLICT_REPLACE (this is the equivalent of the SQL INSERT OR REPLACE .......).

How to check data in SQLite if already exist update or else insert in android

I want to check the data in SQLite if already exist can update or else insert.I am checking code like this what i mentioned below.
Code:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
My activity:
I converted whole json data into string object then insert into SQLite.
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
But It doesn't work.It couldn't insert into sqlite.
Anyone solve this problem Glad to appreciate.
Thanks in advance
You can user insertWithOnConflict() like this
db.insertWithOnConflict(TABLE, null, yourContentValues, SQLiteDatabase.CONFLICT_REPLACE);
You can use refer this Link. That link explains how to find the email address available in a table or not, you can change the column name, table and pass the values according. In your scenario you want to check the whether the name exists already or not, so you must pass which name you want to find. If the name is there then this method will return true or false. You can validate whether you had to insert or update according the response.i.e., false means you had to insert, otherwise if it is true means then you had to update.
you should use replace into
REPLACE INTO table(...) VALUES(...);
Question is not much clear but, i think you want to check either data/record is inserted in SQLite or not. you will need to define some extra variable long rowInserted insert() method returns the row ID of the newly inserted row, or -1 when an error occurred.
menus.insert(TABLE_NAME, null, values);
long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
Toast.makeText(myContext, "New row added :" + rowInserted, Toast.LENGTH_SHORT).show();
else
Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
Updated
check either data is in table or column? for this you use this code
public boolean Exists(String id){
Cursor res = getAllData();
int count=0;
while (res.moveToNext()){
String email =res.getString(3);
if(email.equals(id)){
count++;
}
}
if(count==0){
return false;
} else{
return true;
}
}
Second you asking about json first store all data in any List run time and get string from it then you are able to store in SQlite
try {
items = jsonObject.getJSONArray("myjsonattribute");
List<MyAnySetterGetter> mList = new ArrayList<MyAnySetterGetter>();
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String mfilename = c.getString("myjsonattribute2");
mList.add(mfilename);
}
} catch (JSONException e) {
//e.printStackTrace();
}
then use above list to insert data from list to SQLite
like
String str1 = mList.get(position).getMYITEM1();
String str2 = mList.get(position).getMYITEM2();
insert str1 and str2 in SQLite hope you will get idea.
you should
set key for the table, then
insert(if the key existed it will not insert anymore), then
update all row.

Show error if data cannot be inserted

I need to handle an error when non-unique data is inserted into the database. I have this code:
try {
handler.addBookmark(new BookmarkModel(idBrand, brand, desc, types, detail, image));
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
}catch (SQLiteException e){
e.printStackTrace();
Toast.makeText(this, "Failed", Toast.LENGTH_LONG).show();
}
I insert like this:
public long addBookmark(BookmarkModel bookmark) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, bookmark._id); // Must Unique
values.put(KEY_BRAND, bookmark.brandName);
values.put(KEY_DESC, bookmark.descTerm);
values.put(KEY_TYPE, bookmark.type);
values.put(KEY_DETAIL, bookmark.detail);
values.put(KEY_IMAGE, bookmark.image);
return db.insert(TABLE_BOOKMARK, null, values);
//db.close();
}
Logcat of the error that occurs:
android.database.sqlite.SQLiteConstraintException: column id is not unique (code 19)
The data was not inserted, but I was unable to show the error message. How can I show the toast to let the user know the insert failed?
Do not set _id yourself. This line should be gone:
values.put(KEY_ID, bookmark._id); // Must Unique
If your table schema sets it up correctly (_id INTEGER PRIMARY KEY) then this is auto incremented long value. Nothing you should touch on insert.
You should look into the insertOrThrow() method which will throw an SQLiteConstraintException if this occurs.
Then, you can put your insert into a try/catch block:
try{
db.insertOrThrow(table, columnHack, values);
} catch (SQLiteConstraintException e){
Toast.makeText(context, "Unable to insert values.", Toast.LENGTH_SHORT).show();
}
I got a solution. just set an id to PRIMARY KEY AUTOINCREMENT and set 1 text UNIQUE . for methode that handle an error, i use insertOrThrow and use it with try-catch .

Avoid sqliteAssetHelper to log error

Hi guys i'have problem with this little block of code
// Insert a new contact in database
public void insertInSignature(String TITLE_SI) {
try {
// Open Android Database
db = databaseHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("TITLE_SI", TITLE_SI);
db.insert("DELIVERY_SLIP", null, initialValues);
} catch (SQLException sqle) {
Log.e(TAG, "insertUser Error");
Log.e(TAG, "Exception : " + sqle);
} finally {
// Close Android Database
databaseHelper.close();
}
}
I have unique constraint on my table "DELIVERY_SLIP
So , when i'm trying to insert some row which already exist , it return some error like "Oh shit , you're inserting the same , i'm sorry men , i can't do it"
http://cdn.imghack.se/images/3b51afd07d1f1a8bd021c9e9dfc57e98.png
Here my log
It's this line
databaseHelper.close();
When database helper close , this return the log.
I just want to avoid to log it, I already tested with a tryCatch on sqliteConstraintException
But, nothing worked.
Thanks by advance
Instead of insert(), use insertWithOnConflict() with some conflict resolution algorithm appropriate for your use, such as SQLiteDatabase.CONFLICT_IGNORE.

Execute my update query in sqllite with case statement

I am working in an android application and I am using sqllite in my application. I want to update my sql with a query that contains case statement. Please suggest me a correct solution to execute this query and return me an int value to confirm if the table is updated successfully.
My query ::
UPDATE TblAgencies SET Selected= CASE WHEN ID=6 THEN 1 ELSE 0 END
update TblAgencies set Selected = (ID == 6); will do this.
As to "did the update work correctly" -- that's standard API work, nothing to do with the query itself.
I wont do the programming for you but here how you do it.
int res = db.update(table, values, whereClause, whereArgs);
if(res>0) etc...
try
{
database=openOrCreateDatabase("solutiondb", MODE_PRIVATE, null);
database.execSQL("update patientdetails set name='"+naMe+"',dob='"+DOB+"',gender='"+genDer+"',height="+heiGht+",weight="+weiGht+",bmi="+BMI+",bloodgroup='"+bloodGroup+"',profession='"+proFession+"',address='"+addRess+"',contact="+contactNumber+",smoking='"+smoKing+"',drinking='"+drinKing+"',maritalstatus='"+maritalStatus+"',physician='"+phySican+"' where id="+patientId+"");
Toast.makeText(PersonalInformationActivity.this, "Your Personal Details Are Saved Successfully", Toast.LENGTH_LONG).show();
dialog.dismiss();
intent=new Intent(PersonalInformationActivity.this, PersoxcsdActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
database.close();
}
catch(SQLException exception)
{
}

Categories

Resources