Hello I am making a simple note application, using an SQLite database, using a custom arraylist adapter, where the user can save a note having a title, a descriptive text, and the date. Everything works, but I want users to be able to save a new note only if the title is not in the database. How can I do this ?
Here is the edit note
public class Edit_notes extends AppCompatActivity {
private DBOpenHelper dbop;
private SQLiteDatabase sdb;
private EditText title_text;
private EditText note_text;
public boolean SaveNote(){
String note_title_string = title_text.getText().toString();
String note_text_string = note_text.getText().toString();
if (!note_title_string.isEmpty()){
if(!note_text_string.isEmpty()) {
// Need to check if title is not in the database then insert else don't
String date = new Date().getDate() + "/" + (new Date().getMonth() + 1) + "/" + (new Date().getYear() + 1900);
AddData(note_title_string, note_text_string, date); // Add title to the database
Toast.makeText(this, "Note saved", Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(this, "Note text cannot be empty", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show();
}
return true;
}
public void AddData(String title_entry, String text_entry, String date){
dbop = new DBOpenHelper(this);
sdb = dbop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("TITLE", title_entry);
cv.put("TEXT", text_entry);
cv.put("DATE", date);
sdb.insert("note_table", null, cv);
}
}
SQLite database.java:
public class DBOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "notes.db";
public static final String TABLE_NAME = "note_table";
public static final String ID_COLUMN = "ID";
public static final String TITLE_COLUMN = "TITLE";
public static final String TEXT_COLUMN = "TEXT";
public static final String DATE_COLUMN = "DATE";
SQLiteDatabase db = this.getWritableDatabase();
public DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 5);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT, " + " TEXT TEXT, " + " DATE STRING)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table note_table");
onCreate(db);
}
}
I guess there is no need to provide the mainactivity.java
Change the table Create to :-
String createTable = "CREATE TABLE " + TABLE_NAME
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " TITLE TEXT UNIQUE, " + " TEXT TEXT, " + " DATE STRING)";
Uninstall the App, or delete the App's Data, or increase the database version number and rerun the App. Row will not be added UNIQUE constraint conflict (same title) (insert method effectively uses INSERT OR IGNORE).
Related
I'm having trouble finding what's missing in my code. I'm trying to insert data but "long result == db.insert" in my DatabaseHelper class always returns -1". I cannot pin point what I'm doing wrong. Please help. Any Idea would be very appreciated.
My DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "drivefinal.db";
public static final String TABLE_NAME = "drive_table";
public static final String ID = "ID";
public static final String NUMBER = "Number";
public static final String FNAME = "First Name";
public static final String LNAME = "Last Name";
public static final String COORDINATE = "Coordinate";
public static final String ADDRESS = "Address";
public static final String NOTES = "Notes";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT ,NUMBER TEXT,FNAME TEXT,LNAME TEXT,COORDINATE TEXT,ADDRESS TEXT,NOTES TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
public boolean insertData(String number, String fName, String lName, String coordinate, String address, String notes){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NUMBER, number);
contentValues.put(FNAME, fName);
contentValues.put(LNAME, lName);
contentValues.put(COORDINATE, coordinate);
contentValues.put(ADDRESS, address);
contentValues.put(NOTES, notes);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1 )
return false;
else
return true;
}
My main activity file:
public void addData(){
btnSave.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = myDb.insertData(editTextnumber.getText().toString(),
editTextfname.getText().toString(),
editTextlname.getText().toString(),
editTextcoordinate.getText().toString(),
editTextaddress.getText().toString(),
editTextnotes.getText().toString());
if(isInserted)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
);
}
}
Your table definition creates column names that are not the same as the column names you are trying to use when inserting.
e.g. your table will have the column name FNAME not First Name (etc).
Secondly you would have issues trying to use a column named First Name as it includes a space and would have to be enclosed e.g. [First Name].
I'd suggest using :-
public static final String NUMBER = "Number";
public static final String FNAME = "FirstName"; //<<<<<<<<<< space removed
public static final String LNAME = "LastName"; //<<<<<<<<<< space removed
public static final String COORDINATE = "Coordinate";
public static final String ADDRESS = "Address";
public static final String NOTES = "Notes";
Along with :-
db.execSQL("create table if not exists " + TABLE_NAME +"(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + NUMBER + " TEXT," + FNAME + " TEXT," + LNAME + " TEXT," + COORDINATE + " TEXT," + ADDRESS + " TEXT," + NOTES + " TEXT)");
To introduce the changes (i.e. for the onCreate method to run, as it only runs automatically when creating the database) you would have to do one of the following :-
Delete the App's data.
Uninstall the App.
Change the database version number e.g. change super(context, DATABASE_NAME, null, 1); to super(context, DATABASE_NAME, null, 2);
and then rerun the App.
I am pretty new to Android development and I am trying to implement a database for my app.
I started with only having one column in the database (COLUMN_DATE) and then added another column (COLUMN_REPEAT). This worked fine and printed the results as expected. However, when I tried adding another column (COLUMN_ACCOUNT), printDatabase() in MainActivity did not print anything.
I understand you can view what is in your database by using Android Device Monitor, but I keep getting an error when I click on that so I cannot use it (That is a separate issue which I haven't been able to solve). Hence, I am unsure if it is just an issue with printing the database or if there is actually any data in the database at all.
Any help would be much appreciated
----MainActivity.java----
dbHandler = new DatabaseHandler(this, null, null, 1);
printDatabase();
//Print the database
public void printDatabase() {
String dbString = dbHandler.databaseToString();
recordsTextView.setText(dbString);
}
//Add an item to the database
public void addButtonClicked(View view){
Income date = new Income(dateView.getText().toString());
Income repeat = new Income(repeatSpinner.getSelectedItem().toString());
Income account = new Income(accountSpinner.getSelectedItem().toString());
dbHandler.addData(date, repeat, account);
printDatabase();
}
//Delete items with input date from database
public void deleteButtonClicked(View view){
String inputText = dateView.getText().toString();
dbHandler.deleteData(inputText);
printDatabase();
}
----DatabaseHandler.java----
public class DatabaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "IncomeExpenseDB.db";
public static final String TABLE_NAME = "income_expense";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_REPEAT = "repeat";
public static final String COLUMN_ACCOUNT = "account";
public DatabaseHandler(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_DATE + " TEXT, " + COLUMN_REPEAT + " TEXT, " +
COLUMN_ACCOUNT + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add a new row to the database
public void addData(Income date, Income repeat, Income
account){
ContentValues values = new ContentValues();
values.put(COLUMN_DATE, date.get_item());
values.put(COLUMN_REPEAT, repeat.get_item());
values.put(COLUMN_ACCOUNT, account.get_item());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
//Delete data from the database
public void deleteData(String date){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_DATE + "=\""
+ date + "\";");
}
// Create a string to print out in MainActivity
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
//Cursor points to a location in results
Cursor c = db.rawQuery(query, null);
//Move to first row in results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("date")) != null &&
c.getString(c.getColumnIndex("repeat")) != null &&
c.getString(c.getColumnIndex("account")) != null) {
dbString += c.getString(c.getColumnIndex("date"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("repeat"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("account"));
dbString += "\n";
}
c.moveToNext();
}
db.close();
return dbString;
}
}
----Income.java----
public class Income {
private int _id;
private String _item;
public Income(){
}
public Income(String item) {
this._item = item;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_item() {
return _item;
}
public void set_item(String _item) {
this._item = _item;
}
}
Uninstalling and reinstalling is very naive approach which will only work in development phase. When your app goes on to play store, users are not going to uninstall and reinstall the app.
Correct way to update the database for published apps is to increase your db version and use onUpgrade method to update your database.
look at this method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
In current scenario if you just increase your db version, it will drop existing table and create a new one with new columns and specifications. The downside is that you'll lose all of your existing data.
If you want to save existing data and add new column to db, you have to do something like this -
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//add new column
sqLiteDatabase.execSQL("ALTER TABLE "+ TABLE_NAME + " ADD COLUMN "+ NEW_COLUMN + " INTEGER/TEXT ");
}
}
Just update your version of database when you add any column or make any update in the table. ... this helps me hope it will also work for you.
I know, there are a lot of answers already. But I'm a newbie on using SQLite yet and I tried what those answers say but nothing works.
It says my column id doesn't exist but it does exist:
public class SQLite extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "OMDBAPI";
// Films table name
static final String TABLE_FILMS = "films";
// Contacts Table Columns names
static final String KEY_TITLE = "Title";
static final String KEY_YEAR = "Year";
static final String KEY_RELEASED = "Released";
static final String KEY_RUNTIME = "Runtime";
static final String KEY_GENRE = "Genre";
static final String KEY_DIRECTOR = "Director";
static final String KEY_WRITER = "Writer";
static final String KEY_ACTORS = "Actors";
static final String KEY_PLOT = "Plot";
static final String ID = "_id";
public SQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FILMS_TABLE = "CREATE TABLE " + TABLE_FILMS +"(" +
ID + "integer primary key autoincrement," +
KEY_TITLE + " TEXT, " +
KEY_YEAR + " TEXT, " +
KEY_RELEASED + " TEXT, " +
KEY_RUNTIME + " TEXT, " +
KEY_GENRE + " TEXT, " +
KEY_DIRECTOR + " TEXT, " +
KEY_WRITER + " TEXT, " +
KEY_ACTORS + " TEXT, " +
KEY_PLOT + " TEXT" +
");";
db.execSQL(CREATE_FILMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FILMS);
// Create tables again
onCreate(db);
}
}
And I try to populate this on a listview:
public class Query extends Activity {
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBController crud = new DBController(getBaseContext());
Cursor cursor = crud.loadData();
String[] titles = new String[] {SQLite.ID, SQLite.KEY_TITLE};
int[] idViews = new int[] {R.id.idnumber, R.id.grid_title};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.adapter_layout,cursor,titles,idViews, 0);
list = (ListView)findViewById(R.id.listView);
list.setAdapter(adapter);
}
}
This is my DB CONTROLLER (Newbie mistake? Should I put the ID here too?):
public class DBController {
private SQLiteDatabase db;
private SQLite bank;
String success = "Film saved.";
String failed = "There was a problem saving the movie.";
public DBController(Context context){
bank = new SQLite(context);
}
public String insertData(String title, String release, String year, String writers, String actors, String director, String genre, String plot, String runtime){
ContentValues values;
long result;
db = bank.getWritableDatabase();
values = new ContentValues();
// Insert values
values.put(SQLite.KEY_TITLE, title);
values.put(SQLite.KEY_YEAR, release);
values.put(SQLite.KEY_RELEASED, release);
values.put(SQLite.KEY_YEAR, year);
values.put(SQLite.KEY_GENRE, genre);
values.put(SQLite.KEY_DIRECTOR, director);
values.put(SQLite.KEY_WRITER, writers);
values.put(SQLite.KEY_ACTORS, actors);
values.put(SQLite.KEY_PLOT, plot);
values.put(SQLite.KEY_RUNTIME, runtime);
result = db.insert(SQLite.TABLE_FILMS, null, values);
db.close();
if (result ==-1)
return failed;
else
return success;
}
public Cursor loadData(){
Cursor cursor;
String[] fields = {bank.KEY_TITLE,bank.KEY_RELEASED};
db = bank.getReadableDatabase();
cursor = db.query(bank.TABLE_FILMS, fields, null, null, null, null, null, null);
if(cursor!=null){
cursor.moveToFirst();
}
db.close();
return cursor;
}
}
Can someone help me find out why it says I don't have an ID column?
(Why are ppl downvote the post? I thought Stack Overflow was to help idiots like me =P)
You don't have _id column, you have _idinteger because you forgot to put a space in the CREATE query. Change the line
ID + "integer primary key autoincrement," +
to
ID + " integer primary key autoincrement," +
You can use baseColums interface that provides a primary key field (called _ID)
An example from google
Hi I am new to android development and I am attempting to make an app which stores appointments. My fragments and activities are all fine however I am trying to work out how to check my sqlite database that the string I am trying to enter isn't already stored as a unique string already, any help is much appreciated.
Here is my code for the database so far.
public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "appointments.db";
public static final String TABLE_APPOINTMENTS = "appointments";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_MONTH = "month";
public static final String COLUMN_YEAR = "year";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_DESCRIPTION = "details";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_APPOINTMENTS
+ "(" + COLUMN_DAY + " INTEGER, " + COLUMN_MONTH + " INTEGER, " + COLUMN_YEAR + " INTEGER, "
+ COLUMN_TITLE + " TEXT NOT NULL UNIQUE, " + COLUMN_TIME + " TEXT, " + COLUMN_DESCRIPTION + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_APPOINTMENTS);
onCreate(db);
}
public void addAppointment(Appointment app){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
Call this method and check return true mean its exist otherwise not.
public boolean checkAppointmentExist(String name){
booolean isExist = false;
String selection = COLUMN_TITLE + " = ? ";
String[] selectionArgs = new String[]{name};
Cursor cursor = database.query(TABLE_APPOINTMENTS, null, selection, selectionArgs, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isExist = true;
}
}
return isExist;
}
public void addAppointment(Appointment app){
if(!checkAppointmentExist(app.get_title())){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
I can not create a table. It shows that the database is created and I can also insert a row, but the table is not created.
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
You're missing a , between USER_EMAIL and USER_PASS columns in the CREATE TABLE.
After adding it you can uninstall your app to recreate the database. When is SQLiteOpenHelper onCreate() / onUpgrade() run?
You miss comma in USER PASS type.Uninstall the application and install it again each time you add something new to sqlite database because the table structure has been changed.So you need to reinstall the new application .
The code should be like this
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT ,"+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ")";