Android Sqlite Database Setup Issue - android

Hey Folks am making a simple application in which ill insert two accounts manually into a table for the login authentication and then after that ill do some working based on the accounts type. Am having issues in setting up Sqlite functions. I have one package com.example.emp_management and in it i have 2 classes MainActivity.java and Database_Wrap.java. Code for the Database_Wrap.java is given below:
package com.example.emp_management;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database_Wrap //hotornot
{
public static final String Database_name = "Employee_Managament_System";
public Sql_Lite_Work OurHelper;
public final Context OurContext;
public SQLiteDatabase ourDatabase;
public static class Sql_Lite_Work extends SQLiteOpenHelper
{ //dbhelper = sql_lite_work
public Sql_Lite_Work(Context context)
{
super(context,Database_name , null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE" + "Login_Authentication"+ "(" +
"ID" + "INTEGER PRIMARY KEY AUTOINCREMENT, " +
"UserName" + "TEXT NOT NULL," +
"Password" + "TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + "Login_Authentication");
onCreate(db);
}
}
public Database_Wrap(Context c)
{
OurContext = c;
}
public Database_Wrap Open()
{
OurHelper = new Sql_Lite_Work(OurContext);
ourDatabase = OurHelper.getWritableDatabase();
return this;
}
public void close()
{
OurHelper.close();
}
}
Now next thing i want to do is in my mainactivity i want to do something like:
Database_Wrap entry= new Database_Wrap(MainActivity.this);
and then acces the function written in Database_Wrap to open the database and write the values into table for admin and other users:
entry.Open();
but in eclipse am not able to access open function on entry. I dnt know what is wrong here. Am a beginer. May be am forgetting something. Kindly have a look thankyou!

Java is case sensitive. Try:
Database_Wrap entry= new Database_Wrap(MainActivity.this);
Both your ws in Wrap were lower case.

I just put your code into a small test project. It compiles just fine. I then added this code, in an Activity in the same project:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database_Wrap entry= new Database_Wrap(MainActivity.this);
entry.Open();
}
That too, works just fine.
Judging by the appearance of the code (nothing at all wrong with it, just that the style makes experienced Java devs cringe), you are new to Java; probably eclipse too. Eclipse is weird and does funky stuff all the time. Perhaps you've just encountered some short term anomaly.

Related

SQLite Database Locked in DialogFragment onClick event

People say that it may be caused when you don't close cursor or database. But I have something strange.
I try to open database on OK button click in a dialogfragment window (resultClass) in MainActivity in the beginning of app.
The method that calls DialogFragment window
#SuppressLint("NewApi")
public void vasya(View v){
DialogFragment dlg_rec=new resultClass();
dlg_rec.show(getFragmentManager(), "dlg_rec");}
in my DialogFragment class
public Score_DS dsoop=new Score_DS(getActivity());
..
case R.id.button1:
dsoop.open();// Here comes the crash
...
dsoop.close();
Score_DS is my DataSource class to operate with database.
public class Score_DS {
ContentValues cv= new ContentValues();
DB dbHelper;
SQLiteDatabase db;
public Score_DS(Context context) {
dbHelper = new DB(context);
}
public void open() throws SQLException {
if (dbHelper != null) {
db = dbHelper.getWritableDatabase();
}
}
...
(here I have a couple of methods that I've never called yet)
}
DB.java is this
package com.wordpress.jimmaru.tutorial.SimpleGame;
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 = "mygame.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 Records(_id INTEGER PRIMARY KEY, Player_Name VARCHAR(50), Player_Score VARCHAR(50));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
// TODO Auto-generated method stub
}
}
So, again. I call DialogFragment window in the very beginning of my app by clicking on a button. When I click on OK button in my dialogfragment window, the app crashes and shows that Database is locked. I closed everything (db.close). I have no cursors opened. in MainActivity I have another database related method.
Score_DS dseed=new Score_DS(this);
...
public void clearall(View v)
{
dseed.open();
dseed.execution("DELETE FROM Records");
dseed.close();
}
And it works just fine.
What can be wrong?
It's not "database is locked" but rather NullPointerException in getDatabaseLocked(). It is caused because you passed a null Context to SQLiteOpenHelper here:
public Score_DS dsoop=new Score_DS(getActivity());
When the fragment object is instantiated, it's not yet attached to an activity and getActivity() returns null. Postpone the Score_DS instantiation to e.g. onAttach() or later in the fragment lifecycle.

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 (:

SQLite database handling with android application

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

Categories

Resources