0

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 .

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so how can i initialize Context context and with what
When you're calling the asynctask in your activity, you can pass the activity itself as argument(with this), like I did in the constructor.
0

You need to pass valid context as a parameter:

CreateDB dbhelp = new CreateDB(getContext());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.