android sqlite check if inserted new value

泄露秘密 提交于 2020-01-29 06:49:04

问题


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


回答1:


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



回答2:


long result = db.insert(table name, null, contentvalues);
      if(result==-1)
          return false;
           else
          return true;

this is good solution for it..



来源:https://stackoverflow.com/questions/27863609/android-sqlite-check-if-inserted-new-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!