I am making a diary application in android which is supposed to get some data from text fields.
When I run my app on the emulator, it gets successfully installed but as soon as I give input in the fields and I tap save option in the menu, emulator prompts that diary app has stopped working.
I am not able to find database folder in my app in emulator's file explorer which means my database is not making.
Here is my SQLite connection making and insertion in table code that i am writing in save item.
if(item.getItemId()==R.id.save){
EditText et=(EditText)findViewById(R.id.mood);
String mood=et.getText().toString();
et= (EditText)findViewById(R.id.weather);
String weather=et.getText().toString();
et= (EditText)findViewById(R.id.Text);
String text=et.getText().toString();
Date date= new Date();
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(date);
SQLiteDatabase db= openOrCreateDatabase("DiaryDatabase",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXIST DIARY ('Mood VARCHAR' , 'Weather VARCHAR' , 'Text VARCHAR' , 'Time VARCHAR' , 'Id INTEGER PRIMARY KEY');");
db.execSQL("INSERT INTO DIARY VALUES(mood,weather,text,strDate,NULL);");
db.close();
}
I think your both e.q. DDL and DML statement is incorrect. Try to replace yours with following:
String createQuery = "CREATE TABLE IF NOT EXIST DIARY ("
+ "id integer primary key, "
+ "mood text, "
+ "weather text, "
+ "content text, "
+ "time text" + ")";
Here:
INSERT INTO DIARY VALUES(mood,weather,text,strDate,NULL);
Your origin create statement create PK column as last column and here in your insert statement you are trying to insert NULL as PK that is not allowed and it doesn't make sence since PK is unique identifier of each row.
You should create a SQLite helper class extending from SQLiteOpenHelper to perform all of the database related items such as creating the database and creating the required tables.
Check out this example and use it as a guide:
http://www.vogella.com/articles/AndroidSQLite/article.html
Related
Simply what I want is when android application is launched for the first time to create database and have standard values in it.
I am successfully initiating CREATE TABLE IF NOT EXISTS and creating a table when application is opened first time. Let's say there will be EUR and USD lines in DB. I want EUR to have already value 100 and USD value 0.
What would be simplest solution for populating database table when table is created/first time application is launched(database table will be created anyway only one time when first time launching app)?
I have read about creating database file in assets folder and then just copying it, creating flag in SharedPreferences to know when application is launched for a first time and then create and populated database or just create method in main onCreate() that check database and fills it if it's empty.
This could be start:
void createdDatabase() {
String databasePath = Environment.getExternalStorageDirectory().getPath() + File.separator + "database.db";
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databasePath, null, null);
String sqlCreateMessages = "CREATE TABLE currencies (\n" +
" id INTEGER PRIMARY KEY,\n" +
" name text NOT NULL,\n" +
" value text NOT NULL\n" +
")";
database.execSQL(sqlCreateMessages);
ContentValues values = new ContentValues();
values.put("name", "EUR");
values.put("value", "100");
database.insert("currencies", null, values);
values = new ContentValues();
values.put("name", "USD");
values.put("value", "0");
database.insert("currencies", null, values);
}
I have an app that allows the user to save some chosen rows from a temporary table. The user is able to name the new table.
I am successfully creating a table using the name the user has input, and putting all the chosen rows from the temporary table into the new table.
However, if the table name they enter already exists, I want to notify them via Toast and have them choose another name. I am still learning sqlite - is there a way to do this?
In my head I am using some sort of if statement to check if the table exists, and then executing code, however half of it is in sqlite and half is in java. I'm not sure the correct way to do this. Any suggestions are greatly appreciated!
private void createTable() {
dbHandler.getWritableDatabase().execSQL("CREATE TABLE IF NOT EXISTS " + favoriteName + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT , exercise TEXT , bodypart TEXT , equip TEXT );");
dbHandler.getWritableDatabase().execSQL("INSERT INTO " + favoriteName + " SELECT * FROM randomlypicked");
Try
Cursor cursor = dbHandler.getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName +"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) { //table already exists
//show toast
cursor.close();
return;
}
cursor.close();
}
//create table and insert normally
I'm facing a strange problem. I'm creating a db in sqlite with the below query
String GROUP_TABLE = "groups";
String ROW_ID = "rowid";
String GROUP_ID = "GroupID";
String GROUP_NAME = "GroupName";
String GROUP_STATUS = "GroupStatus";
String IS_ADMIN = "IsAdmin";
String GROUP_TYPE = "GroupType";
String IS_PUBLIC = "IsPublic";
String LAST_UPDATE = "LastUpdate";
String groupQuery = "CREATE TABLE IF NOT EXISTS "+ GROUP_TABLE +" ("
+ROW_ID+" INTEGER PRIMARY KEY, "
+GROUP_ID+" TEXT, "
+GROUP_NAME+" TEXT, "
+GROUP_STATUS+" TEXT, "
+GROUP_TYPE+" TEXT, "
+IS_ADMIN+" TEXT, "
+IS_PUBLIC+" TEXT, "
+LAST_UPDATE+" TEXT);";
This is the schema given by sqlite adb command
H:\adt-bundle-windows-x86_64-20140702\sdk\platform-tools>sqlite3
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open mydb.db
sqlite> .full schema
Usage: .fullschema
sqlite> .fullschema
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE groups (rowid INTEGER PRIMARY KEY, GroupID TEXT, GroupName TEXT, GroupStatus TEXT, GroupType TEXT, IsAdmin TEXT, IsPubli
c TEXT, LastUpdate TEXT);
/* No STAT tables available */
and when I enter records for the first time there will be no problem. But when I try to enter records next time i get
E/SQLiteLog﹕ (1) table groups has no column named LastUpdate
11-04 14:35:01.850 11947-11974/? E/SQLiteDatabase﹕ Error inserting GroupType=1 GroupID=553 LastUpdate=2015-08-08T14:17:14.000Z IsAdmin=1 GroupName=SAIFOOTWEARS GroupStatus=1
android.database.sqlite.SQLiteException: table groups has no column named LastUpdate (code 1): , while compiling: INSERT INTO groups(GroupType,GroupID,LastUpdate,IsAdmin,GroupName,GroupStatus) VALUES (?,?,?,?,?,?)
And when I check the schema again the column is missing.
H:\adt-bundle-windows-x86_64-20140702\sdk\platform-tools>sqlite3
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open mydb.db
sqlite> .fullschema
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE groups ( rowId INTEGER PRIMARY KEY,GroupID TEXT, GroupName TEXT,GroupStatus TEXT,IsAdmin TEXT, GroupType TEXT, IsPublic
TEXT);
/* No STAT tables available */
Any leads on this would be of great help.
onCreate() method of sqliteOpenHelpers called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
I think first time when you created your database you don't include LastUpdate column. Later you included it.but your table is created first time.So when adb get same database version for your app it dose not update your database.
So try this
Change your databse version no. Or uninstall app from your phone and run it again.
If problem does not solve.Then please provide full code of your class in Question.
I have a problem to create a table. If I try to get a value from the second column, android writes a empty space in the toast. But if I try to get a value from the first column, android writes the value of the column correctly. The query functions to write the first column and to write the second column are equal. So I think the Creation of the Table is the problem. But look yourself:
public SQLiteDatabase tabelleerstellen(){
SQLiteDatabase leveldatabase = openOrCreateDatabase("leveldata.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
leveldatabase.setVersion(1);
final String CREATE_TABLE_LEVEL =
"CREATE TABLE IF NOT EXISTS tbl_level ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "ME1 TEXT, "
+ "ME2 TEXT, "
+ "ME3 TEXT, "
+ "ME4 TEXT, "
+ "ME5 TEXT, "
+ "ME6 TEXT, "
+ "ME8 TEXT, "
+ "GESCHAFFT INTEGER);";
leveldatabase.execSQL(CREATE_TABLE_LEVEL);
return leveldatabase;
}
public void tester(SQLiteDatabase leveldata){
ContentValues cursortester = new ContentValues();
cursortester.put("ME2","25");
leveldata.insert("tbl_level",null,cursortester);
String[] testerpr = {"ME2"};
Cursor testerprüfen = leveldata.query("tbl_level",testerpr,null,null, null, null,null,null);
testerprüfen.moveToFirst();
String dada = testerprüfen.getString(testerprüfen.getColumnIndex("ME2"));
Toast testertoast = Toast.makeText(getApplicationContext(),dada,Toast.LENGTH_SHORT);
testertoast.show();
}
Please check the following things:
Please make sure the table is up to date .. so try to call DROP TABLE IF EXISTS tbl_level; and recreate the table.
If you run a test make sure the table is completely empty ... so delete everything at the beggining of the test.
If the table can contain elements during the test then make sure you check the last inserted element. Please note that calling testerprüfen.moveToFirst(); moves the cursor to the first row in the table so checking that row every time is even if the table contains 50 elements is not a good thing. In this case you either use a sorting option in your query of uese while (testerprüfen != null && testerprüfen.moveToNext()) {// Your code here}
All in all I think your problem is that you already inserted more that one element in the able but you always check only the first element (with testerprüfen.moveToFirst();). Please not that there is a cursor.moveToLast() method that you can also call. This method moves the cursor to the last row in the table.
I have three tables (Training, Person and attendance). The connection between the table is; Training has its fields same to person. And the attendance table has only two fields training_id and person_id. When person register to the training, the training_id and person_id insert into the attendance table. Ok, I am able to insert new person. When person that was already attended to the training and want to update himself, the table (person) gets updated but in the attendance table, the person is inserted again. What I want is when the person updated himself, the attendance table should not insert him again.
I tried this;
public void registerToTraining(int training_id) {
DatabaseHelper db = DatabaseHelper.getInstance();
String query = "SELECT * FROM attendance WHERE training_id = "
+ Integer.toString(training_id) + " AND person_id = "
+ Integer.toString(this.getId()) + ";";
db.sqlCommand(query);
if(The query does not return one row or more){
String command = "INSERT INTO attendance (training_id , person_id) VALUES ("
+ Integer.toString(training_id)
+ ", "
+ Integer.toString(this.getId()) + ") ;";
db.sqlCommand(command);
}
First Query then database then make the cursor move to first or not .
if(cursor.moveFirst)
{
Aleady exsist data.
}else
{
new data insert
}
You can use a UNIQUE constraint on the columns of the table when creating it and skip the conflicting row when the constraint is violated (http://www.sqlite.org/lang_conflict.html)
CREATE TABLE attendance (training_id INT, person_id INT, UNIQUE(training_id, person_id)
ON CONFLICT IGNORE);