在ORM-Lite Android中存储数据会产生SqlException

时间:2014-02-28 06:50:09

标签: android sqlite android-sqlite sqlexception

请不要错过任何错误,这是我第一次在stackoverflow上

DAO课程

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    // name of the database file for your application -- change to something
    // appropriate for your app
    private static final String DATABASE_NAME = "fieldsense.db";
    // any time you make changes to your database objects, you may have to
    // increase the database version
    private static final int DATABASE_VERSION = 1;

    // the DAO object we use to access the Appointments table
    private Dao<Appointments, Integer> simpleDao = null;
    private RuntimeExceptionDao<Appointments, Integer> simpleRuntimeDao = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION,
                R.raw.ormlite_config);
    }

    /**
     * This is called when the database is first created. Usually you should
     * call createTable statements here to create the tables that will store
     * your data.
     */
    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
        try {
            Log.i(DatabaseHelper.class.getName(), "onCreate");
            TableUtils.createTable(connectionSource, Appointments.class);
            TableUtils.createTable(connectionSource, Time.class);
            TableUtils.createTable(connectionSource, Customer.class);
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
            throw new RuntimeException(e);
        }

        // here we try inserting data in the on-create as a test
        RuntimeExceptionDao<Appointments, Integer> dao = getSimpleDataDao();
        long millis = System.currentTimeMillis();
        // create some entries in the onCreate

        Log.i(DatabaseHelper.class.getName(),
                "created new entries in onCreate: " + millis);
    }

    /**
     * This is called when your application is upgraded and it has a higher
     * version number. This allows you to adjust the various data to match the
     * new version number.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
            int oldVersion, int newVersion) {
        try {
            Log.i(DatabaseHelper.class.getName(), "onUpgrade");
            TableUtils.dropTable(connectionSource, Appointments.class, true);
            // after we drop the old databases, we create the new ones
            onCreate(db, connectionSource);
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns the Database Access Object (DAO) for our Appointments class. It
     * will create it or just give the cached value.
     */
    public Dao<Appointments, Integer> getDao() throws SQLException {
        if (simpleDao == null) {
            simpleDao = getDao(Appointments.class);
        }
        return simpleDao;
    }

    /**
     * Returns the RuntimeExceptionDao (Database Access Object) version of a Dao
     * for our Appointments class. It will create it or just give the cached
     * value. RuntimeExceptionDao only through RuntimeExceptions.
     */
    public RuntimeExceptionDao<Appointments, Integer> getSimpleDataDao() {
        if (simpleRuntimeDao == null) {
            simpleRuntimeDao = getRuntimeExceptionDao(Appointments.class);
        }
        return simpleRuntimeDao;
    }

    /**
     * Close the database connections and clear any cached DAOs.
     */
    @Override
    public void close() {
        super.close();
        simpleDao = null;
        simpleRuntimeDao = null;
    }

约会模型类

package in.qlc.model;

import android.util.Log;

public class Appointments {

    @DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
    private Time appointmentTime;
    @DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
    private Time createdOn;
    @DatabaseField
    private int cretedById;

    public Time getAppointmentTime() {
        return appointmentTime;
    }

    public void setAppointmentTime(Time appointmentTime) {
        this.appointmentTime = appointmentTime;
    }

    public Time getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Time createdOn) {
        this.createdOn = createdOn;
    }

    @DatabaseField(id = true)
    private int id;
    @DatabaseField(foreign = true,foreignAutoCreate = true,foreignAutoRefresh = true)
    private Customer customer;
    @DatabaseField
    private int outcomeId;
    @DatabaseField
    private int purposeId;
    @DatabaseField
    private int userId;

    public int getCretedById() {
        return cretedById;
    }

    public void setCretedById(int cretedById) {
        this.cretedById = cretedById;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getOutcomeId() {
        return outcomeId;
    }

    public void setOutcomeId(int outcomeId) {
        this.outcomeId = outcomeId;
    }

    public int getPurposeId() {
        return purposeId;
    }

    public void setPurposeId(int purposeId) {
        this.purposeId = purposeId;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }    
}

