Initializing a Loader in an Activity

d.mc2 picture d.mc2 · Mar 29, 2012 · Viewed 26.4k times · Source

I am currently trying to learn how to use Loaders and am having trouble starting a Loader in my activity.

import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;

public class ASwitchActivity extends Activity implements 
             LoaderManager.LoaderCallbacks<SampleLoader.SampleLoaderResult> {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getLoaderManager().initLoader(0, null, this);
    }

    public Loader<SampleLoader.SampleLoaderResult> onCreateLoader(int id, Bundle args) {
      return new SampleLoader(getBaseContext(), account, "dog");
}

  public void onLoadFinished(Loader<SampleLoader.SampleLoaderResult> loader, SampleLoader.SampleLoaderResult out)
  {
      TextView t=(TextView)findViewById(R.id.testTV);
      t.setText("yay");
  }

  public void onLoaderReset(Loader<SampleLoader.SampleLoaderResult> loader){

  }
}   

However Eclipse gives an error stating:

The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, ActivitySwitchActivity)

Can anyone help with where I am going wrong?

Answer

mig35 picture mig35 · Mar 29, 2012

As I can see you use supportV4 library. So to implement Loader you should do some things:

  1. extend your activity from FragmentActivity class
  2. Use getSupportLoaderManager method instead of getLoaderManager

here is sample code:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.widget.Toast;

public class MyActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Object> {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getSupportLoaderManager().initLoader(0, null, this);
}

@Override
public Loader<Object> onCreateLoader(int i, Bundle bundle){
    return null; // TODO
}

@Override
public void onLoadFinished(Loader loader, Object o) {
    Toast.makeText(this, "onLoadFinished", Toast.LENGTH_SHORT).show();
}

@Override
public void onLoaderReset(Loader loader)    {
    Toast.makeText(this, "onLoaderReset", Toast.LENGTH_SHORT).show();
}
}