0

我正在尝试通过使用游标从 SQLite 获取数据来填充列表视图。但是即使光标有预期的行,列表视图中也不会显示任何数据。

这是代码:

public class ShowUsers extends Activity {

    UserDBAdapter db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_user_profile);

            db = new UserDBAdapter(getApplicationContext());
            db.open();

            populateListViewFromDB();

        } catch (Exception e) {
            Log.e("ERROR", "Error occured: " + e.toString());
            e.printStackTrace();
        }
    }

    @SuppressWarnings("deprecation")
    private void populateListViewFromDB() {
        Cursor cursor = db.getAllRecords();
        startManagingCursor(cursor);
        Log.i("MyApp", "Total users: " + cursor.getCount());
        Toast.makeText(getApplicationContext(),
                "Number of rows: " + cursor.getCount(), Toast.LENGTH_LONG)
                .show();

        String[] databaseColumnNames = new String[] { UserDBAdapter.KEY_NAME };
        int[] toViewIDs = new int[] { R.id.textViewName };

        SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,
                R.layout.users_layout, cursor, databaseColumnNames, toViewIDs);

        ListView list = (ListView) findViewById(R.id.listViewFromDB);
        list.setAdapter(myCursordapter);

    }

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

}

XML 文件:activity_user_profile.xml

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

    <ListView
        android:id="@+id/listViewFromDB"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#0000CC"
        android:dividerHeight="0.1dp" >
    </ListView>

</LinearLayout>

用户布局.xml:

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

<TextView
    android:id="@+id/textViewName"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="25dp"
    android:textColor="#0000FF"
    android:text="TextView" />

</LinearLayout>

UserDBAdapeter 文件

public class UserDBAdapter {
    public static final String KEY_USERID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_BIRTHATE = "birthdate";
    public static final String KEY_PUBAGE = "pubage";
    public static final String KEY_PASSWORD = "password";
    private static final String TAG = "UserDBAdapter";

    private static final String DATABASE_NAME = "UserDB";
    private static final String DATABASE_TABLE = "Users";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE = "create table if not exists "
            + DATABASE_TABLE
            + " (id integer primary key autoincrement, "
            + "name VARCHAR not null, birthdate date, pubage number, password VARCHAR );";

    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public UserDBAdapter(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }

    // ---opens the database---
    public UserDBAdapter open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    // ---closes the database---
    public void close() {
        DBHelper.close();
    }

    // ---insert a record into the database---
    public long insertRecord(String name, String password, String birthdate,
            int pubage) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_BIRTHATE, birthdate);
        initialValues.put(KEY_PUBAGE, pubage);
        initialValues.put(KEY_PASSWORD, password);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // ---deletes a particular record---
    public boolean deleteUser(long userId) {
        return db.delete(DATABASE_TABLE, KEY_USERID + "=" + userId, null) > 0;
    }

    // ---retrieves all the records---
    public Cursor getAllRecords() {
        return db.query(DATABASE_TABLE, new String[] { KEY_USERID, KEY_NAME,
                KEY_BIRTHATE, KEY_PUBAGE, KEY_PASSWORD }, null, null, null,
                null, null);
    }

    // ---retrieves a particular record---
    public Cursor getRecord(long userId) throws SQLException {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                KEY_USERID, KEY_NAME, KEY_BIRTHATE, KEY_PUBAGE, KEY_PASSWORD },
                KEY_USERID + "=" + userId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();

        }
        return mCursor;
    }

    // ---updates a record---
    public boolean updateRecord(long userId, String name, String birthdate,
            int pubage, String password) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_BIRTHATE, birthdate);
        args.put(KEY_PUBAGE, pubage);
        args.put(KEY_PASSWORD, password);
        return db.update(DATABASE_TABLE, args, KEY_USERID + "=" + userId, null) > 0;
    }
}

我能够成功地将数据从另一个活动插入到表中,并且能够从该活动中读取,但无法在列表视图中显示。请让我知道这里添加的代码在哪里以及有什么问题。

4

0 回答 0