安卓:绑定数据从数据库的ListView [英] Android: Binding data to listview from database

查看:152
本文介绍了安卓:绑定数据从数据库的ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的SQLite数据库拉我的数据,并在列表视图显示它,这是我迄今为止,但它只会将第一个记录列表视图。
我认为,而(mCursor.moveToNext()){位需要改变,但不知道如何。原来的code,每次把每纪录一个TextView在新的一行。

 如果(mCursor == NULL){
        mCursor.close();
        Log.w(光标,空指针);
    }        mCursor.moveToFirst();
    的String [] S = NULL;
    而(mCursor.moveToNext()){        S =新的String [] {foodNameColumn,proteinColumn,fatColumn,carbsColumn};        mCursor.moveToNext();
    }
    SimpleCursorAdapter适配器=新SimpleCursorAdapter(这一点,
            R.layout.aa_four_column,
            mCursor,
            S,
            新的INT [] {R.id.txtCol1,R.id.txtCol2,R.id.txtCol3,R.id.txtCol4},0);    lvDB.setAdapter(适配器);

更新:

我已经改变了它,只有这code是在onCreate方法,但同样的事情发生,一个项目显示,当有在DB多的东西。

  mCursor = dataBase.select(SELECT * FROM+ TABLE_NAME);        SimpleCursorAdapter适配器=新SimpleCursorAdapter(这一点,
                    R.layout.aa_four_column,
                    mCursor,
                    新的String [] {foodNameColumn,proteinColumn,fatColumn,carbsColumn},
                    新的INT [] {R.id.txtCol1,R.id.txtCol2,R.id.txtCol3,R.id.txtCol4},0);        lvDB.setAdapter(适配器);aa_column_four.xml
< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:方向=横向>    <的TextView
        机器人:ID =@ + ID / txtCol1
        机器人:layout_width =181dp
        机器人:layout_height =WRAP_CONTENT
        机器人:文字=1列文将结束在这里! />    <的TextView
        机器人:ID =@ + ID / txtCol2
        机器人:layout_width =63dp
        机器人:layout_height =WRAP_CONTENT
        机器人:文字=2列文将结束在这里! />    <的TextView
        机器人:ID =@ + ID / txtCol3
        机器人:layout_width =96dp
        机器人:layout_height =WRAP_CONTENT
        机器人:文字=列3文本最终会在这里! />    <的TextView
        机器人:ID =@ + ID / txtCol4
        机器人:layout_width =104dp
        机器人:layout_height =WRAP_CONTENT
        机器人:文字=4列文将结束在这里! />< / LinearLayout中>

DatabaseManager类

 公共类的DatabaseManager扩展SQLiteOpenHelper {    //你的项目的主要包
    私人静态字符串DB_PATH =/data/data/com.example.activities/databases/;    //你的数据库的名称
    私人静态字符串DB_NAME =DB_Nutrition;    私有静态SQLiteDatabase mDataBase;    私有静态的DatabaseManager sInstance = NULL;
    //数据库版本
    私有静态最终诠释DATABASE_VERSION = 1;    / **
     *构造函数和不断传递的上下文中的一个参考,以
     *访问应用程序的资产和资源。
     * /
    的DatabaseManager(){
        超(ApplicationContextProvider.getContext(),DB_NAME,空,DATABASE_VERSION);        尝试{
            的CreateDatabase();
            的openDatabase();
        }赶上(IOException异常五){
            e.printStackTrace();
        }    }    / **
     *对于数据库辛格尔顿
     *
     返回:单实例
     * /
    公共静态的DatabaseManager实例(){        如果(sInstance == NULL){
            sInstance =新的DatabaseManager();
        }
        返回sInstance;
    }
    / **
     *在系统上创建一个空数据库,然后用自己的重写它
     *数据库。
     *
     *抛出:java.io.IOException异常IO异常
     * /
    私人无效的CreateDatabase()抛出IOException        布尔dbExist = checkDataBase();        如果(dbExist){
            //什么也不做 - 已存在于数据库
        }其他{            //通过调用此方法一个空数据库将被创建成
            //默认的系统路径
            //你的应用程序,所以我们要能够覆盖
            //数据库与我们的数据库。
            this.getReadableDatabase();            尝试{                copyDataBase();            }赶上(IOException异常五){                抛出新的错误(错误复制数据库);
            }
        }
    }    / **
     *检查是否已存在于数据库,以避免重新复制每个文件
     *一次打开应用程序。
     *
     *如果存在返回:真的,假的,如果它不
     * /
    私人布尔checkDataBase(){        SQLiteDatabase CHECKDB = NULL;        尝试{
            字符串mypath中= DB_PATH + DB_NAME;
            CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,
                    SQLiteDatabase.OPEN_READONLY);        }赶上(SQLiteException E){            //数据库尚不存在。        }        如果(CHECKDB!= NULL){            checkDB.close();        }        返回CHECKDB!= NULL;
    }    / **
     *副本数据库从本地资产文件夹复制到刚创建
     *在系统文件夹,空数据库从那里可以访问和
     *处理。这是通过转流的字节流进行。
     *
     *抛出:java.io.IOException异常IO异常
     * /
    公共无效copyDataBase()抛出IOException        //打开本地数据库的输入流
        InputStream的myInput = ApplicationContextProvider.getContext()getAssets()开(DB_NAME)。        //路径刚刚创建的空分贝
        字符串outFileName = DB_PATH + DB_NAME;        //打开空分贝的输出流
        的OutputStream myOutput =新的FileOutputStream(outFileName);        //传递从inputfile中字节到OUTPUTFILE
        字节[]缓冲区=新的字节[1024];
        INT长;
        而((长度= myInput.read(缓冲液))大于0){
            myOutput.write(缓冲液,0,长度);
        }        //关闭流
        myOutput.flush();
        myOutput.close();
        myInput.close();    }    私人无效的openDatabase()抛出的SQLException {        //打开数据库
        字符串mypath中= DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(mypath中,空,
                SQLiteDatabase.OPEN_READWRITE);
    }    / **
     *选择方法
     *
     * @参数查询选择查询
     * @返回 - 光标的结果
     * @throws android.database.SQLException SQL异常
     * /
    公共选择光标(查询字符串)抛出的SQLException {
        返回mDataBase.rawQuery(查询,NULL);
    }    / **
     *插入法
     *
     * @参数表 - 表的名称
     * @参数值插入值
     * @throws android.database.SQLException SQL异常
     * /
    公共无效插入(字符串表,ContentValues​​值)抛出的SQLException {
        mDataBase.insert(表,空,价值);
    }    / **
     *删除方法
     *
     * @参数表 - 表名
     * @参数,其中WHERE子句,如果传递null,则所有的行都将被删除
     * @throws android.database.SQLException SQL异常
     * /
    公共无效删除(字符串表,字符串,其中)抛出的SQLException {        mDataBase.delete(表,其中,空);    }    / **
     *更新方法
     *
     * @参数表 - 表名
     * @参数值 - 值更新
     * @参数在哪里 - WHERE子句,如果传递null,所有行会被更新
     * /
    公共无效更新(字符串表,ContentValues​​值,字符串,其中){        mDataBase.update(表中,值,其中,空);    }    / **
     *让你做一个原始查询
     *
     * @参数命令 - 要运行的SQL COMAND
     * /
    公共无效的SqlCommand(字符串命令){
        mDataBase.execSQL(命令);
    }    @覆盖
    公共同步无效的close(){        如果(mDataBase!= NULL)
            mDataBase.close();        super.close();    }    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){    }    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){    }}

