Click here to Skip to main content
15,889,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in the following code i want to use the rollno is the primary key and when the dublicate rollno is entered it should to show the message that "this number is already exist"

i have used the following primary key but it doesnot work



public class DataHaandler {
	
	public static final String NAME="name";
	public static final String EMAIL="email";
	public static final String TABLE_NAME="mytable";
	public static final String DATA_BASE_NAME="mydatabase";
	public static final int DATABASE_VERSION=1;
	public static final String TABLE_CREATE="create table"+ TABLE_NAME+"("+NAME + "INTEGER PRIMARY KEY AUTOINCREMENT,"+TABLE_NAME+" TEXT,"+EMAIL+");";
	DataBaseHelper dbhelper;
	Context ctx;
	SQLiteDatabase db;
	public  DataHaandler(Context ctx)
	{
		this.ctx=ctx;
		dbhelper=new DataBaseHelper(ctx);
	}
	private static class DataBaseHelper extends SQLiteOpenHelper
	{
		public DataBaseHelper(Context ctx)
		{
		super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);	
		}

		public DataBaseHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
		try{
			db.execSQL(TABLE_CREATE);
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			
		db.execSQL("DROP TABLE IF EXISTS mytable");
		onCreate(db);
			
		}
		
	}
	public DataHaandler open()
	{
		db=dbhelper.getWritableDatabase();
		return this;
	}
	
	public void close()
	{
		dbhelper.close();
	}
	
	public long insertData(String name,String email)
	{
		ContentValues content=new ContentValues();
		content.put(name, name);
		content.put(email, email);
		return db.insert(TABLE_NAME, null, content); 
	}
	
	public Cursor returnData()
	{
		return db.query(TABLE_NAME, new String[]{NAME,EMAIL}, null, null,null, null, null);
		
	}


}
Posted

1 solution

Instead of using Insert, try using insertOrThrow[^]. That method should properly throw an exception id an error is encountered. Or if you want to control what happens in conflict, use insertWithOnConflict and pass the proper CONFLICT_ constant.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900