如何在Android中的自定义dapter类中使用或实例化Sqlite Database Helper类实例?

时间:2016-01-26 07:40:53

标签: java android sqlite

我绝对是Android的初学者。现在我正在创建一个教程项目。在我的项目中,我使用ListView和自定义适配器。但我创建了自定义适配器作为一个不同的独立文件,使我的活动干净。但是当我在另一个文件中创建它时,我无法在自定义适配器中使用我的数据库帮助程序类。

问题是我无法将Activity上下文传递给数据库助手类实例。在片段中,我可以通过调用此Cliente* cola; int main(int argc, char** argv) { if (argc < 2) { perror("First arg indicates thread numbers and is required"); } int thread_count = atoi(argv[1]); cola = malloc(sizeof(*cola) * thread_count); ... // Extend cola size without losing previous data cola = realloc(cola, sizeof(*cola) * (thread_count + x)); } 来传递。然后将它传递给我的数据库助手类的构造函数。如何在自定义适配器类中执行相同的操作?

这是我的数据库助手类:

method.getActivity()

这是我的listView(TaskListAdapter.java)的自定义适配器类:

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "todo.db";
    private static final String TABLE_NAME = "task";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_DESCRIPTION = "description";
    private static final String COLUMN_DATE ="date";
    private static final String COLUMN_DONE = "done";
    private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COLUMN_DESCRIPTION+" TEXT,"+
    COLUMN_DATE+" DATE,"+COLUMN_DONE+" BOOLEAN)";
    SQLiteDatabase db;

    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db)
    {
        this.db = db;
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
        db.execSQL(query);
        this.onCreate(db);
    }

    public  void insertTask(Task task)
    {
        db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_DESCRIPTION,task.getDescription());
        values.put(COLUMN_DATE,task.getDate());
        values.put(COLUMN_DONE, Boolean.FALSE.toString());
        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public ArrayList<Task> getAllTasks()
    {
        ArrayList<Task> items = new ArrayList<Task>();
        db = getReadableDatabase();
        String query = "SELECT * FROM "+TABLE_NAME;
        Cursor cursor = db.rawQuery(query,null);
        if(cursor.moveToFirst())
        {
            do{
                Task item = new Task();
                item.setId(cursor.getInt(0));
                item.setDescription(cursor.getString(1));
                item.setDate(cursor.getString(2));
                item.setDone(Boolean.valueOf(cursor.getString(3)));
                items.add(item);
            }
            while (cursor.moveToNext());
        }
        return items;
    }

    public void markAsDone(int id){
        db = getWritableDatabase();
        ContentValues updatedData = new ContentValues();
        updatedData.put(COLUMN_DONE, String.valueOf(Boolean.TRUE));
        String where = COLUMN_ID+" = "+String.valueOf(id);
        db.update(TABLE_NAME,updatedData,where,null);
    } 
}

如何在自定义适配器中实例化dbHelper属性,然后在完成按钮单击事件中调用markAsDone方法。如何在Activity中创建适配器?

3 个答案:

答案 0 :(得分:2)

看起来不是一个大问题,在构造函数中实例化它:

public TaskListAdapter(Context context,ArrayList<Task> values)
{
    super(context,-1,values);
    this.dbHelper = new DatabaseHelper(context.getApplicationContext());
    this.context = context;
    this.values = values;
}

然后在OnClickListener中使用它:

Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setTag(values.get(position).getId());
doneBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        dbHelper.markAsDone(v.getTag());
    }
});

请勿忘记在DatabaseHelper.markAsDone

中关闭数据库

答案 1 :(得分:0)

首先,如果你想在适配器中使用db,你可以使用CursorAdapter而不是ArrayAdapter,

如果你想留在arrayAdapter上,那么你可以在construcor

中传递db对象

答案 2 :(得分:0)

您应该将DatabaseHelper类设置为线程安全Singleton,然后从适配器获取该实例。

public class DatabaseHelper extends SQLiteOpenHelper{
     private static DatabaseHelper dbHelper;

    public static DatabaseHelper getInstance() {
        if(dbHelper == null)
        {
            synchronized (DatabaseHelper.class)
            {
                if(dbHelper == null)
                {
                    dbHelper = new DatabaseHelper(MyApplicationInstance.getAppContext());
                }
            }
        }

        return dbHelper;
    }

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
}

然后在CustomAdapter中执行您的命令DatabaseHelper.getInstance().insert()

希望这有帮助。