使用适配器显示SQLiteDatabase中的数据

时间:2012-01-30 18:38:15

标签: android sqlite cursor android-listview adapter

DBHelper类的代码:

class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_PATH = Environment.getDataDirectory()
            + "/data/test.data/databases/";
    private static final String DATABASE_NAME = "test.sqlite3";
    private static final int SCHEMA_VERSION = 1;
    public static final String TABLE_NAME = "terran_builds";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_OVERVIEW = "overview";

    public SQLiteDatabase dbSqlite;

    private final Context myContext;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

    public void createDatabase() {
        createDB();
    }

    private void createDB() {

        boolean dbExist = DBExists();
        if (!dbExist) {

            this.getReadableDatabase();

            copyDBFromResource();

        }

    }

    private boolean DBExists() {
        SQLiteDatabase db = null;

        try {
            String databasePath = DATABASE_PATH + DATABASE_NAME;
            db = SQLiteDatabase.openDatabase(databasePath, null,
                    SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        } catch (SQLiteException e) {
            Log.e("SqlHelper", "database not found");
        }

        if (db != null) {

            db.close();
        }

        return db != null ? true : false;
    }

    private void copyDBFromResource() {

        InputStream inputStream = null;
        OutputStream outStream = null;
        String dbFilePath = DATABASE_PATH + DATABASE_NAME;

        try {

            inputStream = myContext.getAssets().open(DATABASE_NAME);

            outStream = new FileOutputStream(dbFilePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
        } catch (IOException e) {

            throw new Error("Problem copying database from resource file.");
        }

    }

    public void openDataBase() throws SQLException {

        String myPath = DATABASE_PATH + DATABASE_NAME;
        dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {
        // TODO Auto-generated method stub

        if (dbSqlite != null) {
            dbSqlite.close();
        }
        super.close();
    }

    public Cursor getTerran() {

        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(TABLE_NAME);

        String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
                COLUMN_OVERVIEW };

        Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
                null, null, null, "name");

        return mCursor;
    }

    public String getName(Cursor c) {
        return (c.getString(1));
    }
}

Terran活动的代码:

public class Terran extends Activity {

    private DBHelper dbHelp = null;
    private Cursor ourCursor = null;
    private DBAdapter adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        try {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.terran_layout);

            // this is our listview element, obtained by id from our xml layout
            ListView myListView = (ListView) findViewById(R.id.tvterran);

            // create our database helper
            dbHelp = new DBHelper(this);
            // we call the create right afther initializing helper
            dbHelp.createDatabase();
            // open the database
            dbHelp.openDataBase();
            // get our cursor
            ourCursor = dbHelp.getTerran();

            // tell android to start managing cursor
            startManagingCursor(ourCursor);
            // create our adapter
            adapter = new DBAdapter(ourCursor);
            // set the adapter
            myListView.setAdapter(adapter);

        } catch (Exception e) {

            // send real error message
            Log.e("ERROR", "ERROR IN CODE: " + e.toString());

            e.printStackTrace();
        }
    }

    class DBAdapter extends CursorAdapter {
        DBAdapter(Cursor c) {
            super(Terran.this, c);
        }

        @Override
        public void bindView(View row, Context ctxt, Cursor c) {
            // TODO Auto-generated method stub
            terranHolder holder = (terranHolder) row.getTag();
            holder.populateFrom(c, dbHelp);

        }

        @Override
        public View newView(Context ctxt, Cursor c, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = getLayoutInflater();
            View row = inflater.inflate(R.layout.terran_layout, parent, false);
            terranHolder holder = new terranHolder(row);
            row.setTag(holder);
            return (row);
        }
    }

    static class terranHolder {
        private TextView name = null;

        terranHolder(View row) {
            name = (TextView) row.findViewById(R.id.tvterran);
        }

        void populateFrom(Cursor c, DBHelper r) {
            name.setText(r.getName(c));
        }
    }

}

Logcat例外:

01-30 20:07:13.765: E/ERROR(7153): ERROR IN CODE: java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153): java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153):     at com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
01-30 20:07:13.775: W/System.err(7153):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-30 20:07:13.775: W/System.err(7153):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-30 20:07:13.775: W/System.err(7153):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:1499)
01-30 20:07:13.775: W/System.err(7153):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-30 20:07:13.775: W/System.err(7153):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:731)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost.setCurrentTab(TabHost.java:403)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost.addTab(TabHost.java:242)

我无法从查询结果中生成ListView。根据我的调试情况,我了解错误发生在Terran line 46上。我无法弄清楚出了什么问题。与其他数据库一起测试,数据库连接有效。

2 个答案:

答案 0 :(得分:0)

com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)

放入一个断点并运行调试器。有些东西是空的,我猜这是列表。它就像46一样。

是的,我是金牌随机玩家。曾经是高钻石折腾。祝这个项目好运。

答案 1 :(得分:0)

您的ListView为空,这意味着您的布局中没有ListView具有该ID的内容,或者Android没有为列表生成正确的ID,而您有一个旧的是不正确的。

尝试刷新项目,从文件夹gen中删除R类,以便再次生成ID,重新启动IDE。