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

发布于 2024-12-29 21:05:03 字数 7237 浏览 2 评论 0原文

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从查询结果生成。通过调试,我了解到错误出现在 第 46 行Terran 类中。我不知道出了什么问题。与其他数据库测试,数据库连接正常。

Code for the DBHelper class:

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));
    }
}

Code for the Terran activity:

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 exception:

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)

I can't get the ListView to generate from the query results. From my debugging I understand that the error is in the Terran class on line 46. I can't figure out what is wrong. Tested with other database, database connection works.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

锦欢 2025-01-05 21:05:03

您的 ListView 为 null,这意味着您的布局中没有具有该 id 的 ListView ,或者 android 没有为列表生成正确的 id,而您有一个旧的那是不正确的。

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

Your ListView is null that means that either don't have a ListView with that id in your layout or android didn't generate the proper id for the list and you have an old one that is incorrect.

Try to refresh the project, delete the R class from the folder gen so that the ID are generated again, restart the IDE.

誰認得朕 2025-01-05 21:05:03

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

放置一个断点并运行调试器。有些东西是空的,我猜它就是列表。大概是 46。

顺便说一句,我是黄金随机玩家。曾经是高钻石抛掷。祝项目顺利。

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

put a break point in and run the debugger. Something is null, and I'm guessing it's the list. It's on like 46.

Btw, I'm gold random player. Used to be high diamond Toss. Good luck with the project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文