How To Use Or Instantiate Sqlite Database Helper Class Instance Inside A Custom Dapter Class In Android?
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
Solution 1:
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;
}
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());
    }
});
Don't forget to close your Database in DatabaseHelper.markAsDone
Solution 2:
Firstly if you want to use the db inside the adapter , you can use CursorAdapter not ArrayAdapter ,
if you want to stay on arrayAdapter , then you can pass th db Object in the construcor
Solution 3:
You should make the DatabaseHelper class as thread-safe Singleton and then get that instance from the adapter. 
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);
    }
}
And then in the CustomAdapter just execute your commands as DatabaseHelper.getInstance().insert()
Hope this helps.
Post a Comment for "How To Use Or Instantiate Sqlite Database Helper Class Instance Inside A Custom Dapter Class In Android?"