SQLite database handling with android application - android

Hi i am going to create a SQLite database and insert records. but my database does not create.
following is the code. Cant understand why. trying this for a long time
If someone can help its a great help
public class DatabaseHelper extends SQLiteOpenHelper{
static final String dbName="MyDatabase";
public DatabaseHelper(Context context) {
super(context, dbName, null,33);
}
#Override
public void onCreate(SQLiteDatabase db) {
String qry = "CREATE TABLE DEPT(dept_id INTEGER PRIMARY KEY, deptName TEXT)";
db.execSQL(qry);
}
}
I am calling the constructor like this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper dp = new DatabaseHelper(this);
Toast.makeText(this, "Finish Execution", Toast.LENGTH_LONG).show();
}
}

create your database by using this sample
http://marakana.com/forums/android/examples/55.html

Related

SQLite Datebase Creation

I am trying to create a database, but nothing happening with my code. I know this question is very basic but I am a new learner so I could not solve my problem so kindly help me.
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="employeedb";
private static final String TABLE_NAME="EMPLOYEETABLE";
private static final int DATABASE_VERSION=1;
private static final String EID="_id";
private static final String NAME="Name";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+EID+" INTEGER PRIMARY AUTOINCREMENT, "+NAME+" VARCHAR(255))";
private static final String DROP_TABLE="DROP TABLE "+TABLE_NAME+"IF EXISTS";
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.message(context, "Constructor called.");
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Message.message(context, "onCreate called.");
db.execSQL(CREATE_TABLE);
}
catch (Exception e)
{
Message.message(context, ""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "onUpgrade called.");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
Message.message(context, ""+e);
}
}
}
Here is Message Class that only one method
public class Message {
public static void message(Context context, String message){
Toast.makeText(context,message,Toast.LENGTH_SHORT);
}
}
Here is MainActivity Code where i call the getWritabeDatase Method.
public class MainActivity extends Activity implements MyDialog.Communicator {
LinearLayout layout;
TextView txt;
TextView date;
DatabaseHelper dbhelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layoutbottom);
date = (TextView) findViewById(R.id.date);
txt =(TextView) findViewById(R.id.title);
GeneralMethods generalmethods = new GeneralMethods(this,this);
dbhelper = new DatabaseHelper(this);
SQLiteDatabase sqLiteDatabase = dbhelper.getWritableDatabase();
}
public void showDialog(View v){
FragmentManager manager = getFragmentManager();
MyDialog myDialog = new MyDialog();
myDialog.show(manager,"MyDialog");
}
#Override
public void onDialogueMessage(String message) {
date.setText(message);
}
}
You onCreate will get called when you first access the database using the helper.
Any call to either
getReadableDatabase() or getWritableDatabase()
will cause the onCreate to get triggered and only then. Your onUpgrade will trigger when you change the database version of an already existing schema.
Also as per SQLite documentation, an integer primary key will automatically get incremented to the max+1 value on it's own.
Adding an Auto increment causes unnecessary explicit overhead and changes the rowid selection algorithm and they do not recommend it.
You have forgotten the show() for the toast in your Message class
Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
Basically without the show(), the Toast will not get shown, it will just get created. Now since onCreate gets called only once, to check if it's working , uninstall and reinstall the app or clear it's data before testing

How to create default database in sqlite?

How to Create default database in SQ-Lite database? so if the Database/Value doesn't exist i want my App to use default Database/Value automatically..
Here is my database creation code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=openOrCreateDatabase("D5",MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Record(value1 VARCHAR,value2 VARCHAR,value3 VARCHAR);");
}
What i usually do is a class similar to this...
public class SQLiteAdapter extends SQLiteOpenHelper{
private static final int DATABASE_VERSION=1;
private static String DATABASE_NAME="your_database_name";
public SQLiteAdapter(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS Record(value1 VARCHAR,value2 VARCHAR,value3 VARCHAR);");
}
}
then when you want to use it from an activity:
SQLiteAdapter db;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new SQLiteAdapter(this);
}
and with that instance db you can do whatever you want, db.execSQL, etc. etc.

i want to insert a record to my db in second activity

I am new on Android programming. So that, I'll use wrong technical words, sorry for that ;)
i ve an app. in this app, onCreate, im checking if my db is created ( this check is for first time use ), if my db isn't created yet I'm routing user to a second layout( or activty. i couldnt be sure whch one is right word ). in this activity, when i try to create a SQLiteDatabase parameter im having a null pointer exception.
Here is a part of MainActivity.java
public class MainActivity extends Activity
{
VeriTabani veritabani; // vertiabani means database in turkish
#Override
protected void onCreate(Bundle savedInstanceState)
{
if(db_flag==0)
{
Intent intent = new Intent(MainActivity.this, SecondClass.class);
startActivity(intent);
//...
}
}
}
Here is my VeriTabani.java;
public class VeriTabani extends SQLiteOpenHelper
{
static final String VeriTabani="DATABASENAME";
static final int version=1;
public VeriTabani(Context context) {
super(context, VeriTabani, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE TABLENAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, xxx STRING,yyy STRING );");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST TABLENAME");
onCreate(db);
}
}
And, here is my SecondClass.java;
public class SecondClass extends Activity
{
VeriTabani veritabani;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SQLiteDatabase db=veritabani.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("xxx", another_parameter);
//...
}
//...
}
}
}
im having error on this line;
SQLiteDatabase db=veritabani.getWritableDatabase();
I'm using same VeriTabani class to insert records to DB in MainActivity and it works perfectly. i couldnt undertand what is wrong when i use same code block in another activity.
i guess solve is simple but i couldnt get it.
Thanks for your help.
you have just declared your variable
VeriTabani veritabani;
you haven't initialized that variable. you need to initialize it on onCreate() method.
veritabani = new VeriTabani(YourActivityName.this);
im having error on this line;
SQLiteDatabase db=veritabani.getWritableDatabase();
Looks like you didn't initialize your veritabani variable.
Add the following to that activity's onCreate():
veritabani = new VeriTabani(this);