Customer.java

package in.qlc.model;    
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

public class Customer {

    // private Time createdOn;

    public Customer() {

    }

    @Override
    public String toString() {
        return "Customer [customerAddress1=" + customerAddress1
                + ", customerAddress2=" + customerAddress2
                + ", customerAddress3=" + customerAddress3 + ", customerCity="
                + customerCity + ", customerCountry=" + customerCountry
                + ", customerEmail1=" + customerEmail1 + ", customerEmail2="
                + customerEmail2 + ", customerEmail3=" + customerEmail3
                + ", customerFax1=" + customerFax1 + ", customerFax2="
                + customerFax2 + ", customerLocation=" + customerLocation
                + ", customerName=" + customerName + ", customerPhone1="
                + customerPhone1 + ", customerPhone2=" + customerPhone2
                + ", customerPhone3=" + customerPhone3 + ", customerPrintas="
                + customerPrintas + ", customerState=" + customerState
                + ", customerWebsiteUrl1=" + customerWebsiteUrl1
                + ", customerWebsiteUrl2=" + customerWebsiteUrl2
                + ", customerZipcode=" + customerZipcode + ", id=" + id
                + ", industry=" + industry + ", isHeadOffice=" + isHeadOffice
                + ", territory=" + territory + "]";
    }

    @DatabaseField
    private String customerAddress1;
    @DatabaseField
    private String customerAddress2;
    @DatabaseField
    private String customerAddress3;
    @DatabaseField
    private String customerCity;
    @DatabaseField
    private String customerCountry;
    @DatabaseField
    private String customerEmail1;
    @DatabaseField
    private String customerEmail2;
    @DatabaseField
    private String customerEmail3;
    @DatabaseField
    private String customerFax1;
    @DatabaseField
    private String customerFax2;
    @DatabaseField
    private String customerLocation;
    @DatabaseField
    private String customerName;
    @DatabaseField
    private String customerPhone1;
    @DatabaseField
    private String customerPhone2;
    @DatabaseField
    private String customerPhone3;
    @DatabaseField
    private String customerPrintas;
    @DatabaseField
    private String customerState;
    @DatabaseField
    private String customerWebsiteUrl1;
    @DatabaseField
    private String customerWebsiteUrl2;
    @DatabaseField
    private String customerZipcode;
    @DatabaseField(id = true)
    private int id;
    @DatabaseField
    private String industry;
    @DatabaseField
    private boolean isHeadOffice;
    @DatabaseField
    private String territory;

    // public Time getCreatedOn() {
    // return createdOn;
    // }
    //
    // public void setCreatedOn(Time createdOn) {
    // this.createdOn = createdOn;
    // }

    public String getCustomerAddress1() {
        return customerAddress1;
    }

    public void setCustomerAddress1(String customerAddress1) {
        this.customerAddress1 = customerAddress1;
    }

    public String getCustomerAddress2() {
        return customerAddress2;
    }

    public void setCustomerAddress2(String customerAddress2) {
        this.customerAddress2 = customerAddress2;
    }

    public String getCustomerAddress3() {
        return customerAddress3;
    }

    public void setCustomerAddress3(String customerAddress3) {
        this.customerAddress3 = customerAddress3;
    }

    public String getCustomerCity() {
        return customerCity;
    }

    public void setCustomerCity(String customerCity) {
        this.customerCity = customerCity;
    }

    public String getCustomerCountry() {
        return customerCountry;
    }

    public void setCustomerCountry(String customerCountry) {
        this.customerCountry = customerCountry;
    }

    public String getCustomerEmail1() {
        return customerEmail1;
    }

    public void setCustomerEmail1(String customerEmail1) {
        this.customerEmail1 = customerEmail1;
    }

