Reputation: 1233
The code is for android but the question is related to Java I have a derived class I want to create list and pass to the super constructor while mantaining the reference in the child class
This code below is what I actualy want to do
public class AccountListAdapter extends ArrayAdapter<Account> {
private List<Account> cuentas;
private Context context;
private AccountListStore loginstore;
public AccountListAdapter(Context context) {
loginstore = new AccountListStore(context);
try {
cuentas = loginstore.getAccounts();
} catch (SQLException e) {
cuentas = new ArrayList<>();
e.printStackTrace();
}
//What I wana but I know is not posible
super(context, R.layout.acount_listadapter, cuentas);
}
Upvotes: 2
Views: 71
Reputation: 32980
I guess the answer of @spa already saves your problem. But there are cases where you need to construct a super constructor argument, but the super class does not give you access to that value.
You can solve this by creating a static helper method to construct the argument value and a second private constructor which you invoke from the public one:
public class AccountListAdapter extends ArrayAdapter<Account> {
private List<Account> cuentas;
private Context context;
private static List<Account> createCuentas(Context context)
{
AccountListStore loginstore = new AccountListStore(context);
try {
return loginstore.getAccounts();
} catch (SQLException e) {
e.printStackTrace();
return new ArrayList<>();
}
}
public AccountListAdapter(Context context) {
this(context, createCuentas(context));
}
private AccountListAdapter(Context context, List<Account> cuentas) {
super(context, R.layout.acount_listadapter, cuentas);
this.cuentas = cuentas;
}
}
Upvotes: 6
Reputation: 5185
Super has to be called first in a constructor. I would do sth. like this:
public class AccountListAdapter extends ArrayAdapter<Account> {
private List<Account> cuentas;
private Context context;
private AccountListStore loginstore;
public AccountListAdapter(Context context) {
super(context, R.layout.acount_listadapter, new ArrayList());
this.loginstore = new AccountListStore(context);
try {
this.cuentas = loginstore.getAccounts();
} catch (SQLException e) {
this.cuentas = new ArrayList<>();
e.printStackTrace();
}
this.addAll(cuentas);
}
The only issue with that might be that ArrayAdapter
works on a copy of the list. That can mean that when you adapt cuentas
it might not reflect in the backing list of the adapter.
Upvotes: 2