Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android sqlite check if inserted new value

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

like image 824
chromelend Avatar asked Jan 09 '15 15:01

chromelend


People also ask

How can we check data is inserted or not in SQLite android?

How to check whether the value is inserted or not in Android? if inserted==true return true; else return false; This is my code: SQLiteDatabase db = this.

How do you check if data exists in a table SQLite?

Use this code: SELECT name FROM sqlite_master WHERE type='table' AND name='yourTableName'; If the returned array count is equal to 1 it means the table exists. Otherwise it does not exist.

Why use SQLite in android?

SQLite is an open-source relational database i.e. used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database. It is embedded in android bydefault. So, there is no need to perform any database setup or administration task.


2 Answers

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();
like image 165
Rohit5k2 Avatar answered Sep 18 '22 12:09

Rohit5k2


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

this is good solution for it..

like image 42
rs11 Avatar answered Sep 21 '22 12:09

rs11