从不是Activity的类调用LoaderManager

时间:2017-02-19 06:25:21

标签: android android-loadermanager

我正致力于通过手机接听联系人,为此我使用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中调用它?

1 个答案:

答案 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());
       }
     }