سؤال

What is the best way to implement a ListFragment using SQLite database. Currently I have created an DBAdapter to facilitate opening, closing, and fetching records into a SimpleCursorAdapter. I have my MainActivity which implements an ActionBar with Navigation Tabs which I would like to display a different ListView for each tab.

Here is my ListFragment:

public class MaterialsListFragment extends ListFragment {

public DBAdapter db;   

@Override
public View onCreateView(LayoutInflater inflater, 
ViewGroup container, Bundle savedInstanceState) { 


    return inflater.inflate(R.layout.portrait_material_view, container, false);
}

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

    // create new DBAdapter
    db = new DBAdapter(getActivity());
    db.open();

    Cursor c = db.getAllRecords();

    String[] from = new String[] { DBAdapter.KEY_IDNO, DBAdapter.KEY_MATERIAL };
    int[] to = new int[] { R.id.idno, R.id.materials };        

    // Now create an array adapter and set it to display using our row
    MyListAdapter materials = new MyListAdapter(this, R.layout.list_cell, c, from, to);
    setListAdapter(materials);
 }

Here is MyListAdapter code which for now is in it's own class file:

public class MyListAdapter extends SimpleCursorAdapter {

    public MyListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) {
        super(context, layout , cursor, from, to);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        // Create the idno textview with background image
        TextView idno = (TextView) view.findViewById(R.id.idno);
        idno.setText(cursor.getSring(3));

        // create the material textview
        TextView materials = (TextView) view.findViewById(R.id.materials);
        materials.setText(cursor.getString(1));
    }
}

Is this the way to go about this? I would appreciate any suggestion you may have or if you know of any good examples.

هل كانت مفيدة؟

المحلول

I was able to get this to work, so I think I'm on the right track. I had to make this modification to get it to run, but it seems to be working well.

      MyListAdapter materials = new MyListAdapter(getActivity(), R.layout.list_cell, c, from, to);

I would still be interested in any suggestions or ways to improve this approach.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top