Reputation: 41
I have an app with lots of activities and almost on each I am creating a table filling with sqlite data like this:
if (cursor != null) {
cursor.moveToFirst();
TextView data;
TableRow row;
int cnt = 0 ;
do {
row = new TableRow(myActivity.this);
row.setPadding(2,2,2,2);
if (cnt++ % 2 == 0)
row.setBackgroundColor(Color.WHITE);
for (int x = 0; x < cursor.getColumnCount(); x++) {
// arReport[i] += cursor.getString(x);
data = new TextView(myActivity.this);
if (x == 0) {
data.setTypeface(Typeface.DEFAULT_BOLD);
data.setGravity(Gravity.CENTER_HORIZONTAL);
}
data.setText(cursor.getString(x));
row.addView(data);
}
theView.addView(row);
} while (cursor.moveToNext());
theView.setShrinkAllColumns(true);
theView.setStretchAllColumns(true);
}
So I wanted to create a separate class with static method drawTable() which will create this table in each activity on call. However I need to pass activity name as a parameter to that method so I can do row = new TableRow(myActivity.this).. I was trying to replace myActivity.this with getActivity() or just this -- it didnt work. Please suggest what should I use to do that...
Upvotes: 0
Views: 912
Reputation: 343
You could create the separate class and pass your activity's context in the constructor
public class DbHadler {
Context context;
public DbHandler(Context context) {
this.context= context;
}
public void drawTable(Activity activity) {
//relevent code
Table row;
row = new Table(activity);
}
And then use this class in your activity like this
DbHandler db = new DbHandler(getApplicationContext());
or if fragment then,
DbHandler db = new DbHandler(getContext());
And then its method in your activity like this.
db.drawTable(this);
or if fragment then,
db.drawTable(getActivity());
Upvotes: 2