Reputation: 5
i have class CreateDB
public class CreateDB extends SQLiteOpenHelper{ // SQLiteOpenHelper auto create if db not exists.
private static final int DB_VERSION = 1;
private static final String DB_NAME = "mydb.db";
public CreateDB(Context ctx) {
super(ctx, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE friends (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phonenumber INTEGER);");
}}
i call createdb in another class which act as background thread
public class manager extends AsyncTask<Void, Void, String> {
public Context context;
@Override
protected String doInBackground(Void... params) {
CreateDB dbhelp = new CreateDB(context);
}
}
when i run it then it stop working and emulator give error that app stop responding
but when i run `CreateDB dbhelp = new CreateDB(this); in main activity then it works and database is created . so please help so that i can create database in background thread .
Upvotes: 0
Views: 794
Reputation: 93842
but when i run
CreateDB dbhelp = new CreateDB(this);
in main activity then it works and database is created
Because you forgot to initialize your context
object in your AsyncTask
.
public class manager extends AsyncTask<Void, Void, String> {
public Context context; <-- Declared but not initialized
@Override
protected String doInBackground(Void... params) {
CreateDB dbhelp = new CreateDB(context);
}
You could create a constructor for your AsyncTask :
public manager(Context context) {
this.context = context;
}
And then in your activity :
new manager(this).execute();
Also try to respect name conventions.
Upvotes: 2
Reputation: 708
You need to pass valid context as a parameter:
CreateDB dbhelp = new CreateDB(getContext());
Upvotes: 0