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.
Related
I am trying to save the Latitude and Longitude to my SQLite database. However it is not saving it and not getting any error messages.
This is my code I have so far:
dbHandler = new DBHandler(MapsActivity.this);
googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
String latLong = latLng.latitude + " : " + latLng.longitude;
dbHandler.addNewLocation(latLong);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.addMarker(markerOptions);
Toast.makeText(MapsActivity.this, "Location has been added.", Toast.LENGTH_SHORT).show();
}
});
And then the DBHandler class:
public class DBHandler extends SQLiteOpenHelper {
private static final String DB_NAME = "locationsdb";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "mylocations";
private static final String ID_COL = "id";
private static final String NAME_LAT = "lat";
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_LAT + " TEXT)";
db.execSQL(query);
}
public void addNewLocation(String latLong) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_LAT, latLong);
db.insert(TABLE_NAME, null, values);
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Then when I check the database there is nothing saved in it?
Can someone please let me know what I am doing wrong here?
Thanks
Try db.beginTransaction() after calling getWritableDatabase() and use db.endTransaction() instead of db.close() in addNewLocation(...).
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).
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.
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 "+ ")";