资产/ example.sqlite的listview

时间:2015-09-03 09:25:02

标签: java android android-listview

我想从现有数据库生成列表视图。我已经浏览了几个会在运行时创建数据库的网站,但我不希望它那样。我想要的是从现有数据库中读取数据库,并从中填充listview。我是android开发的新手。

My database path .
assets/databases/example.sqlite

1 个答案:

答案 0 :(得分:0)

检查此库:SQLiteAssetHelper。 这是一个有效的例子:

public class MyDataBase extends SQLiteAssetHelper {
private static final String TAG = "MyDataBase.class";
private static final String DATABASE_NAME = "news.sqlite";
private static final int DATABASE_VERSION = 1;
//Table Fields
private static final String ITEM_TITLE = "title";
private static final String ITEM_DESCRIPTION = "description";
private static final String ITEM_CATEGORY = "category";
private static final String ITEM_PUBDATE = "pubDate";
private static final String ITEM_CREATOR = "creator";
private static final String ITEM_URL = "url";
private static final String ITEM_IMAGE_URI = "image_uri";
private static final String ITEM_IMAGE_PATH = "image_path";
//Table name
private static final String TABLE = "Item";
public MyDataBase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//getting Items from database
public ArrayList<Item> getItems(){
    ArrayList<Item> items=new ArrayList<>();
    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String [] sqlSelect = {"id", ITEM_TITLE, ITEM_DESCRIPTION, ITEM_CATEGORY, ITEM_PUBDATE,
            ITEM_CREATOR, ITEM_URL, ITEM_IMAGE_URI, ITEM_IMAGE_PATH  };
    String sqlTables = TABLE;
    qb.setTables(sqlTables);
    Cursor c = qb.query(db, sqlSelect, null, null,
            null, null, null);

    if (c.moveToFirst()) {
        do {

            Item item = new Item();
            item.setTitle(c.getString(c.getColumnIndex(ITEM_TITLE)));
            item.setCategory(c.getString(c.getColumnIndex(ITEM_CATEGORY)));
            item.setDescription(c.getString(c.getColumnIndex(ITEM_DESCRIPTION)));
            item.setPubDate(c.getString(c.getColumnIndex(ITEM_PUBDATE)));
            item.setCreator(c.getString(c.getColumnIndex(ITEM_CREATOR)));
            item.setURL(c.getString(c.getColumnIndex(ITEM_URL)));
            item.setImage_uri(c.getString(c.getColumnIndex(ITEM_IMAGE_URI)));
            item.setImage_path(c.getString(c.getColumnIndex(ITEM_IMAGE_PATH)));
            items.add(item);
        } while (c.moveToNext());
    }
    Log.i(TAG, "getItems() completed");
    c.close();
    db.close();
    return items;
}

现在异步从DB获取数据:

private class DbTask extends AsyncTask<Void, Void, Void> {


    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Void doInBackground(Void... params) {

            MyDataBase db = new MyDataBase(context);
            list.clear();
            list.addAll(db.getItems());

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        adapter.notifyDataSetChanged();

    }

希望这个答案对你有用。 快乐的编码!