Android SQLiteDatabase table does not exists

I am having a class named GameDb and it's extending SQLiteOpenHelper. I don't know why, but onCreate it's not called, the table is not created !
Having a singelton for all my activities and fragments:
public MyApp extends Application
{
// .... Code
private GameDb gameDb;
public GameDb getGameDb()
{
if (gameDb == null)
gameDb = new GameDb(this);
return this.gameDb;
}
}
Getting all games from database, calling from an activity
public class MyActivity extends FragmentActivity
{
#Override
protected void onCreate(Bundle bundle)
{
// Code....
// Get all games
ArrayList<Game> allGames = getMyApp().getGameDb().getAllGames();
}
}
Class which contains all necessary methods for querying the database (writing and reading). This methods are not written below because it's not necessary.
public class GameDb
{
private SQLiteDatabase db;
private GameDbHelper dbHelper;
public GameDb(Context context)
{
this.dbHelper = new GameDbHelper(context);
this.db = dbHelper.getWritableDatabase();
}
public ArrayList<Games> getAllGames()
{
// return db.query(....);
}
public void insertNewGame(int id, String name)
{
// db.query(....);
}
// Static inner class which extends SQLiteOpenHelper
private static class GameDbHelper extends SQLiteOpenHelper
{
public GameDbHelper(Context context)
{
super(context, "DB_NAME", null, 1);
}
// On create not called !
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE my_table(_id INTEGER AUTOINCREMENT, date TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
dropTable(db);
onCreate(db);
}
public void dropTable(SQLiteDatabase db)
{
db.execSQL("DROP TABLE IF EXISTS my_table");
}
}
}
When I'm trying to get all games, or add a new game I'm getting a FATAL EXCEPTION, (1) no such table: my_table
You may have a old database present on your device and database doesn't always get deleted when you reinstall the app using IDE. Thus you must uninstall the app manually and the reinstall your app using IDE.
I don't believe onCreate() gets implicitly called when you instantiate your database object. You need to explicitly call your Activity's openOrCreateDatabase() method.

Android/SQLite right way to open/close db?

Im a bit new to OOP so i want to know if im doing things correctly. For communication with database i have created a class SQLiteHelper witch does all the usual stuff (onCreate, onUpdate) and also opens and closes connection.
Here is the class, at the moment it has just on table but more will be added:
public class SQLiteHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "notebook";
public static final int DATABASE_VERSION = 2;
public static final String TABLE_LIST = "list";
public static final String TABLE_LIST_ID = "_id";
public static final String TABLE_LIST_NAME = "name";
public SQLiteDatabase db;
public SQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table " + TABLE_LIST + "(" + TABLE_LIST_ID
+ " integer primary key autoincrement, " + TABLE_LIST_NAME
+ " text not null);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);
onCreate(db);
}
public void open(){
db = getWritableDatabase();
}
public void close(){
db.close();
}
}
And next for each table i will create a new class witch extends previous class andd where i do all the operations relevant to that specific table.
For example ListSQL:
public class ListSQL extends SQLiteHelper {
public ListSQL(Context context) {
super(context);
}
public void delete(int id) {
open();
db.delete(TABLE_LIST, TABLE_LIST_ID + " = " + id, null);
close();
}
}
My question is that in OOP is this the correct way of doing things? Espesially the usage of open/close methods and db and TABLE variables in ListSQL seem kind of strange to me?
I always open the db connection in onResume() and close it in onPause(). In this way database is always open for each activity.
The reason I am not doing it in onCreate() and onDestroy() is once user go to other activity onCreate() of new activity will be called first then onDestroy() of old activity so if I perform any operation(ex:- search in my list or changing the status of user etc) on places other then onCreate() it will crash the app with reason database already closed.
Note: You have to open and close the connection, even if you are using SQLiteHelper class.
According to the Android manual, you do not need to close a database when using an SQLiteOpenHelper. The system will do it for you.
As #Dan mentioned above, you do no need to open and close the database every time you do a read/write operation if you are using SQLiteOpenHelper. The best way to use the database is :
1.
Declare and initialize an instance of SQLiteHelper in your Application base class like this :
public class App extends Application {
public static SQLiteHelper db;
#Override
public void onCreate() {
super.onCreate();
db = new SQLiteHelper(getApplicationContext());
db.open();
}
}
2.
In you activity, or any other place you want to use the DB, initialize the SQLiteHelper object like this :
SQLiteHelper db = App.db;
And then you can use the database anyway you want without having to worry about opening and closing it (:

Categories

Resources