错误

  15 03-03:42:13.894:E / SQLiteLog(9809):(14)在30176行无法打开文件[00bb9c9ce4]
03-03 15:42:13.894:E / SQLiteLog(9809):(14)os_unix.c:30176:(2)开(/data/data/com.example.activities/databases/DB_Nutrition) -
03-03 15:42:13.904:E / SQLiteDatabase(9809):无法打开数据库'/data/data/com.example.activities/databases/DB_Nutrition。
03-03 15:42:13.904:E / SQLiteDatabase(9809):android.database.sqlite.SQLiteCantOpenDatabaseException:未知错误(code 14):无法打开数据库
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteConnection.nativeOpen(本机方法)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804​​)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在com.example.db_food.DataBaseManager.checkDataBase(DataBaseManager.java:228)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在com.example.db_food.DataBaseManager.createDataBase(DataBaseManager.java:193)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在com.example.db_food.DataBaseManager<&初始化GT;(DataBaseManager.java:163)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在com.example.db_food.DataBaseManager.instance(DataBaseManager.java:179)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在com.example.db_food.MyActivity.onCreate(MyActivity.java:63)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.app.Activity.performCreate(Activity.java:5104)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.os.Looper.loop(Looper.java:137)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在android.app.ActivityThread.main(ActivityThread.java:5041)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在java.lang.reflect.Method.invokeNative(本机方法)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在java.lang.reflect.Method.invoke(Method.java:511)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-03 15:42:13.904:E / SQLiteDatabase(9809):在dalvik.system.NativeStart.main(本机方法)


解决方案