    public String getCustomerEmail2() {
        return customerEmail2;
    }

    public void setCustomerEmail2(String customerEmail2) {
        this.customerEmail2 = customerEmail2;
    }

    public String getCustomerEmail3() {
        return customerEmail3;
    }

    public void setCustomerEmail3(String customerEmail3) {
        this.customerEmail3 = customerEmail3;
    }

    public String getCustomerFax1() {
        return customerFax1;
    }

    public void setCustomerFax1(String customerFax1) {
        this.customerFax1 = customerFax1;
    }

    public String getCustomerFax2() {
        return customerFax2;
    }

    public void setCustomerFax2(String customerFax2) {
        this.customerFax2 = customerFax2;
    }

    public String getCustomerLocation() {
        return customerLocation;
    }

    public void setCustomerLocation(String customerLocation) {
        this.customerLocation = customerLocation;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerPhone1() {
        return customerPhone1;
    }

    public void setCustomerPhone1(String customerPhone1) {
        this.customerPhone1 = customerPhone1;
    }

    public String getCustomerPhone2() {
        return customerPhone2;
    }

    public void setCustomerPhone2(String customerPhone2) {
        this.customerPhone2 = customerPhone2;
    }

    public String getCustomerPhone3() {
        return customerPhone3;
    }

    public void setCustomerPhone3(String customerPhone3) {
        this.customerPhone3 = customerPhone3;
    }

    public String getCustomerPrintas() {
        return customerPrintas;
    }

    public void setCustomerPrintas(String customerPrintas) {
        this.customerPrintas = customerPrintas;
    }

    public String getCustomerState() {
        return customerState;
    }

    public void setCustomerState(String customerState) {
        this.customerState = customerState;
    }

    public String getCustomerWebsiteUrl1() {
        return customerWebsiteUrl1;
    }

    public void setCustomerWebsiteUrl1(String customerWebsiteUrl1) {
        this.customerWebsiteUrl1 = customerWebsiteUrl1;
    }

    public String getCustomerWebsiteUrl2() {
        return customerWebsiteUrl2;
    }

    public void setCustomerWebsiteUrl2(String customerWebsiteUrl2) {
        this.customerWebsiteUrl2 = customerWebsiteUrl2;
    }

    public String getCustomerZipcode() {
        return customerZipcode;
    }

    public void setCustomerZipcode(String customerZipcode) {
        this.customerZipcode = customerZipcode;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getIndustry() {
        return industry;
    }

    public void setIndustry(String industry) {
        this.industry = industry;
    }

    public boolean isHeadOffice() {
        return isHeadOffice;
    }

    public void setHeadOffice(boolean isHeadOffice) {
        this.isHeadOffice = isHeadOffice;
    }

    public String getTerritory() {
        return territory;
    }

    public void setTerritory(String territory) {
        this.territory = territory;
    }
}

Time.java

public class Time {

    @Override
    public String toString() {
        return "Time [date=" + date + ", day=" + day + ", hours=" + hours
                + ", minutes=" + minutes + ", month=" + month + ", nanos="
                + nanos + ", seconds=" + seconds + ", time=" + time
                + ", timezoneOffset=" + timezoneOffset + ", year=" + year
                + ", dbid=" + dbid + "]";
    }

    public Time() {
    }

    @DatabaseField
    private int date;
    @DatabaseField
    private int day;
    @DatabaseField
    private int hours;
    @DatabaseField
    private int minutes;
    @DatabaseField
    private int month;
    @DatabaseField
    private int nanos;
    @DatabaseField
    private int seconds;
    @DatabaseField
    private long time;
    @DatabaseField
    private int timezoneOffset;
    @DatabaseField
    private int year;

    @DatabaseField(id = true)
    private int dbid;

    public int getId() {
        return dbid;
    }

    public void setId(int id) {
        this.dbid = id;
    }

    public int getDate() {
        return date;
    }

    public void setDate(int date) {
        this.date = date;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getHours() {
        return hours;
    }

    public void setHours(int hours) {
        this.hours = hours;
    }

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getNanos() {
        return nanos;
    }

    public void setNanos(int nanos) {
        this.nanos = nanos;
    }

    public int getSeconds() {
        return seconds;
    }

    public void setSeconds(int seconds) {
        this.seconds = seconds;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public int getTimezoneOffset() {
        return timezoneOffset;
    }

    public void setTimezoneOffset(int timezoneOffset) {
        this.timezoneOffset = timezoneOffset;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

}

要拨打的主要代码

 private void doSampleDatabaseStuff(List<Appointments> appoint) {
        // get our dao
        RuntimeExceptionDao<Appointments, Integer> appointDao = getHelper()
                .getSimpleDataDao();



        for (Iterator iterator = appoint.iterator(); iterator.hasNext();) {
            Appointments appointments = (Appointments) iterator.next();
            int create = appointDao.create(appointments);
            Log.e(TAG," create "+ create);
        }

错误

02-28 12:09:29.656: E/AndroidRuntime(27931): java.lang.RuntimeException: java.sql.SQLException: Unable to run insert stmt on object in.qlc.model.Appointments@406fff00: INSERT INTO `appointments` (`appointmentTime_id` ,`createdOn_id` ,`cretedById` ,`id` ,`customer_id` ,`outcomeId` ,`purposeId` ,`userId` ) VALUES (?,?,?,?,?,?,?,?)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.dao.RuntimeExceptionDao.create(RuntimeExceptionDao.java:228)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at in.qlc.fragments.SlideUpFragment.doSampleDatabaseStuff(SlideUpFragment.java:256)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at in.qlc.fragments.SlideUpFragment.access$0(SlideUpFragment.java:247)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at in.qlc.fragments.SlideUpFragment$GetTask.onPostExecute(SlideUpFragment.java:225)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at in.qlc.fragments.SlideUpFragment$GetTask.onPostExecute(SlideUpFragment.java:1)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.os.AsyncTask.finish(AsyncTask.java:417)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.os.AsyncTask.access$300(AsyncTask.java:127)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.os.Looper.loop(Looper.java:150)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.app.ActivityThread.main(ActivityThread.java:4277)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at java.lang.reflect.Method.invokeNative(Native Method)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at java.lang.reflect.Method.invoke(Method.java:507)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at dalvik.system.NativeStart.main(Native Method)
02-28 12:09:29.656: E/AndroidRuntime(27931): Caused by: java.sql.SQLException: Unable to run insert stmt on object in.qlc.model.Appointments@406fff00: INSERT INTO `appointments` (`appointmentTime_id` ,`createdOn_id` ,`cretedById` ,`id` ,`customer_id` ,`outcomeId` ,`purposeId` ,`userId` ) VALUES (?,?,?,?,?,?,?,?)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.stmt.mapped.MappedCreate.insert(MappedCreate.java:124)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.stmt.StatementExecutor.create(StatementExecutor.java:394)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.dao.BaseDaoImpl.create(BaseDaoImpl.java:308)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.dao.RuntimeExceptionDao.create(RuntimeExceptionDao.java:225)
02-28 12:09:29.656: E/AndroidRuntime(27931):    ... 15 more
02-28 12:09:29.656: E/AndroidRuntime(27931): Caused by: java.sql.SQLException: Unable to run insert stmt on object Time [date=26, day=3, hours=5, minutes=30, month=1, nanos=0, seconds=0, time=1393372800000, timezoneOffset=-330, year=114, dbid=0]: INSERT INTO `time` (`date` ,`day` ,`hours` ,`minutes` ,`month` ,`nanos` ,`seconds` ,`time` ,`timezoneOffset` ,`year` ,`dbid` ) VALUES (?,?,?,?,?,?,?,?,?,?,?)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.stmt.mapped.MappedCreate.insert(MappedCreate.java:124)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.stmt.StatementExecutor.create(StatementExecutor.java:394)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.dao.BaseDaoImpl.create(BaseDaoImpl.java:308)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.field.FieldType.createWithForeignDao(FieldType.java:916)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.stmt.mapped.MappedCreate.insert(MappedCreate.java:74)
02-28 12:09:29.656: E/AndroidRuntime(27931):    ... 18 more
02-28 12:09:29.656: E/AndroidRuntime(27931): Caused by: java.sql.SQLException: inserting to database failed: INSERT INTO `time` (`date` ,`day` ,`hours` ,`minutes` ,`month` ,`nanos` ,`seconds` ,`time` ,`timezoneOffset` ,`year` ,`dbid` ) VALUES (?,?,?,?,?,?,?,?,?,?,?)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.android.AndroidDatabaseConnection.insert(AndroidDatabaseConnection.java:152)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.stmt.mapped.MappedCreate.insert(MappedCreate.java:89)
02-28 12:09:29.656: E/AndroidRuntime(27931):    ... 22 more
02-28 12:09:29.656: E/AndroidRuntime(27931): Caused by: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:88)
02-28 12:09:29.656: E/AndroidRuntime(27931):    at com.j256.ormlite.android.AndroidDatabaseConnection.insert(AndroidDatabaseConnection.java:140)
02-28 12:09:29.656: E/AndroidRuntime(27931):    ... 23 more


This was the create stament tha  i got in the logs

02-28 12:29:54.131: I/in.qlc.fieldsense.database.DatabaseHelper(3593): onCreate
02-28 12:29:54.151: I/TableUtils(3593): creating table 'appointments'
02-28 12:29:54.181: I/TableUtils(3593): executed create table statement changed 1 rows: CREATE TABLE `appointments` (`appointmentTime_id` INTEGER , `createdOn_id` INTEGER , `cretedById` INTEGER , `id` INTEGER , `customer_id` INTEGER , `outcomeId` INTEGER , `purposeId` INTEGER , `userId` INTEGER , PRIMARY KEY (`id`) ) 
02-28 12:29:54.201: I/TableUtils(3593): creating table 'time'
02-28 12:29:54.201: I/TableUtils(3593): executed create table statement changed 1 rows: CREATE TABLE `time` (`date` INTEGER , `day` INTEGER , `hours` INTEGER , `minutes` INTEGER , `month` INTEGER , `nanos` INTEGER , `seconds` INTEGER , `time` BIGINT , `timezoneOffset` INTEGER , `year` INTEGER , `dbid` INTEGER , PRIMARY KEY (`dbid`) ) 
02-28 12:29:54.211: I/TableUtils(3593): creating table 'customer'
02-28 12:29:54.231: I/TableUtils(3593): executed create table statement changed 1 rows: CREATE TABLE `customer` (`customerAddress1` VARCHAR , `customerAddress2` VARCHAR , `customerAddress3` VARCHAR , `customerCity` VARCHAR , `customerCountry` VARCHAR , `customerEmail1` VARCHAR , `customerEmail2` VARCHAR , `customerEmail3` VARCHAR , `customerFax1` VARCHAR , `customerFax2` VARCHAR , `customerLocation` VARCHAR , `customerName` VARCHAR , `customerPhone1` VARCHAR , `customerPhone2` VARCHAR , `customerPhone3` VARCHAR , `customerPrintas` VARCHAR , `customerState` VARCHAR , `customerWebsiteUrl1` VARCHAR , `customerWebsiteUrl2` VARCHAR , `customerZipcode` VARCHAR , `id` INTEGER , `industry` VARCHAR , `isHeadOffice` SMALLINT , `territory` VARCHAR , PRIMARY KEY (`id`) ) 
02-28 12:29:54.231: I/in.qlc.fieldsense.database.DatabaseHelper(3593): created new entries in onCreate: 1393570794244

1 个答案:

答案 0 :(得分:0)

我使用ORMLite来存储和检索数据库中的数据

&#13;
&#13;
 

 I have used ORMLite for storing and retrieveing data from and to database in android below or some simple steps to insert user detail into database through ORM


(1)first we need library for ormlite we can download lib or use dependency in gradle like
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')  
    compile group: 'com.j256.ormlite', name: 'ormlite-android', version: '4.45'
}


(2) we need to create pojo class User

    public class User {

    @DatabaseField(unique = true,dataType = DataType.STRING)
    String email;
    @DatabaseField(canBeNull = false,dataType = DataType.STRING)
    String pwd; 
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}  


(3)We need to create helper class to manage database creation and version management


    public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	private static final String DATABASE_NAME = "databasename.db";
	private static final int DATABASE_VERSION = 1;
	private Dao<User, Integer> dao = null;
	private RuntimeExceptionDao<User, Integer> runtimeDao = null;
	static  DatabaseHelper databaseHelper;
	public static synchronized DatabaseHelper getInstance(Context context){
		if(databaseHelper== null){
			databaseHelper= new DatabaseHelper(context);
		}
		return databaseHelper;
	}
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	/**
	 * This is called when the database is first created. Usually you should call createTable statements here to create
	 * the tables that will store your data.
	 */
	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, User.class);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
	}

	/**
	 * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
	 * the various data to match the new version number.
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {

	}

	/**
	 * Returns the Database Access Object (DAO) for our User class. It will create it or just give the cached
	 * value.
	 */
	public synchronized Dao<User, Integer> getDAO() throws SQLException {
		if (dao == null) {
			dao = getDao(User.class);
		}
		return dao;
	}
	
	/**
	 * Returns the RuntimeExceptionDao (Database Access Object) version of a Dao for our User  class. It will
	 * create it or just give the cached value. RuntimeExceptionDao only through RuntimeExceptions.
	 */
	public synchronized RuntimeExceptionDao<User, Integer> getRuntimeDao() {

		if (runtimeDao == null) {
			runtimeDao = getRuntimeExceptionDao(User.class);
		}
		return runtimeDao;
	}



(4) we can insert user into table through DatabaseHelper class from activity or fragment wherever you want

    User user = new User();
    user.setEmail("xyz@gmail.com");
    user.setPwd("1234");



 //this below will insert user into table
   

     public boolean insertUserIntoTable(User user){
        int rowaffected = 0;
        try {
            RuntimeExceptionDao<User, Integer> dao = DatabaseHelper.getInstance(context);
.getRuntimeDao();
            long millis = System.currentTimeMillis();
            rowaffected = dao.create(user);         
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
        return (rowaffected == 0) ? false : true;
 }

 

//this will get user from database

    public User getUser(String email,String pwd){

        User user = null;

        QueryBuilder<User, Integer> qb = null;
        try {
            qb =  DatabaseHelper.getInstance(context).getDAO().queryBuilder();
            qb.where().eq("email",email).and().eq("pwd",pwd);
            user = qb.queryForFirst();

        } catch (SQLException e) {

            e.printStackTrace();

        }finally {

        }
        return user;
    }



  //this will update the user in database
 

      public boolean updateUser(User user){
        try {

            Dao<User, Integer> dao = databaseHelper.getDAO();
            UpdateBuilder<User, Integer> updateBuilder = dao.updateBuilder();
            
            updateBuilder.updateColumnValue("email", user.getEmail());
            updateBuilder.updateColumnValue("pwd", user.getPwd());
            updateBuilder.where().eq("email", user.getEmail());
            int row = dao.update(updateBuilder.prepare());

            if(row == 0)
                return false;
            else
                return true;

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
        }
        return false;
    }
&#13;
&#13;
&#13;