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.
I am new to Android Programming.. I am trying to create sqLite Database in android Here is my code
sqLitee.java
package com.example.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class sqLitee extends SQLiteOpenHelper
{
public static final String DB_NAME="student.db";
public static final String TABLE_NAME="student";
public static final String COL_1="ID";
public static final String COL_2="FIRST_NAME";
public static final String COL_3="LAST_NAME";
public static final String COL_4="MARKS";
public sqLitee(Context context)
{
super(context, DB_NAME,null, 1);
// TODO Auto-generated constructor stub
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTO INCREMENT, FIRST_NAME TEXT, LAST_NAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
}
MainActivity.java
package com.example.sqlite;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
sqLitee myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new sqLitee(this);
setContentView(R.layout.activity_main);
}
}
When I am trying to run it on Android virtual Device , It says unfortunately , sqLite has stopped..
Thanks
remove this line in your sqllite constructor:
SQLiteDatabase db=this.getWritableDatabase();
you try to get the db, which is currently initializing.
There's a syntax error in your CREATE TABLE SQL. AUTO INCREMENT should be AUTOINCREMENT.
As always, first see the logcat for exception stacktrace and to learn what is failing and where.
Am developing an android application in which i have created "Server" database. In that database i have two tables i,e employee_table and attendance_table in that i hav not included my onReceive function and with that onReceive function i need to parse the new message and that message content should be store in employee table and attendance table so please me out to solve this issue..
Thanks in advance..
Here is my DbHelper.java :
package com.example.attendancesystem;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="Server";
public static final String EmployeeTable="employee_table";
public static final String Name="name";
public static final String Mobile_no="mobile";
public static final String Id="id";
public static final String AttendanceTable="attendance_table";
public static final String Latitude="Lat";
public static final String Longitude="Lan";
public static final String Accuracy="Accry";
public static final String Date="date";
public static final String Time="time";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+EmployeeTable+" ("+Id+" INTEGER PRIMARY KEY, "+Name+" TEXT, "+Mobile_no+" VARCHAR(13))";
db.execSQL(CREATE_TABLE);
CREATE_TABLE="CREATE TABLE "+AttendanceTable+" ("+Latitude+" double precision, "+Longitude+" double precision, "+Accuracy+" double,"+Date+" date,"+Time+"time)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+EmployeeTable);
db.execSQL("DROP TABLE IF EXISTS "+AttendanceTable);
onCreate(db);
}
}
My database class is DB.java
package com.example.pocketbooker;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class DB extends SQLiteOpenHelper implements BaseColumns{
private static final String DATABASE_NAME = "pb_database.db";
private static final int DATABASE_VERSION = 1;
public DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE Members(_id INTEGER PRIMARY KEY AUTOINCREMENT, Mem_Name VARCHAR(50));");
db.execSQL("CREATE TABLE Incomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Inc_Name VARCHAR(50), Inc_Sum VARCHAR(10), Inc_Mem VARCHAR (50), Inc_Change_Date DATE, " +
"Inc_Perbeg_Date DATE, Inc_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Outcomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Out_Name VARCHAR(50), Out_Sum VARCHAR(10), Out_Mem VARCHAR (50), Out_Change_Date DATE, " +
"Out_Perbeg_Date DATE, Out_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Goals(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Goal_Name VARCHAR(50), Goal_Sum VARCHAR(10), Goal_Mem VARCHAR (50), Goal_Change_Date DATE, " +
"Goal_Perbeg_Date DATE, Goal_Period VARCHAR (4));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
// TODO Auto-generated method stub
}
}
My "other" class is Dialog_mem.java
package com.example.pocketbooker;
import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint({ "NewApi", "ValidFragment" })
public class Dialog_mem extends DialogFragment implements OnClickListener {
EditText memname;
ContentValues cv = new ContentValues();
private SQLiteDatabase database;
private DB dbHelper;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Добавить Члена Семьи");
View v = inflater.inflate(R.layout.mem_dialog, null);
v.findViewById(R.id.mem_btnOK).setOnClickListener(this);
v.findViewById(R.id.mem_btnCancel).setOnClickListener(this);
memname=(EditText) v.findViewById(R.id.mem_name);
return v;
}
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
database = dbHelper.getWritableDatabase();
cv.put("Mem_Name", memname.getText().toString());
database.insert("Members", "Mem_Name", cv);
database.close();
Toast.makeText(getActivity(), "Добавлено", Toast.LENGTH_SHORT).show();
default:
dismiss();}
}
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}
}
Eclipse shows NullPointerException. I guess it's context error, but I don't know how to point the context needed. getActivity() is the wrong one. "This" too. getApplicationContext() doesn't work at all.
You need to initialize the dbHelper instance.
What you can do is
1. Create a singleton class for all Database operations.
2. Create a Datasource class. Through which you will access the Database.
3. In Data Source class add open() method
/**
* Open the Database
* #throws SQLException
*/
public void open() throws SQLException {
if (dbHelper != null) {
db = dbHelper.getWritableDatabase();
}
}
/**
* Close
*/
public void close() {
dbHelper.close();
}
4. Write the method which you need to acces Database in DataSource class and call the database operations on this db instance.
Well, I used the akashsr's answer (thank you, man, for the idea). If anyone is interested how I've made it (at last) here's the code.
DB.java
package com.example.pocketbooker;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class DB extends SQLiteOpenHelper implements BaseColumns{
private static final String DATABASE_NAME = "pb_database.db";
private static final int DATABASE_VERSION = 1;
private static DB sInstance;
ContentValues cv;
public DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE Members(_id INTEGER PRIMARY KEY AUTOINCREMENT, Mem_Name VARCHAR(50));");
db.execSQL("CREATE TABLE Incomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Inc_Name VARCHAR(50), Inc_Sum VARCHAR(10), Inc_Mem VARCHAR (50), Inc_Change_Date DATE, " +
"Inc_Perbeg_Date DATE, Inc_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Outcomes(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Out_Name VARCHAR(50), Out_Sum VARCHAR(10), Out_Mem VARCHAR (50), Out_Change_Date DATE, " +
"Out_Perbeg_Date DATE, Out_Period VARCHAR (4));");
db.execSQL("CREATE TABLE Goals(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Goal_Name VARCHAR(50), Goal_Sum VARCHAR(10), Goal_Mem VARCHAR (50), Goal_Change_Date DATE, " +
"Goal_Perbeg_Date DATE, Goal_Period VARCHAR (4));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
// TODO Auto-generated method stub
}
}
Created DataSource class with insert method. PBDataSource.java
package com.example.pocketbooker;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class PBDataSource {
DB dbHelper;
SQLiteDatabase db;
public PBDataSource(Context context) {
dbHelper = new DB(context);
}
public void open() throws SQLException {
if (dbHelper != null) {
db = dbHelper.getWritableDatabase();
}
}
public void close() {
dbHelper.close();
}
public void insertrecord (String a, String b, String c)
{ContentValues cv= new ContentValues();
cv.put(b,c);
db.insert(a, null, cv);
}
}
And used this method in my DialogFragment class Dialog_mem.java
package com.example.pocketbooker;
import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint({ "NewApi", "ValidFragment" })
public class Dialog_mem extends DialogFragment implements OnClickListener {
EditText memname;
private PBDataSource datasource;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().setTitle("Добавить Члена Семьи");
View v = inflater.inflate(R.layout.mem_dialog, null);
v.findViewById(R.id.mem_btnOK).setOnClickListener(this);
v.findViewById(R.id.mem_btnCancel).setOnClickListener(this);
memname=(EditText) v.findViewById(R.id.mem_name);
datasource = new PBDataSource(getActivity());
return v;
}
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.insertrecord("Members","Mem_Name", memname.getText().toString());
datasource.close();
Toast.makeText(getActivity(), "Добавлено", Toast.LENGTH_SHORT).show();
default:
dismiss();}
}
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}}
Of course, I'm a noob. I try to study myself as I can. And I hope it will help someone like me.
It seems that SQLiteOpenHelper need pass Context parameter when I create a object, so I pass PublicPar.myContext=getApplicationContext() in Main (extends Activity).
But in IntentService, there isn't UI, and there isn't Activity, maybe I can't use getApplicationContext(). How can I operate SQLite when I use IntentService?
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
PublicPar.myContext=getApplicationContext();
RuleMain dBMainHelper=new RuleMain(PublicPar.myContext);
return dBMainHelper.ListAllRuleMain();
...
}
}
Helper:
package dal;
import java.util.ArrayList;
import java.util.List;
import model.MPublicPar.IncomingType;
import model.MRule;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class RuleMain extends SQLiteOpenHelper {
private final static String DBName="smsforwardrulemain.db";
private final static String TableRuleMain="rulemain";
public RuleMain(Context context) {
super(context, DBName, null, DBPublicPar.DBVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "Create table "
+ TableRuleMain
+ " (ruleID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "enabled INTEGER NOT NULL,"
+ "incomingType INTEGER NOT NULL,"
+ "name TEXT NOT NULL"
+ ");";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String sql=" DROP TABLE IF EXISTS "+TableRuleMain;
db.execSQL(sql);
onCreate(db);
}
public List<MRule> ListAllRuleMain(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+TableRuleMain, null);
List<MRule> myRuleMainList=GetMRuleListFromCursor(cursor);
cursor.close();
db.close();
return myRuleMainList;
}
}