Search code examples
androidsqliteandroid-listfragmentlistactivity

How to convert ListActivity to ListFragment?


i have a database which i created in Sqlite database browser and using a library to use that database for populating my lists in ListActivity. now to i want to convert my ListActivity to ListFragment...

here is the code...

code for DataBaseHelper

    import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

    public class DataBaseHelper extends SQLiteAssetHelper {

    private static final String DATABASE_NAME = "dictionary.db";
    private static final int DATABASE_VERSION = 1;

    public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    public Cursor getDictionary() {

        SQLiteDatabase db = getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        String [] sqlSelect = {"0 _id", "dream_title", "dream_meaning"}; 
        String sqlTables = "dictionary";

        qb.setTables(sqlTables);
        Cursor c = qb.query(db, sqlSelect, null, null,
                null, null, null);

        c.moveToFirst();
        return c;

    }

}

code for MainActivity

public class MainActivity extends ListActivity {

    private Cursor dictionary;
    private DataBaseHelper db;

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

        db = new DataBaseHelper(this);
        dictionary = db.getDictionary(); // you would not typically call this on the main thread

        ListAdapter adapter = new SimpleCursorAdapter(this, 
                android.R.layout.simple_list_item_1, 
                dictionary, 
                new String[] {"dream_title"}, 
                new int[] {android.R.id.text1});

        getListView().setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dictionary.close();
        db.close();
    }

}

Any help will be appreciable


Solution

  • ListFragment uses setListAdapter. I think that's all you would need to change.