它看起来像你想从一个ListView表中显示的数据,因此只需创建一个适配器:

  SimpleCursorAdapter适配器=新SimpleCursorAdapter(这一点,
        R.layout.aa_four_column,
        mCursor,
        新的String [] {foodNameColumn,proteinColumn,fatColumn,carbsColumn},
        新的INT [] {R.id.txtCol1,R.id.txtCol2,R.id.txtCol3,R.id.txtCol4},0);lvDB.setAdapter(适配器);

(单独使用此code,你不需要使用任何其他code以下,但你应该读得懂,为什么大部分的code不会做你正在尝试做的。)


您有几个逻辑错误。

1),如果对象是您不能引用任何方法:

 如果(mCursor == NULL){
    / * mCursor.close();这将抛出一个NullPointerException异常! * /
    Log.w(光标,空指针);
    返回;
}

2)通过调用 moveToFirst() moveToNext()前阅读排你跳过第一个记录。你还呼吁 moveToNext()两次读取记录之间,所以你只阅读每隔之一。试试这个:

 而(mCursor.moveToNext()){
    // 做一点事
}

3)现在,手动读取从光标的实际值,必须使用像的getString()的方法调用getInt()

 列表<串GT;串=新ArralyList<串GT;();
而(mCursor.moveToNext()){
    strings.add(mCursor.getString(mCursor.getColumnIndex(foodNameColumn))++ mCursor.getInt(mCursor.getColumnIndex(proteinColumn)));
}

4)在原来的循环,你不添加任何数据取值。你只是覆盖取值具有相同的价值一遍又一遍:

 而(mCursor.moveToNext()){
    S =新的String [] {foodNameColumn,proteinColumn,fatColumn,carbsColumn};
}

如果这个循环执行一次或一千倍,取值将永远是相同不要紧。

I'm trying to pull my data from my SQLite DB and display it in a listview, this is what I have so far but it only puts the first record in the listview. I think the "while (mCursor.moveToNext()){" bit needs changing but not sure how. The original code put each record in a textview on a new line each time.

    if (mCursor == null){
        mCursor.close();
        Log.w("cursor", "null cursor");
    }       

        mCursor.moveToFirst();
    String[] s = null;


    while (mCursor.moveToNext()){

        s = new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn };

        mCursor.moveToNext();
    }


    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
            R.layout.aa_four_column,
            mCursor, 
            s, 
            new int[] { R.id.txtCol1, R.id.txtCol2, R.id.txtCol3, R.id.txtCol4 }, 0);

    lvDB.setAdapter(adapter);

Update:

I've changed it so only this code is in the onCreate method, but the same thing happens, one item displayed when there are multiple things in the DB.

            mCursor = dataBase.select("SELECT * FROM " + TABLE_NAME);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
                    R.layout.aa_four_column,
                    mCursor, 
                    new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn }, 
                    new int[] { R.id.txtCol1, R.id.txtCol2, R.id.txtCol3, R.id.txtCol4 }, 0);

        lvDB.setAdapter(adapter);

aa_column_four.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/txtCol1"
        android:layout_width="181dp"
        android:layout_height="wrap_content"
        android:text="Column 1 text will end up here!" />

    <TextView
        android:id="@+id/txtCol2"
        android:layout_width="63dp"
        android:layout_height="wrap_content"
        android:text="Column 2 text will end up here!" />

    <TextView
        android:id="@+id/txtCol3"
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:text="Column 3 text will end up here!" />

    <TextView
        android:id="@+id/txtCol4"
        android:layout_width="104dp"
        android:layout_height="wrap_content"
        android:text="Column 4 text will end up here!" />

</LinearLayout>

