I have the following Java Class
package com.sjhdevelopment.shaunharrison.myejuiceapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "EJuiceData.db";
public static final int DATABASE_VERSION = 1;
public MyDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase database) {
database.execSQL("create table if not exists Inventory");
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
database.execSQL("ALTER TABLE Recipe ADD COLUMN NOTES TEXT");
onCreate(database);
}
}
Then in my main activity I have the following;
public class Calculation extends AppCompatActivity {
private MyDBHelper dbHelper;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
try {
dbHelper = new MyDBHelper(this);
dbHelper.getWritableDatabase();
}
catch(Exception e)
{
showError("Error", e.getMessage());
}
}
However, when I debug the code to see if the database + tables are being created with a break point on the try and on the database.execSQL("create....
There debugger doesn't actually go into the MyDBHelper class to do anything, therefore I'm assuming that the database + tables aren't being created
I've looked online and it says that when a getWritableDatabase/readable is called the onCreate method should get called
Any idea's as to what I'm doing wrong?
onCreate(...) is only called when the database is created for the first time. If you want to change your database you have to increase DATABASE_VERSION then it will jump into onUpgrade(...)
It looks like your SQL is not correct onCreate. Instead of database.execSQL("create table if not exists Inventory"); it should be
database.execSQL("CREATE TABLE table_name
(id_column INTEGER PRIMARY KEY
, column_name TEXT);";
You need to manually created every table with all the corrected columns. They will be created once you call the database for the first time.
Related
i have a very simple code i am trying to create SQL lite database but it's not creating while i check my DEVICE FILE EXPLORER folder there is not any database folder there under my apps folder.
here is the code:
DatabaseHelper.java
package com.example.ali.schoolapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db = this.getWritableDatabase();
db.execSQL("CREATE TABLE Items " + " (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, description TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}
MainActivity.java
package com.example.ali.schoolapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
}
}
The database will not get created until you attempt to do something with it. Only then (when getWritableDatabase or getReadableDatabase is called) will the database be created.
So you could try :-
myDb = new DatabaseHelper(this); //<<<<<<<<<<< EXISTING LINE
Cursor csr = myDB.getWritableDatabase().query("Items",null,null,null,null,null,null);
csr.close();
And then the Database would have been created.
Note the above isn't how you would typically access the database, it's a quick fix. Normally you'd have you access methods in a Class (perhaps in the DatabaseHelper Class).
P.S. your onUpgrade method would very likely fail if you changed the version number (4th parameter (which is 1) when you call super). That is onUpgrade calls onCreate as the table exists you will get an error. You would typically DROP the table before calling onCreate).
I have prepared a code to create a database as well as table in SQLITE ANDROID STUDIO, but I am getting error in SQL statement.
Image of error is here :- ERROR IMAGE
package com.example.thakkar.registration;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DATABASAE_NAME="student.db";
public static final String TABLE_NAME="student_table";
public static final String COL_1="NAME";
public static final String COL_2="EMAIL";
public static final String COL_3="PASSWORD";
public DataBaseHelper(Context context) {
super(context, DATABASAE_NAME, null, 1);
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table"+ TABLE_NAME+ "(NAME TEXT,EMAIL TEXT,PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXIST"+ TABLE_NAME);
onCreate(db);
}
}
You need to separate table with space before TABLE_NAME,
Something like ,
db.execSQL("create table "+ TABLE_NAME+ "(NAME TEXT,EMAIL TEXT,PASSWORD TEXT)");
Also do the same in onUpgrade() method,
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
I have an app and I didn't use database up the present.Now I will update my app and this app contains a database.I am curious about this.Which method will call on updated phones in database onCreate or onUpgrade ?
first time if db don't exist, onCreate() method will run.
if db exist and your current db version is higher than installed version, onUpgrade() will run and you should check version in onUpgrade method and do what you want.
here is an example of dbHandler.java class.
package com.app.util;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Milad
*/
public class DBHandler extends SQLiteOpenHelper {
private static final String DB_NAME = "YourDbName";
private static final int DB_VERSION = 1;
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create firstTable
db.execSQL("CREATE TABLE TEST ( _id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >2) {
db.execSQL("DROP TABLE IF EXISTS TEST");
onCreate(db);
}
}
}
When you first create the database onCreate() method will be called. If you upgrade the database version then that time onUpgrade() method will be called.
I have 2 text fields on the screen and a button. When the button is pressed I want the information in the name text field to be passed to a variable, then run my addAccount() method in my DatabaseHelper.class, passing the variable into this method, this should store the variable information in an SQLite database.
Here is my Activity with the text field and button.
package mr.mwod.moneyorganiser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddAccountActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addaccountlayout);
Button addAccountVairiable = (Button) findViewById(R.id.addAccountButton);
addAccountVairiable.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText accountNameData = (EditText)findViewById(R.id.accountNameTextField);
String accountNameVairiable = accountNameData.getText().toString();
//Need the code here to run addAccount form DatabaseHelper.class
//accountName vairiable needs to be passed into the method as the information to store.
}
});
}
}
I have commented where I think the code needs to go and what it needs to do.
Here is my DatabaseHelper.class encase their are errors is in there.
package mr.mwod.moneyorganiser;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "money_organiser";
private static final String TABLE_ACCOUNTS = "accounts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "account_name";
private static final String KEY_ACCOUNT_BALANCE = "account_balance";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_ACCOUNT_BALANCE + " INTEGER" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCOUNTS);
// Create tables again
onCreate(db);
}
public void addAccount(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
db.insert(TABLE_ACCOUNTS, null, values);
db.close();
}
}
Any help would be greatly appreciated.
Is there any trick in your question? Isn't just calling new DatabaseHelper(this).addAccount(accountNameVairiable); working? Of course it will make sense to reuse the variable, rather than allocating it every time, but I am almost sure this is not your problem.
By the way I would recommend you to change the name of the primary key column of the table. Use _id, some android helper methods will be easier to use in this way.
EDIT: I just noticed the call happens in anonymous class. This as noted by you will trigger a compilation error, because the listener is not a Context. The activity is. Luckily this can be very easily solved via placing what class exactly to use for the ocnstruction (using the parent Activity, which is a context).
new DatabaseHelper(AddAccountActivity.this).addAccount(accountNameVairiable);
It looks as if all you are missing is a call to DatabaseHelper.addAccount() at the lines you have highlighted.
Does this not work? If you are getting an error, then tell us what the problem is.
If you are wondering how to access the DatabaseHelper, then you could make it a singleton and refer to its instance when needed.
I'm newbie to android. I have gone through the android docs and I googled it, but I'm confused why my code is returning a no such table error.
I want to create a DB named as demo and I want to create a table student with three columns.
Here's my code:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
static final String dbName="demo";
public DatabaseHelper(Context context) {
super(context, dbName, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("Create table IF NOT EXISTS student(title text,address text,gender text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void insert_datas(String title,String artist,String patharray,String table_name){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("title",title);
initialValues.put("address",address);
initialValues.put("gender",gender);
long n = db.insert(table_name,title,initialValues);
System.out.println("n"+n);
db.close();
}
public Cursor get_datas(){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT * FROM student",null);
return cur;
}
}
and this how i m call the DatabaseHelper class:
public class MYActivity extends Activity{
DatabaseHelper dbAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customlist);
dbAdapter = new DatabaseHelper(this);
dbAdapter.insert_datas("test","test","test","student");
}
}
My error
**11-26 02:10:00.210: INFO/SqliteDatabaseCpp(27151): sqlite returned: error code = 1, msg = no such table: student, db=/data/data/com.player.activites/databases/demo
11-26 02:10:00.210: ERROR/SQLiteDatabase(27151): android.database.sqlite.SQLiteException: no such table: student: , while compiling: INSERT INTO studenty(title,address,gender) VALUES (?,?,?)**
Thanks
Try upgrading the database version number (right now you have it as 1). Is it possible you ran your app and tried to access the DB before your helper's onCreate actually did anything? If you did that, you would have an empty DB at version 1. If you don't want to increment your version numbers, you could alternatively uninstall your app or clear its data to delete the DB file entirely.