如何在 Android 中的自定义 dapter 类中使用或实例化 Sqlite Database Helper 类实例? [英] How to use or instantiate Sqlite Database Helper class instance inside a custom dapter class in Android?

查看:25
本文介绍了如何在 Android 中的自定义 dapter 类中使用或实例化 Sqlite Database Helper 类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am absolute beginner to Android. Now I am creating a tutorial project. In my project I am using ListView with custom adapter. But I created the custom adapter as a different and standalone file to make my activity clean. But when I create it in a different file, I cannot use my database helper class inside the custom adapter.

问题是我无法将 Activity 上下文传递给数据库助手类实例.在片段中,我可以通过调用这个method.getActivity().然后将它传递给我的数据库助手类的构造函数.如何在我的自定义适配器类中做同样的事情?

The problem is I cannot pass the Activity context to the database helper class instance. In fragment, I can pass by calling this method.getActivity(). Then pass it to the constructor of my database helper class. How can I do the same thing in my custom adapter class?

这是我的数据库助手类:

This is my database helper class:

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);
    } 
}

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

This is my custom adapter class for listView (TaskListAdapter.java):

public class TaskListAdapter extends ArrayAdapter<Task> {
    private final Context context;
    private final ArrayList<Task> values;
    private DatabaseHelper dbHelper;
    public TaskListAdapter(Context context,ArrayList<Task> values)
    {
        super(context,-1,values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position,View convertView,ViewGroup parent)
    {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView  = inflater.inflate(R.layout.task_list_row,parent, false);
        rowView.setTag(values.get(position).getId());
        TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
        rowDescription.setText(values.get(position).getDescription());
        ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);

        Long currentDateMillSec= System.currentTimeMillis();
        Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
        if(values.get(position).getDone()==Boolean.TRUE)
        {
           rowStatusIcon.setImageResource(R.drawable.done_icon);
        }
        else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
        {
           rowStatusIcon.setImageResource(R.drawable.failed_icon);
        }
        else{
            rowStatusIcon.setImageResource(R.drawable.todo_icon);
        }


        TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
        dateTf.setText(values.get(position).getDate());

        Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
        doneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //how can I instantiate the dbHelper class
                //Then use the merkAsDone method here
            }
        });
        return rowView;
    }


}

如何在我的自定义适配器中实例化 dbHelper 属性,然后在完成按钮单击事件中调用 markAsDone 方法.在 Activity 中未创建适配器的情况下,如何实现它?

How can I instantiate the dbHelper property in my custom adapter and then call the markAsDone method in the done button click event. How can I achieve it whereas the adapter is not created within Activity?

推荐答案

看起来问题不大,在你的构造函数中实例化:

Does not look like a big problem, instantiate it in your constructor:

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

然后在您的 OnClickListener 中使用它:

Then use it in your 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

这篇关于如何在 Android 中的自定义 dapter 类中使用或实例化 Sqlite Database Helper 类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