DatabaseManager Class

    public class DataBaseManager extends SQLiteOpenHelper {

    //the MAIN package of your project
    private static String DB_PATH = "/data/data/com.example.activities/databases/";

    //the name of your database
    private static String DB_NAME = "DB_Nutrition";

    private static SQLiteDatabase mDataBase;

    private static DataBaseManager sInstance = null;
    // database version   
    private static final int DATABASE_VERSION = 1;

    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     */
    DataBaseManager() {
        super(ApplicationContextProvider.getContext(), DB_NAME, null, DATABASE_VERSION);

        try {
            createDataBase();
            openDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * Singleton for DataBase
     *
     * @return singleton instance
     */
    public static DataBaseManager instance() {

        if (sInstance == null) {
            sInstance = new DataBaseManager();
        }
        return sInstance;
    }


    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     *
     * @throws java.io.IOException io exception
     */
    private void createDataBase() throws IOException {

        boolean dbExist = checkDataBase();

        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method an empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {

        SQLiteDatabase checkDB = null;

        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {

            // database doesn't exist yet.

        }

        if (checkDB != null) {

            checkDB.close();

        }

        return checkDB != null;
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     *
     * @throws java.io.IOException io exception
     */
    public void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    private void openDataBase() throws SQLException {

        // Open the database
        String myPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    /**
     * Select method
     *
     * @param query select query
     * @return - Cursor with the results
     * @throws android.database.SQLException sql exception
     */
    public Cursor select(String query) throws SQLException {
        return mDataBase.rawQuery(query, null);
    }

    /**
     * Insert method
     *
     * @param table  - name of the table
     * @param values values to insert
     * @throws android.database.SQLException sql exception
     */
    public void insert(String table, ContentValues values) throws SQLException {
        mDataBase.insert(table, null, values);
    }

    /**
     * Delete method
     *
     * @param table - table name
     * @param where WHERE clause, if pass null, all the rows will be deleted
     * @throws android.database.SQLException sql exception
     */
    public void delete(String table, String where) throws SQLException {

        mDataBase.delete(table, where, null);

    }

    /**
     * Update method
     *
     * @param table  - table name
     * @param values - values to update
     * @param where  - WHERE clause, if pass null, all rows will be updated
     */
    public void update(String table, ContentValues values, String where) {

        mDataBase.update(table, values, where, null);

    }

    /**
     * Let you make a raw query
     *
     * @param command - the sql comand you want to run
     */
    public void sqlCommand(String command) {
        mDataBase.execSQL(command);
    }

    @Override
    public synchronized void close() {

        if (mDataBase != null)
            mDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

Error

03-03 15:42:13.894: E/SQLiteLog(9809): (14) cannot open file at line 30176 of [00bb9c9ce4]
03-03 15:42:13.894: E/SQLiteLog(9809): (14) os_unix.c:30176: (2) open(/data/data/com.example.activities/databases/DB_Nutrition) - 
03-03 15:42:13.904: E/SQLiteDatabase(9809): Failed to open database '/data/data/com.example.activities/databases/DB_Nutrition'.
03-03 15:42:13.904: E/SQLiteDatabase(9809): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at com.example.db_food.DataBaseManager.checkDataBase(DataBaseManager.java:228)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at com.example.db_food.DataBaseManager.createDataBase(DataBaseManager.java:193)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at com.example.db_food.DataBaseManager.<init>(DataBaseManager.java:163)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at com.example.db_food.DataBaseManager.instance(DataBaseManager.java:179)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at com.example.db_food.MyActivity.onCreate(MyActivity.java:63)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.app.Activity.performCreate(Activity.java:5104)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.os.Looper.loop(Looper.java:137)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at android.app.ActivityThread.main(ActivityThread.java:5041)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at java.lang.reflect.Method.invokeNative(Native Method)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at java.lang.reflect.Method.invoke(Method.java:511)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-03 15:42:13.904: E/SQLiteDatabase(9809):     at dalvik.system.NativeStart.main(Native Method)

解决方案

It looks like you want to display the data from a table in a ListView, so simply create an Adapter:

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        R.layout.aa_four_column,
        mCursor, 
        new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn }, 
        new int[] { R.id.txtCol1, R.id.txtCol2, R.id.txtCol3, R.id.txtCol4 }, 0);

lvDB.setAdapter(adapter);

(Use this code by itself, you don't need to use any of the other code below but you should read it to understand why most of your code won't do what you are trying to do.)


You have a few logical faults.

1) If an object is null you cannot reference any of its method:

if (mCursor == null){
    /* mCursor.close(); This will throw an NullPointerException! */
    Log.w("cursor", "null cursor");
    return;
}       

2) By calling moveToFirst() and moveToNext() before reading a row you skip the first record. Also you are calling moveToNext() twice between reading the records, so you are only reading every other one. Try this instead:

while (mCursor.moveToNext()){
    // Do something
}

3) Now to manually read an actual value from a Cursor you must use a method like getString() or getInt():

List<String> strings = new ArralyList<String>();
while (mCursor.moveToNext()){
    strings.add(mCursor.getString(mCursor.getColumnIndex(foodNameColumn)) + "  " + mCursor.getInt(mCursor.getColumnIndex(proteinColumn)));
}

4) In the original loop, you are not adding any data to s. You are just overwriting s with the same value over and over:

while (mCursor.moveToNext()){
    s = new String[] { foodNameColumn, proteinColumn, fatColumn, carbsColumn };
}

It doesn't matter if this loop executes once or a thousand times, s will always be the same.

这篇关于安卓:绑定数据从数据库的ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