Reputation: 308
when I extend my DatabaseClass with SQLiteOpenHelper class I have to implement constructor which must contains Context in its parameter. If I have to use this databases with my Other classes context maybe changed. What changes are done when I provide different context.
public class DatabaseClass extends SQLiteOpenHelper {
static String TABLE_NAME = "hammad";
static String DATABASE_NAME = "databases.db";
SQLiteDatabase database;
public DatabaseClass(Context context) {
super(context, DATABASE_NAME, null, 1);
Log.i("xcv", "Constructor called");
this.database = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
Log.i("xcv", "OnCreate");
try {
sqLiteDatabase.execSQL("create table student (id integer primary key autoincrement,name varchar)");
Log.i("xcv", "On Create query Table created");
} catch (Exception ffff) {
Log.i("xcv", "2:"+ffff.getMessage());
}
}
StartPage.java
public class StartPage extends AppCompatActivity {
DatabaseClass database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_page);
setLoginBtn(); // Set Login Btn
database=new DatabaseClass(this);
}
}
Class2.java
public class Class2 extends AppCompatActivity {
DatabaseClass database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_page);
setLoginBtn(); // Set Login Btn
database=new DatabaseClass(this);
}
}
Upvotes: 0
Views: 1184
Reputation: 152827
SQLiteOpenHelper
uses the Context
passed in to find your application package-private data directory where the database files are located. The package is the package
declared in your app's AndroidManifest.xml
, not the Java package of your class files.
All Context
s in your application have the same package-private data directory and the database will work just fine with any valid Context
.
Upvotes: 0
Reputation: 2810
"Context may be changed" You should be first clear about this line... Yes context will be changed every time you create new instance of database by calling from different class and it has to change.... Bcoz context is the one that states this activity has the permision to access the database.... So when you pass "this"
of xyz activity then that xyz has permission to access data and modify data in the database... It is like showing an ID card to database before taking control over its resources....
Also you can access your database from any class by passing the context, you can retrieve data, modify data and close connection...
Scenario :
Its like single fridge in a home you can open n only see whats in it.. You can take out something and eat it... Or you can place in something... And samething can be done by any of the family members... While "this"
or "context"
is the individual person
Upvotes: 2