如何在ListView中仅显示数据的一列?

时间:2019-04-29 12:58:06

标签: java android android-sqlite

我有一个包含信息的数据库,当我请求数据时,我只希望在ListView中显示一列,以便用户可以选择他们想要显示的信息

这是我的数据库助手:

public Cursor viewData () {

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("Select * from " +TABLE_NAME, null);

        return res;

    }

我的代码:

private void viewData() {
        Cursor cursor = db.viewData();

        if (cursor.getCount()== 0){
            Toast.makeText(this,"No Data To Show", Toast.LENGTH_LONG).show();
        }else {
            while(cursor.moveToNext()){
                listItems.add(cursor.getString(0));//index 1 is name, 0 is ID
            }
            String[] StringArray = new String[]{
                    DatabaseHelper.COL_2
            };
            int[] IntArray = new int[]{
                    R.id.textView1
            };

            adapter = new SimpleCursorAdapter(this, R.layout.item_layout, cursor, StringArray, IntArray);
            userList.setAdapter(adapter);

        }

    }

我的item_layout.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/mway">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="8dp"
        android:textColor="@color/colorPrimary"
        android:textSize="28sp"
        android:textStyle="bold"/>


</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

将布局的高度更改为:

android:layout_height="wrap_content"

因此它将是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/mway">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="8dp"
        android:textColor="@color/colorPrimary"
        android:textSize="28sp"
        android:textStyle="bold"/>
</RelativeLayout>