我正致力于通过手机接听联系人,为此我使用LoaderCallbacks<Cursor>
我创建了一个名为FetchContacts
的新班级并实施loaderManager
。现在我想要在创建该类的对象时自动初始化
的 FetchContacts
public class FetchContacts implements LoaderManager.LoaderCallbacks<Cursor> {
private Context context;
FetchContacts(Context ctx){
context = ctx;
getLoaderManager().initLoader(0, null, this); // Error: Undefined method
}
// Reset of code like override methods.
MainActivity
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FetchContacts fetchContacts = new FetchContacts(this);
}
}
我知道错误的原因,因为FetchContacts
未从Activity类扩展。是否有必要从Activity类扩展它,还是有其他方法从MainActivity中调用它?
答案 0 :(得分:6)
将LoaderManager
作为参数传递给@Mike说。
<强> FetchContacts 强>
public class FetchContacts implements LoaderManager.LoaderCallbacks<Cursor> {
private Context context;
FetchContacts(Context ctx, LoaderManager loaderManager){
context = ctx;
loaderManager.initLoader(0, null, this);
}
// Reset of code like override methods.
<强> MainActivity 强>
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FetchContacts fetchContacts = new FetchContacts(this, getLoaderManager());
}
}