我有一个利用我创建的Database类的Fragment。我有一个名为populateListView()的方法,它使用CursorAdapter用数据填充ListView。我的问题是我不断收到语法错误,指出' CursorAdapter是抽象的,无法实例化'。在Activity中使用此代码时我没有遇到任何问题,但它不能在片段中工作。有人知道为什么吗?
以下是我片段中的代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contacts_fragments, container, false);
inputName = (EditText)view.findViewById(R.id.inputName);
inputNumber = (EditText)view.findViewById(R.id.inputNumber);
inputEmail = (EditText)view.findViewById(R.id.inputEmail);
saveButton = (Button)view.findViewById(R.id.saveButton);
deleteAllButton = (Button)view.findViewById(R.id.deleteAllButton);
openDB();
populateListView();
return view;
}
private void openDB(){
myDB = new DBAdapter(getActivity());
myDB.open();
}
public void populateListView(){
View view = getView();
Cursor cursor = myDB.getAllRows();
String[] fromFieldNames = new String[] {DBAdapter.KEY_NAME,DBAdapter.KEY_NUMBER,DBAdapter.KEY_EMAIL};
int[] toViewIDs = new int[] {R.id.customRowContactName,R.id.customRowContactNumber,R.id.customRowRowEmail};
CursorAdapter cursorAdapter;
//***SYNTAX ERROR WITH FOLLOWING LINE***
cursorAdapter = new CursorAdapter(getActivity(),R.layout.contacts_custom_row,cursor,fromFieldNames,toViewIDs);
myList = (ListView)view.findViewById(R.id.listView);
myList.setAdapter(cursorAdapter);
}
答案 0 :(得分:2)
CursorAdapter
是一个抽象类,意味着它无法实例化。
在您的活动中,您可能正在使用SimpleCursorAdapter
,因为您的构造函数参数符合其要求,或者您可能正在使用自己的CursorAdapter
实现。
如果Fragment
已经使用了Activity
,则其中任何一个都可以在cursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.contacts_custom_row,
cursor, fromFieldNames, toViewIDs);
中使用。
EditText payable;
Button calculate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText salary = (EditText) findViewById(R.id.edit_salary);
EditText allowance = (EditText) findViewById(R.id.edit_allowance);
EditText incomeTax = (EditText) findViewById(R.id.IncTax_edit);
EditText payable = (EditText) findViewById(R.id.payable_edit);
EditText totalTax = (EditText) findViewById(R.id.deduction_edit);
Button calculate = (Button) findViewById(R.id.calculate_button);
if(salary.getText().toString().length()>0)
{
double realSalary=Double.parseDouble(salary.getText().toString());
}
if(allowance.getText().toString().length()>0)
{
double realAllowance = Double.parseDouble(allowance.getText().toString());
}