Android sqlite check if a new value is inserted

I am working with sqlite. I have successfully created the database and table. I also wrote code that can insert new values ​​into my table. My code works fine, but now I want to show, for example: a toast message, if a new value is inserted, otherwise show an error message in the toast or something else. This is my insert in the source code of the table:

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 as follows:

 loginDataBaseAdapter.InsertToPhysicalPersonTable("FirstName", "LastName", "FullName", "FatherName" ); 

If anyone knows a solution, please help me. Thanks

+6
source share
2 answers

insert() method returns the row identifier of the row just inserted, or -1 if an error occurred.

Edit

 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(); 
+26
source
 long result = db.insert(table name, null, contentvalues); if(result==-1) return false; else return true; 

This is a good solution for him.

+2
source

Source: https://habr.com/ru/post/980769/


All Articles