简体   繁体   中英

unable to create sqlite database in Android

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 .

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.

您需要将有效上下文作为参数传递:

CreateDB dbhelp = new CreateDB(getContext());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM