Search code examples
androidlistviewandroid-cursorloader

How to use a LoaderManager and a CursorLoader inside an OnClickItemListener of an Android ListView


I have a simple (?) Android application that begins with an Activity ("First Activity") with a ListView that lists three items: Beginning, Intermediate and Advanced. So far, so good. What I want to happen next is if the user clicks on e.g. Beginning, a SQLite database will be queried and all items designated "Beginning" in the database will be retrieved. I then want a second Activity ("Second Activity") to launch and have all the items from the query displayed in a ListView on that Activity. I have this working using a cursor, but I'm trying to update my code to use a LoaderManager and a CursorLoader. I think that I need to put an onCreateLoader method inside the ListView's onItemClick method in the First Activity. To give an example, I'm thinking of code like this:

public class FirstActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {
    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView listview = getListView();
    String[] values = new String[] {
            "Beginning", "Intermediate", "Advanced"
    };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(this, <myUri>,
            <myFields>, <myQuery>, null, null); 
}               
        }

    });
}

}

Also in my onClickItem, I'm going to create an Intent and stuff it with a Bundle of data (my Second Activity's ListView will need this data for its onItemClick method). Anyway, when I try this, Eclipse is unhappy with the onCreateLoader inside the onItemClick, giving me lots of error messages about mismatched curly braces, missing semi-colons, etc. So what am I doing wrong? How do I query my database when a listitem is clicked? If I move the onCreateLoader method outside of the onItemClick method, but within the setItemClickListener, I don't get error messages, but then how do I reference it within my onItemClick method?

Any help is greatly appreciated. Many thanks in advance!


Thanks very much for both answers! I'm an Android newbie; I'm trying to implement your suggestions and am stuck once again. I created a new Activity called GetLevelData. My first activity now looks like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView listview = getListView();
    final String[] values = new String[] {
            "Beginning", "Intermediate", "Advanced"
    };

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            Intent choice = new Intent(getApplicationContext(), com.MyProject.project.GetLevelData.class);
            Bundle dataBundle = new Bundle();
            String chosenValue = values[position];
            dataBundle.putString("Level",chosenValue);
            choice.putExtras(dataBundle);
            try {
                startActivity(choice);
            } catch (Exception e) {
                Dialog d = new Dialog(getApplicationContext());
                d.setTitle("MyProjectActivity line 60");
                TextView tv = new TextView(getApplicationContext());
                tv.setText(e.toString());
                d.setContentView(tv);
                d.show();
            } finally {

            }
        }

    });
}

My new Activity looks like this:

public class GetLevelData extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.leveldata);

    Intent myData = getIntent();
    Bundle info = myData.getExtras();

    if (info != null){
        TextView myTextView = (TextView)findViewById(R.id.textView1);
        String level = info.getString("Level");
        myTextView.setText(level);
    }
}

}

textView1 is a TextView inside a LinearLayout in leveldata.xml in my layout folder. When I try to run this, at startActivity, I get an exception: Activity not found. What am I missing? I'


Solution

  • To make it simpler pass the choice to the second activity, not the cursor. Also CursorLoader is for content handlers not for general cursors. Last time I did something like this I believe I inherited AsyncTaskLoader.

    Thus, pass the choice in an extra in the intent, and let the second activity do the query.